/// <reference lib="dom" />
import { readdir, readFile } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

// Use the replay agent's actual MCP credential, as a shell tool in that agent would.
// Credentials never enter the browser, report, screenshots, or uploaded driver.
async function agentMcp(threadId: string) {
  for (const pid of await readdir("/proc")) {
    if (!/^\d+$/.test(pid)) continue;
    try {
      const env = Object.fromEntries((await readFile(`/proc/${pid}/environ`, "utf8")).split("\0").map((item) => {
        const at = item.indexOf("=");
        return [item.slice(0, at), item.slice(at + 1)];
      }));
      if (env.T3CODE_THREAD_ID !== threadId || !env.T3_ACP_MCP_AUTHORIZATION) continue;
      let session = "";
      let id = 0;
      const rpc = async (method: string, params: unknown, notification = false) => {
        const response = await fetch(env.T3_ACP_MCP_ENDPOINT!, {
          method: "POST",
          headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: env.T3_ACP_MCP_AUTHORIZATION!, ...(session ? { "mcp-session-id": session, "mcp-protocol-version": "2025-06-18" } : {}) },
          body: JSON.stringify({ jsonrpc: "2.0", ...(notification ? {} : { id: ++id }), method, params }),
        });
        session = response.headers.get("mcp-session-id") ?? session;
        if (!response.ok) throw new Error(`MCP HTTP ${response.status}`);
        const body = await response.text();
        if (!body) return;
        const payload = body.startsWith("data:") || body.includes("\ndata:") ? JSON.parse(body.split("\n").filter((line) => line.startsWith("data:")).at(-1)!.slice(5)) : JSON.parse(body);
        if (payload.error) throw new Error(JSON.stringify(payload.error));
        return payload.result;
      };
      await rpc("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "sidebar-proof", version: "1" } });
      await rpc("notifications/initialized", {}, true);
      return async (name: string, args: unknown) => {
        const result = await rpc("tools/call", { name, arguments: args });
        if (result?.isError) throw new Error(JSON.stringify(result));
        return result?.structuredContent;
      };
    } catch (error) {
      if ((error as NodeJS.ErrnoException).code === "ENOENT" || (error as NodeJS.ErrnoException).code === "EACCES") continue;
      throw error;
    }
  }
  throw new Error("The seeded replay agent has no live MCP credential");
}

test("Prompted MCP threads appear directly in Working", WEB, async ({ t3, app, browser, screen }) => {
  await browser.addInitScript(() => localStorage.setItem("t3code:sidebar:working-expanded", "true"));
  const project = await t3.project("Launch demo");
  const caller = await t3.thread({ project, title: "Launch coordinator", messages: ["first"], model: "question" });
  const call = await agentMcp(caller.threadId);
  await t3.open("/settings/general");
  await screen.getByRole("switch", "Working section").check();
  await t3.open(caller);
  await expect(screen.getByRole("textbox").first()).toBeVisible();
  await expect(screen.getByRole("button", "Launch coordinator", { exact: false }).first()).toBeVisible();
  await browser.evaluate(() => {
    const seen: Record<string, string[]> = {};
    Object.assign(window, { sidebarProof: seen });
    const scan = () => {
      for (const row of document.querySelectorAll<HTMLElement>("[data-sidebar-row]")) {
        const title = row.textContent?.match(/(?:Launch|Batch) task [1-8]|Idle launch/)?.[0];
        if (!title) continue;
        const section = row.dataset.sidebarParent ?? "Inbox";
        const history = seen[title] ??= [];
        if (history.at(-1) !== section) history.push(section);
      }
    };
    new MutationObserver(scan).observe(document.body, { subtree: true, childList: true, attributes: true, characterData: true });
    scan();
  });
  const launched = Promise.all(Array.from({ length: 8 }, (_, i) => call("t3_thread_launch", { title: `Launch task ${i + 1}`, message: "Give me a short tour", modelSelection: { instanceId: "devReplay", model: "showcase" } })));
  await app.screenshot("concurrent-launches");
  await launched;
  await app.screenshot("launches-running");
  const batched = call("create_threads", { threads: Array.from({ length: 8 }, (_, i) => ({ title: `Batch task ${i + 1}`, prompt: "Give me a short tour", target: { providerInstanceId: "devReplay", model: "showcase" } })) });
  await app.screenshot("batch-launches");
  await batched;
  await call("t3_thread_launch", { title: "Idle launch" });
  await expect(screen.getByRole("button", "Idle launch", { exact: false }).first()).toBeVisible();
  await app.screenshot("prompted-and-idle");
  const observed = await browser.evaluate(() => (window as unknown as { sidebarProof: Record<string, string[]> }).sidebarProof);
  console.log("First rendered sidebar sections:", JSON.stringify(observed));
  expect(Object.entries(observed).filter(([title, history]) => title !== "Idle launch" && history[0] !== "shelf:working")).toEqual([]);
  expect(Object.keys(observed).filter((title) => title !== "Idle launch").length).toBe(16);
  expect(observed["Idle launch"]?.[0]).toBe("Inbox");
});
