
```ts
// Repro harness for issue 32848: runs the real DesktopBrowserHost in Electron, attaches a fresh
// <webview> per round, and connects Playwright through a ws relay when the host announces "attached".
import { app, BrowserWindow } from "electron";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { WebSocketServer, type WebSocket } from "ws";
import { chromium } from "/home/ubuntu/wt/issue-32848/node_modules/.pnpm/playwright-core@1.60.0/node_modules/playwright-core/index.js";
import * as Fs from "node:fs";

import { make as makeHost } from "/home/ubuntu/wt/issue-32848/apps/desktop/src/preview/DesktopBrowserHost.ts";

const ROUNDS = Number(process.env.ROUNDS ?? 40);
const OUT = process.env.OUT ?? "/tmp/issue-lead-32848-r1/harness/result.jsonl";
const SRC = process.env.SRC ?? "about:blank";
const threadId = "thread-1";

process.on("uncaughtException", (e) => { console.error("UNCAUGHT", e); app.exit(3); });
setTimeout(() => { console.error("WATCHDOG"); app.exit(4); }, Number(process.env.WATCHDOG_MS ?? 600000)).unref();
app.commandLine.appendSwitch("no-sandbox");
app.commandLine.appendSwitch("disable-gpu");

const step = (m: string) => Fs.appendFileSync(OUT + ".steps", `${Math.round(performance.now())} ${m}\n`);
const log = (o: unknown) => {
  const line = JSON.stringify(o);
  console.log(line);
  Fs.appendFileSync(OUT, line + "\n");
};

const withTimeout = <A>(p: Promise<A>, ms: number) =>
  Promise.race([
    p.then((v) => ({ ok: true as const, v })),
    new Promise<{ ok: false; v: string }>((r) => setTimeout(() => r({ ok: false, v: `HUNG >${ms}ms` }), ms)),
  ]).catch((e: unknown) => ({ ok: false as const, v: String(e).slice(0, 200) }));

app.whenReady().then(async () => {
  step("ready");
  const host = await Effect.runPromise(makeHost);
  step("host made");
  const sockets = new Map<string, WebSocket>();
  const attachedWaiters = new Map<string, () => void>();
  const attachedAt = new Map<string, number>();
  void Effect.runPromise(
    host.events.pipe(
      Stream.runForEach((bytes) =>
        Effect.sync(() => {
          for (const line of new TextDecoder().decode(bytes).split("\n")) {
            if (!line) continue;
            const event = JSON.parse(line);
            if (event.type === "attached") {
              attachedAt.set(event.tabId, performance.now());
              attachedWaiters.get(event.tabId)?.();
            } else if (event.type === "cdp") {
              sockets.get(event.tabId)?.send(event.message);
            }
          }
        }),
      ),
    ),
  );

  const wss = new WebSocketServer({ port: 0, host: "127.0.0.1" });
  await new Promise((r) => wss.once("listening", r));
  const port = (wss.address() as { port: number }).port;
  wss.on("connection", (socket, request) => {
    const tabId = new URL(request.url!, "http://x").searchParams.get("tab")!;
    sockets.set(tabId, socket);
    socket.on("message", (data) => {
      void Effect.runPromise(
        host.handleCommandLine(JSON.stringify({ type: "cdp", threadId, tabId, message: data.toString() })),
      );
    });
    socket.on("close", () => {
      if (sockets.get(tabId) === socket) sockets.delete(tabId);
      void Effect.runPromise(host.handleCommandLine(JSON.stringify({ type: "release", threadId, tabId })));
    });
  });

  const win = new BrowserWindow({ width: 1000, height: 700, show: true, webPreferences: { webviewTag: true } });
  step("window");
  await win.loadURL("data:text/html,<body style='margin:0'></body>");

  let failures = 0;
  for (let round = 0; round < ROUNDS; round++) {
    const tabId = `tab-${round}`;
    const guestReady = new Promise<Electron.WebContents>((resolve) => {
      win.webContents.once("did-attach-webview", (_e, wc) => resolve(wc));
    });
    const t0 = performance.now();
    await win.webContents.executeJavaScript(
      `{document.body.innerHTML='';const w=document.createElement('webview');w.style.cssText='width:900px;height:600px';w.src=${JSON.stringify(SRC)};document.body.appendChild(w);}0`,
    );
    step(`round ${round} appended`);
    const wc = await guestReady;
    step(`round ${round} guest`);
    let firstCommit = -1;
    let domReady = -1;
    wc.on("did-navigate", () => (firstCommit = performance.now() - t0));
    wc.once("dom-ready", () => (domReady = performance.now() - t0));
    // As prepareWebview: the control session attaches as soon as the guest attaches.
    wc.debugger.attach("1.3");
    const attached = new Promise<void>((r) => attachedWaiters.set(tabId, r));
    if (process.env.ATTACH_AFTER === "domready") await new Promise((r) => wc.once("dom-ready", () => r(null)));
    // As registerWebview on the renderer's did-attach.
    host.attach({ threadId, tabId }, { webContents: wc, debugger: wc.debugger });
    if (process.env.REPLACE_URL) void wc.loadURL(process.env.REPLACE_URL).catch(() => {});
    await attached;
    step(`round ${round} attached`);
    const attachMs = attachedAt.get(tabId)! - t0;
    let connectError: string | null = null;
    let browser: Awaited<ReturnType<typeof chromium.connectOverCDP>> | null = null;
    try {
      browser = await chromium.connectOverCDP(`ws://127.0.0.1:${port}/?tab=${tabId}`, { timeout: 15_000 });
    } catch (e) {
      connectError = String(e).split("\n")[0]!.slice(0, 200);
    }
    step(`round ${round} connected`);
    const connectedMs = performance.now() - t0;
    const result: Record<string, unknown> = { round, attachMs: Math.round(attachMs), connectedMs: Math.round(connectedMs) };
    if (browser) {
      const page = browser.contexts().flatMap((c) => c.pages())[0];
      if (!page) result.page = "none";
      else {
        await new Promise((r) => setTimeout(r, 300));
        result.mainEval = (await withTimeout(page.evaluate(() => 1 + 1), 3000)).v;
        result.locatorCount = (await withTimeout(page.locator("body").count(), 3000)).v;
        result.waitFor = (await withTimeout(page.waitForSelector("body", { timeout: 3000 }).then(() => "ok"), 3500)).v;
      }
      await withTimeout(browser.close(), 2000);
    }
    result.firstCommitMs = Math.round(firstCommit);
    result.domReadyMs = Math.round(domReady);
    if (connectError) result.connectError = connectError;
    const failed = connectError !== null || result.locatorCount !== 1 || result.waitFor !== "ok";
    result.failed = failed;
    if (failed) failures++;
    log(result);
    host.detach({ threadId, tabId });
    if (wc.debugger.isAttached()) wc.debugger.detach();
  }
  log({ summary: true, rounds: ROUNDS, failures, src: SRC, electron: process.versions.electron });
  app.exit(0);
});
```

```sh
#!/bin/bash
set -e
W=/home/ubuntu/wt/issue-32848
WSDIR=$W/node_modules/.pnpm/ws@8.22.0_bufferutil@4.1.0_utf-8-validate@6.0.6/node_modules
cd /tmp/issue-lead-32848-r1/harness
NODE_PATH=$W/apps/desktop/node_modules:$W/node_modules:$WSDIR $W/node_modules/.pnpm/esbuild@0.28.2/node_modules/esbuild/bin/esbuild harness.ts --bundle --platform=node --format=cjs --target=node22 --external:electron --external:/home/ubuntu/wt/issue-32848/node_modules/.pnpm/playwright-core@1.60.0/node_modules/playwright-core/index.js --external:bufferutil --external:utf-8-validate --outfile=harness.cjs --log-level=error
#!/bin/bash
# usage: run.sh <outdir> <rounds> [src]   (env LOAD=n spawns n CPU burners for the run)
W=/home/ubuntu/wt/issue-32848
OUTDIR=$1; mkdir -p "$OUTDIR"
burners=()
for ((i=0;i<${LOAD:-0};i++)); do (while :; do :; done) & burners+=($!); done
ROUNDS=$2 SRC=${3:-about:blank} OUT=$OUTDIR/result.jsonl headless-desktop $W/apps/desktop/node_modules/electron/dist/electron --no-sandbox --disable-gpu /tmp/issue-lead-32848-r1/harness > "$OUTDIR/electron.log" 2>&1
echo "exit $?" >> "$OUTDIR/electron.log"
for p in "${burners[@]}"; do kill "$p"; done
```
