import { expect } from "e2e";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("An ACP prompt RPC failure ends its pending foreground tool in both work-state modes", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("ACP RPC proof");
  const failures: boolean[] = [];
  for (const [provider, mode] of [["controlledOff", "off"], ["controlledOn", "on"]]) {
    const result = await runPromise(run(process.execPath, ["apps/server/src/bin.ts", "thread", "start", project, "Prepare the controlled session", "--title", `Work state ${mode}`, "--provider", provider!, "--model", "default", "--wait", "--json", "--base-dir", T3_HOME], {cwd:APP_DIR, env:{PATH:process.env.PATH,HOME:process.env.HOME}}));
    await t3.open(JSON.parse(result.stdout));
    const input = screen.getByRole("textbox");
    await input.fill("Run the controlled pending command and fail the prompt");
    await input.press("Enter");
    await screen.getByText("Controlled prompt RPC failure", {exact:false}).first().waitFor({state:"visible", timeout:60000});
    await screen.getByRole("button", "Dismiss error").tap();
    await screen.getByRole("button", "Dismiss error").waitFor({state:"hidden", timeout:30000});
    await app.screenshot(`work-state-${mode}-after-rpc-error`);
    failures.push(await browser.locator('[aria-label="Tool call failed"]').count() > 0);
  }
  await expect(failures).toEqual([true, true]);
});
