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

test("Stopping a turn away from its thread does not mark it Done", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo-project");
  const stopped = await t3.thread({ project, title: "Thread to stop", model: "showcase", messages: ["First tour", "Second tour"] });
  await t3.thread({ project, title: "Other thread", model: "showcase", messages: ["Another tour"] });
  await t3.open(stopped);
  await screen.getByTestId("composer-editor").waitFor();
  await runPromise(makeState(T3_HOME).cli(["thread", "send", stopped.threadId, "A tour to interrupt", "--json"]));
  await screen.getByRole("button", "Stop generation").waitFor();
  // Both clicks must happen before the server's interrupt response can record a visit.
  await browser.evaluate(() => {
    const stop = document.querySelector<HTMLButtonElement>('button[aria-label="Stop generation"]');
    const other = [...document.querySelectorAll<HTMLElement>('[role="button"][aria-label]')]
      .find((button) => button.getAttribute("aria-label")?.startsWith("Other thread,"));
    if (!stop || !other) throw new Error("Stop generation or Other thread control missing");
    stop.click();
    other.click();
  });
  // Let the interrupt arrive and the sidebar's working shelf exit grace elapse.
  await setTimeout(8_000);
  await app.screenshot("stopped-thread-sidebar");
  await expect(screen.getByRole("button", { name: /^Thread to stop,/ })).not.toHaveAccessibleName(/Done|Completed/);
});
