import { readFile } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Merging a completed fork previews context until the next turn", WEB, async ({t3, app, screen}) => {
  const stableScreenshot = async (label: string) => {
    let previous = await app.screenshot(`${label}-stability`);
    for (let attempt = 0; attempt < 10; attempt++) {
      await new Promise((resolve) => setTimeout(resolve, 500));
      const current = await app.screenshot(label);
      if ((await readFile(previous)).equals(await readFile(current))) return;
      previous = current;
    }
    throw new Error("The screenshot did not stabilize");
  };
  const project = await t3.project("context-demo");
  await t3.thread({project, title: "Source conversation", messages: ["Prepare the source conversation"]});
  await t3.open();
  await screen.getByRole("button", "Source conversation, Done, context-demo").tap();
  await screen.getByRole("button", "Fork from this response").last().tap();
  await screen.getByRole("textbox", "Message Source conversation fork").fill("Complete the fork work");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("first fixture turn complete", {exact:true}).nth(1).waitFor();
  await screen.getByRole("button", "Stop generation").waitFor({state:"hidden"});
  await screen.getByRole("button", "Merge back to Source conversation").tap();
  await screen.getByRole("textbox", "Message Source conversation", {exact:true}).waitFor();
  await stableScreenshot("merged-pending-context");
  const pendingPreviewCount = await screen.getByText("Context handoff pending", {exact:true}).count();
  await screen.getByRole("textbox").fill("Continue with the merged context");
  await screen.getByRole("textbox").press("Enter");
  await expect(screen.getByText("Context handoff pending", {exact:true})).toBeHidden();
  await expect(screen.getByText("Context handoff", {exact:true}).last()).toBeVisible();
  await screen.getByRole("button", "Stop generation").waitFor({state:"hidden"});
  await stableScreenshot("consumed-context");
  expect(pendingPreviewCount).toBe(1);
});
