import { expect } from "e2e";
import { writeFile } from "node:fs/promises";
import { test, WEB, makeState, runPromise } from "./t3.ts";
import { run } from "./shell.ts";
import { T3_HOME } from "../e2e.config.ts";

test("Queued messages share one folder checkpoint timeout", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("Shared checkpoint demo", {
    ".gitattributes": "*.dat filter=slow\n", "big.dat": "original\n",
  });
  await runPromise(run("git", ["config", "filter.slow.clean", "sleep 40; cat"], { cwd: project }));
  await writeFile(`${project}/big.dat`, "modified\n");
  const { cli } = makeState(T3_HOME);
  const threads: { threadId: string }[] = [];
  for (let i = 1; i <= 3; i++) {
    const started = await runPromise(cli(["thread", "start", project, "First message", "--title", `Shared folder ${i}`, "--provider", "devReplay", "--model", "multi-turn", "--json"]));
    const thread = JSON.parse(started.stdout);
    threads.push(thread);
    await runPromise(cli(["thread", "send", thread.threadId, "Queued follow-up"]));
  }
  await t3.open(threads[2]);
  await screen.getByText("first fixture turn complete", { exact: true }).waitFor({ timeout: 60_000 });
  await app.screenshot("queued-follow-up");
  await runPromise(run("sleep", ["40"]));
  await app.screenshot("forty-seconds-after-first-reply");
  // One 30-second Git timeout is expected; another per waiting capture is the defect.
  await expect(screen.getByText("second fixture turn complete", { exact: true })).toBeVisible({ timeout: 1_000 });
  await app.screenshot("follow-up-started");
});
