import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { runPromise, test, WEB } from "./t3.ts";

test("Diagnostics uses singular exit after one shell exits", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Terminal work", messages: ["Start"] });
  await t3.open("/settings/diagnostics");
  await screen.getByText(/\d+ starts? · 0 exits/).waitFor({ timeout: 40000 });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle terminal drawer").tap();
  const terminal = screen.getByLabel("Terminal input");
  const ready = () => runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    return yield* fs.readFileString(`${project}/shell-ready`);
  }).pipe(Effect.orElseSucceed(() => "")));
  await expect.poll(async () => {
    await terminal.focus();
    await browser.keyboard.type("echo ready > shell-ready");
    await browser.keyboard.press("Enter");
    return ready();
  }, { timeout: 30000 }).toBe("ready\n");
  await t3.open("/settings/diagnostics");
  await screen.getByRole("cell", "bash", { exact: true }).first().waitFor({ timeout: 40000 });
  await t3.open(thread);
  await terminal.focus();
  await browser.keyboard.type("exit");
  await browser.keyboard.press("Enter");
  await t3.open("/settings/diagnostics");
  await screen.getByText(/\d+ starts? · 1 exits?$/).waitFor({ timeout: 40000 });
  await app.screenshot("one-process-exit");
  await expect(screen.getByText(/\d+ starts? · 1 exit$/)).toBeVisible();
});
