import { expect } from "e2e";
import { writeFile } from "node:fs/promises";
import { setTimeout as delay } from "node:timers/promises";
import { join } from "node:path";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("A connection after editor discovery expires receives refreshed VS Code", WEB, async ({ app, browser, screen, t3 }) => {
  const project = await t3.project("editor-refresh");
  const thread = await t3.thread({ project, title: "Editor discovery", messages: ["Start"] });
  await browser.setViewport({ width: 1280, height: 800 });
  await t3.open(thread);
  const details = screen.getByRole("button", "Toggle thread details panel", { exact: true });
  if ((await details.getAttribute("aria-pressed")) !== "true") await details.tap();
  await screen.getByRole("button", "Choose editor", { exact: true }).tap();
  await app.screenshot("initial-editors-before-install");
  await browser.keyboard.press("Escape");
  // Match the report: a newly installed executable appears on the running server's PATH.
  // The executable is only discovered; no editor or provider output is simulated.
  await writeFile(join(T3_HOME, "bin", "code"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
  // This is the real production cache TTL, deliberately allowed to expire without clock mocks.
  await delay(65_000);
  await browser.evaluate(() => { window.location.reload(); });
  await screen.getByRole("button", "Choose editor", { exact: true }).waitFor({ timeout: 60_000 });
  // Give the background refresh the same 25 seconds as the reported reproduction.
  await delay(25_000);
  await screen.getByRole("button", "Choose editor", { exact: true }).tap();
  await app.screenshot("editors-on-first-connection-after-expiry");
  await expect(screen.getByRole("menuitem", "VS Code", { exact: true })).toBeVisible();
});
