/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("New worktree send shows progress while the layout-command read waits", WEB, async ({ t3, app, browser, screen }) => {
  await browser.setViewport({ width: 1280, height: 800 });
  await browser.addInitScript(() => {
    const state = { held: false, released: false };
    (window as unknown as { layoutWait: typeof state }).layoutWait = state;
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string" && data.includes('workspace.layoutCommands')) {
        state.held = true;
        setTimeout(() => { send.call(this, data); state.released = true; }, 6000);
        return;
      }
      return send.call(this, data);
    };
  });
  await t3.project("layout-demo", { "t3.json": "{}\n" });
  await t3.open();
  await screen.getByRole("combobox", "Workspace", { exact: true }).tap();
  await screen.getByRole("option", "New worktree", { exact: true }).tap();
  const composer = screen.getByRole("textbox");
  await composer.fill("say hello");
  await composer.press("Enter");
  await expect.poll(() => browser.evaluate(() => (window as unknown as {layoutWait: {held: boolean}}).layoutWait.held)).toBe(true);
  // Capture the same pending network state on both commits, before releasing the read.
  await browser.evaluate(() => new Promise(resolve => setTimeout(resolve, 1500)));
  await app.screenshot("layout-read-pending");
  try {
    await expect(screen.getByRole("button", "Preparing worktree", { exact: true })).toBeVisible({ timeout: 2000 });
  } finally {
    await expect.poll(() => browser.evaluate(() => (window as unknown as {layoutWait: {released: boolean}}).layoutWait.released)).toBe(true);
    await browser.locator('[data-message-role="user"]').filter({ hasText: "say hello" }).waitFor();
    await app.screenshot("layout-read-released");
  }
});
