/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("A side chat subagent opens its parent in the main thread panel", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const main = await t3.thread({ project, title: "Main thread", messages: ["Main conversation"] });
  await t3.open(main);
  // Use the same public orchestration commands as the client to seed real lineage.
  const rpc = async (tag: string, payload: unknown) => browser.evaluate(async ({ tag, payload }) => {
    const socket = new WebSocket(`${location.origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=2`);
    return await new Promise<any>((resolve, reject) => {
      socket.onopen = () => socket.send(JSON.stringify({ _tag: "Request", id: "1", tag, payload, headers: [] }));
      socket.onerror = () => reject(new Error("Scenario RPC connection failed"));
      socket.onmessage = event => {
        const messages = JSON.parse(event.data);
        for (const message of Array.isArray(messages) ? messages : [messages]) {
          if (message._tag === "Ping") socket.send(JSON.stringify({ _tag: "Pong" }));
          if (message._tag === "Exit" && message.requestId === "1") {
            socket.close();
            if (message.exit._tag === "Success") resolve(message.exit.value);
            else reject(new Error(JSON.stringify(message.exit)));
          }
        }
      };
    });
  }, { tag, payload });
  const dispatch = (command: object) => rpc("orchestration.dispatchCommand", { commandId: crypto.randomUUID(), ...command });
  const sideId = crypto.randomUUID();
  await dispatch({ type: "thread.fork", sourceThreadId: main.threadId, targetThreadId: sideId, sourcePoint: { type: "latest_stable" }, sideChat: true, title: "Subagent Launch Request", createdBy: "user", creationSource: "web" });
  // Approval replay holds the parent run open while the real delegation command starts its child.
  await dispatch({ type: "thread.runtime-mode.set", threadId: sideId, runtimeMode: "approval-required" });
  await dispatch({ type: "thread.model-selection.set", threadId: sideId, modelSelection: { instanceId: "devReplay", model: "approval" } });
  await dispatch({ type: "message.dispatch", threadId: sideId, messageId: crypto.randomUUID(), text: "Launch a subagent", attachments: [], dispatchMode: { type: "start_immediately" }, createdBy: "user", creationSource: "web" });
  const parent = await rpc("orchestration.getThreadProjection", { threadId: sideId });
  const run = parent.runs.at(-1);
  await dispatch({ type: "delegated_task.request", parentThreadId: sideId, parentRunId: run.id, parentNodeId: run.rootNodeId, task: "Reply pong", title: "Pong subagent check", modelSelection: { instanceId: "devReplay", model: "multi-turn" }, runtimeMode: "approval-required", interactionMode: "default", createdBy: "user", creationSource: "mcp" });
  const delegated = await rpc("orchestration.getThreadProjection", { threadId: sideId });
  const childId = delegated.subagents.at(-1).childThreadId;
  const destinations: Array<{ control: string; threadId: string; sideChatSelected: boolean }> = [];
  for (const control of ["header-breadcrumb", "timeline-parent-link", "lineage-row"]) {
    await t3.open({ threadId: childId });
    const breadcrumb = screen.getByRole("button", "Open parent thread: Subagent Launch Request");
    await breadcrumb.waitFor();
    if (control === "header-breadcrumb") {
      await app.screenshot("subagent-start");
      await breadcrumb.tap();
    } else if (control === "timeline-parent-link") {
      await screen.getByRole("button", "Open parent thread", { exact: true }).tap();
    } else {
      await screen.getByRole("button", /^Subagent Launch Request /).tap();
    }
    await breadcrumb.waitFor({ state: "hidden" });
    await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
    await app.screenshot(control + "-destination");
    destinations.push(await browser.evaluate(({ control, sideId }) => ({
      control,
      threadId: decodeURIComponent(location.pathname.split("/").at(-1) ?? ""),
      sideChatSelected: document.querySelector(`[data-side-chat-pane="${sideId}"]`) !== null,
    }), { control, sideId }));
  }
  expect(destinations).toEqual(["header-breadcrumb", "timeline-parent-link", "lineage-row"].map(control => ({ control, threadId: main.threadId, sideChatSelected: true })));
});
