/// <reference lib="dom" />
// Real Codex proof: replay intentionally drops post-reply background frames.
import * as fs from "node:fs/promises";
import * as path from "node:path";
import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("An open preview refreshes when an earlier background command finishes late", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo", { "note.txt": "OLD CONTENTS v1\nThe background command has not finished.\n" });
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({
      patch: { defaultRuntimeMode: "full-access" },
      providerInstanceMutation: { operation: "upsert", instanceId: ProviderInstanceId.make("codex"), instance: {
        driver: ProviderDriverKind.make("codex"), enabled: true,
        config: { setupMode: "existing", binaryPath: "/usr/local/bin/codex", homePath: path.join(process.env.HOME!, ".codex"), customModels: ["gpt-6-luna"] }
      } }
    });
  }).pipe(Effect.scoped));
  const { cli } = makeState(T3_HOME);
  const started = await runPromise(cli(["thread", "start", project, "Reply only READY. Do not use tools.", "--title", "Background preview refresh", "--provider", "codex", "--model", "gpt-6-luna", "--wait", "--json"]));
  const thread = JSON.parse(started.stdout) as { threadId: string };
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", { exact: true }).tap();
  const openFile = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const row = host.shadowRoot?.querySelector<HTMLElement>('[data-item-path="note.txt"]');
      if (row) { row.click(); return true; }
    }
    return false;
  });
  const preview = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return "";
  });
  // Setup waits are not expectations about the bug.
  for (let i = 0; i < 30 && !(await openFile()); i++) await new Promise(r => setTimeout(r, 200));
  for (let i = 0; i < 30 && !(await preview()).includes("OLD CONTENTS v1"); i++) await new Promise(r => setTimeout(r, 200));
  if (!(await preview()).includes("OLD CONTENTS v1")) throw new Error("Initial preview did not open");
  await app.screenshot("preview-before-command");
  const prompt = "Reproduce a background command timing issue. Start this exact command as a background terminal command, returning after 1000 ms: sleep 45 && printf 'NEW CONTENTS v2\\nThe earlier background command finished rewriting this file.\\n' > note.txt . While it sleeps, run a separate command echo quick-check. Then reply exactly STARTED and end your turn immediately, without waiting or polling for the background command. When automatically notified that the background command completed, write a 1200-word story about a lighthouse, with no tools. Do not read or modify any other files. Use exec_command's yield_time_ms=1000 for the sleep command so it remains a tracked background task, not shell ampersand.";
  await runPromise(cli(["thread", "send", thread.threadId, prompt]));
  let rewritten = false;
  for (let i = 0; i < 150; i++) {
    if ((await fs.readFile(path.join(project, "note.txt"), "utf8")).includes("NEW CONTENTS v2")) { rewritten = true; break; }
    await new Promise(r => setTimeout(r, 1000));
  }
  if (!rewritten) throw new Error("Real background command did not rewrite note.txt");
  // Give the completion notification and file read five seconds, while the continuation streams.
  await new Promise(r => setTimeout(r, 5000));
  await app.screenshot("preview-after-background-completion");
  await expect.poll(preview, { timeout: 3000 }).toContain("NEW CONTENTS v2");
});
