/// <reference lib="dom" />
import * as fs from "node:fs/promises";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("Reopening reconciles a cached waiting delegated child with the completed server record", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("Cache reconciliation");
  const path = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await fs.readFile(path, "utf8"));
  settings.providerInstances.opencode = {driver: "opencode", enabled: true};
  await fs.writeFile(path, JSON.stringify(settings));
  const {cli} = makeState(T3_HOME);
  const started = await runPromise(cli(["thread", "start", project,
    "Call orchestrator_capabilities once, then delegate_task exactly once with title Pong response, task Reply exactly PONG, target providerInstanceId devReplay model multi-turn, mode wait. After the child finishes reply DONE. Do not do any other work.",
    "--title", "Completed delegated child", "--provider", "opencode", "--model", "openai/gpt-5.6-luna", "--wait", "--json"]));
  const {threadId} = JSON.parse(started.stdout);
  await t3.open({threadId});
  await screen.getByText("Previous agents", {exact: true}).waitFor();
  // Keep the server authoritative and completed. Recreate the stale cache left by an
  // unjournalled settlement: its cursor is unchanged, but its child is still waiting.
  await browser.evaluate(async (threadId: string) => {
    const db = await new Promise<IDBDatabase>((resolve, reject) => {
      const request = indexedDB.open("t3code:connection-runtime");
      request.onsuccess = () => resolve(request.result);
      request.onerror = () => reject(request.error);
    });
    for (let attempt = 0; attempt < 200; attempt++) {
      const found = await new Promise<boolean>((resolve, reject) => {
        const request = db.transaction("thread").objectStore("thread").getAll();
        request.onsuccess = () => resolve(request.result.some(raw => JSON.parse(raw).threadId === threadId));
        request.onerror = () => reject(request.error);
      });
      if (found) {db.close(); return null;}
      await new Promise(resolve => setTimeout(resolve, 50));
    }
    db.close(); throw new Error("Thread cache never persisted");
  }, threadId);
  await browser.evaluate(async (threadId: string) => {
    const db = await new Promise<IDBDatabase>((resolve, reject) => {
      const r = indexedDB.open("t3code:connection-runtime");
      r.onsuccess = () => resolve(r.result); r.onerror = () => reject(r.error);
    });
    await new Promise<void>((resolve, reject) => {
      const tx = db.transaction("thread", "readwrite");
      const store = tx.objectStore("thread");
      const r = store.openCursor(); let found = false;
      r.onsuccess = () => {
        const cursor = r.result; if (!cursor) {if (!found) reject(new Error("Thread cache not saved")); return;}
        const data = JSON.parse(cursor.value);
        if (data.threadId === threadId) {
          if (data.snapshot.projection.subagents.length !== 1) throw new Error("Expected one delegated child");
          const child = data.snapshot.projection.subagents[0];
          if (child.origin !== "app_owned" || child.status !== "completed") throw new Error("Child is not completed");
          child.status = "waiting"; child.completedAt = null;
          if (child.completionDelivery) child.completionDelivery.state = "pending";
          const node = data.snapshot.projection.nodes.find((n: {id: string}) => n.id === child.id);
          if (node) {node.status = "running"; node.completedAt = null;}
          cursor.update(JSON.stringify(data)); found = true;
        }
        cursor.continue();
      };
      tx.oncomplete = () => resolve(); tx.onerror = () => reject(tx.error);
    });
    db.close();
    return null;
  }, threadId);
  await browser.reload();
  await screen.getByText("Completed delegated child", {exact: true}).first().waitFor();
  try {
    await expect(screen.getByText("Previous agents", {exact: true})).toBeVisible();
    await expect(screen.getByRole("button", "Stop subagent Pong response", {exact: true})).not.toBeVisible();
  } finally {
    await screen.getByText("Syncing messages...", {exact: true}).waitFor({state: "hidden"});
    await app.screenshot("lineage-after-reopening-cached-waiting-child");
  }
});
