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

test("A stopped turn keeps its own diff after another turn", WEB, async ({t3,app,browser,screen}) => {
  const project = await t3.project("demo", {"notes.txt":"Original\n"});
  const thread = await t3.thread({project,title:"Stopped turn changes",messages:["Read the project"],model:"todo-list"});
  await t3.open(thread);
  const model = async (name: string) => {
    await browser.locator("[data-chat-provider-model-picker-label]").first().tap();
    await screen.getByPlaceholder("Search models...").fill(name);
    await screen.getByRole("option", new RegExp(`^${name}`)).tap();
    await browser.keyboard.press("Escape");
  };
  const send = async (text: string) => {
    await screen.getByRole("textbox").fill(text);
    await screen.getByRole("textbox").press("Enter");
  };
  await model("Question");
  await send("Change notes.txt");
  await screen.getByText("Input requested", {exact:true}).waitFor();
  await writeFile(`${project}/notes.txt`, "Changed by stopped turn\n");
  await screen.getByRole("button", "Stop generation", {exact:true}).tap();
  await screen.getByText("Stopped by user", {exact:false}).waitFor();
  await screen.getByRole("button", "Toggle right panel", {exact:true}).tap();
  await screen.getByText("Diff", {exact:true}).tap();
  await screen.getByRole("button", /^Diff scope:/).tap();
  await screen.getByRole("menuitemradio", "Latest turn", {exact:true}).tap();
  // Wait for the query to settle on either side before capturing it.
  await browser.locator('button[aria-label="Expand notes.txt"], button[aria-label="Collapse notes.txt"], :text("Failed to load turn diff")').first().waitFor();
  await app.screenshot("latest-stopped-turn");
  const latest = await screen.getByRole("button", /^(Expand|Collapse) notes\.txt$/).count();
  await model("Plan and reads");
  await send("Read once more");
  await screen.getByRole("button", "Stop generation", {exact:true}).waitFor({state:"hidden"});
  await screen.getByRole("button", /^Diff scope:/).tap();
  await screen.getByRole("menuitem", "Turn", {exact:true}).tap();
  await screen.getByRole("menuitemradio", /^Turn 2/).tap();
  await browser.locator('button[aria-label="Expand notes.txt"], button[aria-label="Collapse notes.txt"], :text("Failed to load turn diff")').first().waitFor();
  const expand = screen.getByRole("button", "Expand notes.txt", {exact:true});
  if (await expand.count()) await expand.tap();
  await app.screenshot("explicit-stopped-turn-after-later-turn");
  const lines = await browser.evaluate(() => Array.from(document.querySelectorAll("diffs-container")).map(h=>h.shadowRoot?.textContent ?? "").join("\n"));
  expect({latest, changed:lines.includes("Changed by stopped turn"), original:lines.includes("Original")}).toEqual({latest:1,changed:true,original:true});
});
