import { expect } from "e2e";
import { setTimeout } from "node:timers/promises";
import { test, WEB, makeState, runPromise } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";

test("Foreground native children identify what the open parent run is waiting for", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Foreground tasks", { "a.txt": "Alpha\n", "b.txt": "Bravo\n", "c.txt": "Charlie\n" });
  const { cli } = makeState(T3_HOME);
  const waiting: boolean[] = [];
  for (const model of ["three", "single", "hidden"]) {
    const launched = await runPromise(cli(["thread", "start", project, "Use the task tool to launch foreground general subagents. Run sleep 150 and read the files. Announce dispatch, wait for all children, then summarize.", "--title", `${model} foreground case`, "--provider", "foregroundReplay", "--model", model, "--json"]));
    const { threadId } = JSON.parse(launched.stdout);
    await t3.open({ threadId });
    await screen.getByText(model === "single" ? "Dispatching one subagent." : "Dispatching three subagents.", { exact: false }).first().waitFor({ state: "visible" });
    await screen.getByText("Syncing messages...", { exact: false }).first().waitFor({ state: "hidden" });
    if (model === "hidden") {
      await browser.evaluate(() => {
        const key = "t3code:client-settings:v1";
        const settings = JSON.parse(localStorage.getItem(key) ?? "{}");
        localStorage.setItem(key, JSON.stringify({ ...settings, toolCallVisibility: "hideAll" }));
      });
      await t3.open({ threadId });
      await screen.getByText("Dispatching three subagents.", { exact: false }).first().waitFor({ state: "visible" });
      await screen.getByText("Syncing messages...", { exact: false }).first().waitFor({ state: "hidden" });
    }
    const details = screen.getByRole("button", "Toggle thread details panel");
    if (await details.getAttribute("aria-pressed") === "true") await details.tap();
    await app.screenshot(`${model}-stable-first`);
    await setTimeout(500);
    await app.screenshot(`${model}-foreground-subagents`);
    if (model === "hidden") await expect(screen.getByText("Thinking", { exact: true, visible: true }).first()).toBeVisible();
    else waiting.push(await screen.getByText(model === "single" ? "Waiting on a subagent" : "Waiting on 3 subagents", { exact: true, visible: true }).first().isVisible());
  }
  await expect(waiting).toEqual([true, true]);
});
