import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Missing delegated task IDs list recoverable tasks", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Diagnostic demo");
  const thread = await t3.thread({ project, title: "Delegated task recovery", model: "default", messages: ["SETUP_PARENT"] });
  await t3.open(thread);
  await screen.getByRole("textbox").fill("PROOF_PARENT: Start an async delegate, probe childThreadId and nonexistent task IDs, then recover using the listed taskId.");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("PROOF_COMPLETE", { exact: false }).scrollIntoView();
  for (const [heading, label] of [
    ["task_status with childThreadId", "status-child-thread-id"],
    ["task_status with nonexistent ID", "status-nonexistent-id"],
    ["task_cancel with nonexistent ID", "cancel-nonexistent-id"],
  ]) {
    await screen.getByText(heading, { exact: false }).scrollIntoView();
    await browser.evaluate((heading) => {
      const target = Array.from(document.querySelectorAll("h3")).find((node) => node.textContent?.includes(heading));
      target?.scrollIntoView({ block: "start", behavior: "instant" });
      return null;
    }, heading);
    await new Promise((resolve) => setTimeout(resolve, 700));
    await app.screenshot(label);
  }
  await screen.getByText("Retry with", { exact: false }).scrollIntoView();
  await new Promise((resolve) => setTimeout(resolve, 700));
  await browser.evaluate(() => {
    Array.from(document.querySelectorAll("h3")).find((node) => node.textContent?.includes("Retry with"))?.scrollIntoView({ block: "start", behavior: "instant" });
    return null;
  });
  await new Promise((resolve) => setTimeout(resolve, 700));
  await app.screenshot("recovery");
  await expect(screen.getByText("Open delegated tasks on this thread:", { exact: false }).last()).toBeVisible();
  await expect(screen.getByText("Retry with listed taskId", { exact: false })).toBeVisible();
});
