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

test("fx Full access and return to Supervised", WEB, async ({t3, app, screen, browser}) => {
  await t3.project("demo");
  await t3.open();
  await screen.getByText("main", {exact:true}).first().textContent();
  await app.screenshot("initial-state");
  await screen.getByRole("button", /^Permissions:/).tap();
  await app.screenshot("permission-picker");
  await expect.soft(screen.getByRole("menuitemradio", "Full access", {exact: true})).toBeVisible();
  await browser.keyboard.press("Escape");
  await screen.getByRole("textbox").fill("Create proof.txt containing ACCESS_PROOF. Then run the shell command: printf SHELL_PROOF. Do both now, then reply PROOF_DONE.");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByRole("button", "Stop generation").textContent();
  await expect.poll(() => browser.evaluate(() => [...document.querySelectorAll("button")].some(b=>b.textContent?.trim()==="Approve") || !document.querySelector('[aria-label="Stop generation"]')), {timeout:120000}).toBe(true);
  await app.screenshot("first-action");
  // Base asks for approval. Head completes without a response from the driver.
  const approval = await browser.evaluate(() => [...document.querySelectorAll('button')].some(b=>b.textContent?.trim()==='Approve'));
  await expect.soft(approval).toBe(false);
  if (approval) await screen.getByRole("button", "Stop generation").tap();
  await expect(screen.getByRole("button", "Stop generation")).toBeHidden({timeout:120000});
  await app.screenshot("first-turn-complete");
  await screen.getByRole("button", /^Default \(grok-3-mini\)/).tap();
  await screen.getByRole("button", /^Permissions:/).last().tap();
  await screen.getByRole("menuitemradio", "Supervised", {exact:true}).tap();
  await browser.keyboard.press("Escape");
  await screen.getByRole("textbox").fill("Run this new shell command now: printf SUPERVISED_PROOF. Do not just describe it.");
  await screen.getByRole("textbox").press("Enter");
  await expect(screen.getByRole("button", "Approve", {exact:true}).first()).toBeVisible({timeout:120000});
  await app.screenshot("supervised-approval");
});
