import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Force stop ends a stranded run while sibling work continues", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("force-stop-demo");
  const cli = makeState(T3_HOME).cli;
  const start = async (title: string, prompt: string) => {
    const result = await runPromise(cli(["thread", "start", project, prompt, "--title", title, "--provider", "devReplay", "--model", "multi-turn", "--json"]));
    return JSON.parse(result.stdout) as { threadId: string };
  };
  const target = await start("Stranded target", "Finish the provider turn");
  await t3.open(target);
  await screen.getByText("fixture turn complete", { exact: false }).first().waitFor({ state: "visible" });
  const sibling = await start("Working sibling", "KEEP_WORKING");
  await app.screenshot("stranded-before-stop");
  const stop = screen.getByRole("button", "Stop generation");
  await stop.tap();
  await screen.getByRole("button", "Force stop", { exact: true }).waitFor({ state: "visible", timeout: 45000 });
  await app.screenshot("stop-unresponsive");
  await screen.getByRole("button", "Force stop", { exact: true }).tap();
  try {
    await expect(stop).toBeHidden();
  } finally {
    await screen.getByText("Turn stopped; the agent process kept running", { exact: true }).waitFor({ state: "hidden" });
    await app.screenshot("after-force-stop");
  }
  await t3.open(sibling);
  await screen.getByText("Sibling heartbeat 23.", { exact: false }).first().waitFor({ state: "visible" });
  await app.screenshot("sibling-keeps-working");
  await expect(screen.getByRole("button", "Stop generation")).toBeVisible();
});
