Remove outdated plans for shared HTTP MCP server and visible preview browser automation via CDP. Consolidate and refine the architecture and process models for the new preview automation framework, including updated contracts, server-side broker, and desktop integration. Introduce new WS methods for client communication and enhance security measures for token management. Ensure comprehensive testing strategies are in place for all components.

This commit is contained in:
Julius Marminge authored and Theo Browne committed 2026-06-13 22:18:37 -07:00
1 parent d4ba9e9618
commit cd91ec75f3
28 files changed
-6147

No files matched your search

@@ -1,35 +0,0 @@
# ADR 006: Renderer Failure Boundary
## Status
Accepted, revising ADR 001 terminology and failure handling.
## Decision
Keep the renderer-hosted Electron `<webview>` for the next implementation iteration because it supports normal renderer composition, annotations, and the selected covered-surface recording strategy.
Do not describe this as process-durable. It is:
- durable across React unmounts, route changes, panel closure, and tab switching;
- not durable across host-renderer reload, host-renderer crash, window destruction, or application restart.
The logical `BrowserSession` and `BrowserTab` records survive host loss. The live page process state does not. When the host disappears, the environment server marks the host unavailable and tabs as lost rather than pretending the DOM, JavaScript heap, sockets, and history can be recovered.
## Evidence
The `renderer-reload` spike created both a renderer `<webview>` and a main-owned `WebContentsView`, modified state in each, and reloaded the host renderer:
- `<webview>` guest id changed from `2` to `4`, the first guest was destroyed, and count reset from `1` to `0`;
- `WebContentsView` retained id `3`, remained alive, and retained count `1`.
## Product Requirements
- Show an explicit "browser page was lost" state with last known URL, title, screenshot, and artifacts.
- Offer restart-and-restore as a new browser process, clearly reporting which state cannot be restored.
- Never silently bind a replacement guest to the old live-process identity.
- Bind every desktop browser host to one window id and define window-close as host loss.
- A future multi-window implementation must explicitly move or restart sessions; `<webview>` elements cannot be reparented across renderer documents.
## Rejected for This Iteration
Migrating the collaborative surface to `WebContentsView` solely for renderer-reload survival remains rejected because Phase 0 found hidden/detached recording and overlay composition unsuitable. The trade is now explicit: collaborative composition and recording are prioritized over host-renderer reload survival.
@@ -1,40 +0,0 @@
# ADR 007: Playwright Injected Runtime
## Status
Accepted as the initial implementation direction; supersedes the bespoke interpretation of ADR 002.
## Decision
Load a version-pinned Playwright injected runtime into each guest frame through the persistent CDP connection. Use it for selector parsing, role/name/text/test-id resolution, shadow DOM traversal, element-state checks, hit-target checks, and locator re-resolution.
T3 continues to own:
- browser sessions, hosts, tabs, command queues, authorization, and cancellation;
- CDP target discovery and per-frame execution contexts;
- native input dispatch, navigation, dialogs, downloads, artifacts, and remote reachability;
- the stable T3 automation contract exposed to agents.
Do not expose Playwright internal objects directly as the product API.
## Evidence
The `injected-runtime` spike extracted the runtime bundled with installed Playwright 1.60.0 and evaluated it inside the real Electron guest over CDP:
- injected source size: `307,101` bytes;
- install time: approximately `6.5–8.5 ms` across the recorded runs;
- role/name locator matched the button;
- role/name locator pierced an open shadow root;
- the same locator re-resolved after the input element was replaced;
- same-origin frames still require a separate injected runtime and routing context.
## Constraints
- Playwright's injected runtime is internal and version-coupled. Pin its version and run compatibility fixtures on upgrades.
- OOPIFs remain separate CDP targets. The Browser Control Service must enable target auto-attach and maintain frame-to-session routing.
- Locators are durable query descriptions resolved at action time. Snapshot node references are optional, short-lived accelerators only.
- The T3 adapter must compare key behavior against real Playwright tests for actionability, shadow DOM, frames, rerenders, and strictness.
## Fallback
If a future Playwright release makes the injected runtime impractical to consume, retain the T3 contract and replace only the internal locator provider. Do not leak the vendored runtime across architecture boundaries.
@@ -1,32 +0,0 @@
# ADR 008: Covered Recording Is Provisional
## Status
Accepted with concurrency and platform gates.
## Decision
Keep CDP screencast plus Chromium MediaRecorder and the covered full-size parking surface for the first recording implementation.
Default to one actively recorded tab per desktop window until multi-tab budgets are measured. Hidden idle tabs remain offscreen; hidden recording tabs remain composited and covered.
## Evidence
The `recording-endurance` spike recorded a `1600×1200` covered webview for ten seconds at a requested 12 fps:
- 111–112 sampled frames, approximately 11.1–11.2 fps across the recorded runs;
- 9.98-second seekable H.264 MP4;
- main-process CPU sample approximately 3.5–3.8%;
- observed renderer working sets approximately 146 MiB and 99 MiB, plus GPU working set approximately 149 MiB.
This is stronger than the original 800×600 proof, but it is not a production concurrency budget.
## Required Before Raising Concurrency
- 30-minute soak with active timers, animation, HMR, and navigation;
- two and four simultaneous recording tabs;
- Retina device-scale-factor coverage;
- window resize, minimization, macOS Spaces, sleep/wake, and display changes;
- explicit `backgroundThrottling` policy and regression tests;
- proof that the cover cannot receive or leak pointer input to the parked guest;
- bounded frame queues with drop metrics and encoder-failure finalization.
@@ -1,33 +0,0 @@
# ADR 009: Loopback Is Not an Authorization Boundary
## Status
Accepted, revising ADR 004.
## Threat
A listener bound to `127.0.0.1` can be reached by any local process. Browser content can also cause cross-origin requests to it even when CORS prevents reading the response. Possession of a loopback port therefore cannot authorize access to a remote environment.
## Evidence
The `run-tunnel-security-spike.mjs` probe loaded an unrelated page in Chromium and issued a `no-cors` request to another loopback port. The request reached the preview listener. The request did not include an `Origin` header, so origin-header validation alone would not reject it.
The same probe confirmed:
- local storage survives when the exact loopback authority remains stable;
- changing only the port creates a new origin and loses that storage;
- an absolute HTTPS redirect passes through unchanged and escapes the loopback authority.
## Decision
- Allocate one stable local authority per environment/project/target tuple for the lifetime of its origin grant.
- Treat the authority as a browser capability, not a random open port.
- The desktop browser host must restrict navigation to authorities granted to that browser session and prevent unrelated tabs from using preview authorities.
- Environment tunnel grants remain scoped to environment, session, target host, and target port, but server-side grants do not protect the desktop listener from local callers.
- Add a desktop-side connection broker that verifies the connecting browser guest belongs to the authorized session. A bare TCP listener without browser attribution is insufficient for the final design.
- Absolute redirects, OAuth callbacks, HTTPS upstreams, service workers, and configured public origins require explicit compatibility policy rather than a "no rewriting" guarantee.
- Replace one-WebSocket-per-TCP-stream before relay rollout unless load testing proves the relay limits acceptable. The target design is bounded multiplexing over dedicated authenticated tunnel connections.
## Open Implementation Choice
The browser-attribution mechanism needs a dedicated spike. Candidates include an Electron protocol/proxy integration, per-session proxy configuration, or another browser-mediated connection path that preserves ordinary application semantics while identifying the requesting guest. Port secrecy is explicitly rejected.
@@ -1,23 +0,0 @@
# ADR 010: Human Input Interruption
## Status
Accepted for the initial lease implementation, with regression coverage.
## Decision
Observe native user keyboard and pointer activity at the Electron guest/window boundary and revoke or pause the conflicting automation lease. Do not implement a timing-based suppression window unless a supported platform demonstrates that CDP-dispatched input is reported through the same native event path.
## Evidence
The `input-origin` spike attached Electron's `before-input-event` listener to the guest and dispatched keyboard input through CDP. No `before-input-event` was emitted.
This contradicts the assumption that CDP keyboard input is necessarily indistinguishable from human input at this boundary. It does not prove every Electron version, platform, input method, or pointer path behaves identically.
## Requirements
- Cover keyboard, pointer, wheel, touch, IME, accessibility input, and DevTools interaction where available.
- Record the interruption reason and the command that was cancelled.
- Serialize lease transition and command cancellation so a late automation event cannot land after the user takes control.
- Keep a regression fixture for CDP keyboard and mouse dispatch on every supported desktop platform.
- Remove the undefined `shared` controller mode. Initial modes are `human`, `agent`, and `none`.
-23
View File
@@ -1,23 +0,0 @@
# Browser Phase 0.5
Phase 0.5 closes the production-risk questions raised after the original browser spikes. It does not add application behavior. It expands the executable harness and revises the architecture decisions before session implementation begins.
## Commands
```bash
node .plans/browser-phase-0/spikes/run-electron-spikes.mjs renderer-reload
node .plans/browser-phase-0/spikes/run-electron-spikes.mjs injected-runtime
node .plans/browser-phase-0/spikes/run-electron-spikes.mjs recording-endurance
node .plans/browser-phase-0/spikes/run-electron-spikes.mjs input-origin
node .plans/browser-phase-0/spikes/run-tunnel-security-spike.mjs
```
## Decisions
- `006-renderer-failure-boundary.md`: keep `<webview>` for this iteration, but describe it as route-durable rather than process-durable and specify session-loss behavior.
- `007-playwright-injected-runtime.md`: use Playwright's injected runtime as the initial semantic locator/actionability substrate, behind a T3-owned adapter and compatibility tests.
- `008-recording-endurance.md`: retain covered parking provisionally, with a one-recording default and further soak/platform tests required before widening concurrency.
- `009-loopback-threat-model.md`: a plain loopback listener is not an authorization boundary; stable origins and a browser-enforced capability authority are required.
- `010-human-input-interruption.md`: Electron `before-input-event` did not observe CDP keyboard dispatch in the tested guest, so human interruption can start with native input observation without a dispatch suppression window, while retaining regression coverage.
See `findings.md` for measured results and the resulting roadmap changes.
-27
View File
@@ -1,27 +0,0 @@
# Phase 0.5 Findings
## Executive Decisions
1. The selected `<webview>` is route-durable, not process-durable. Renderer reload destroys its guest and state; `WebContentsView` survives that specific failure boundary.
2. Use Playwright's injected runtime behind the T3 Browser Control Service instead of implementing locator and actionability semantics from scratch.
3. Use locator descriptions that re-resolve at action time. Treat snapshot element references as ephemeral.
4. Covered recording remains viable at 1600×1200 for one tab, but concurrency and long-duration operation remain gated.
5. A loopback port is not an authorization capability. Stable origin, browser attribution, and bounded tunnel multiplexing are required before remote preview ships.
6. CDP keyboard dispatch did not trigger Electron `before-input-event` in the tested guest. Start with native input interruption and no timing suppression hack.
## Roadmap Changes
- Add host loss, window identity, session-loss UX, annotation preservation, port discovery, and guest hardening to the session foundation phase.
- Put persistent CDP, Playwright injected-runtime integration, console buffers, and network buffers in the automation phase.
- Add OOPIF target routing and per-frame injected runtimes to the automation acceptance criteria.
- Move remote preview behind a second browser-attribution spike; raw TCP transport feasibility alone is insufficient.
- Keep one active recording per window as the initial policy.
- Remove `shared` controller mode until concurrency semantics exist.
## Remaining Open Questions
- Browser-attributed local tunnel ingress that preserves application origin behavior.
- Multi-tab recording budgets and 30-minute platform soak results.
- Pointer/touch interruption behavior across macOS, Windows, and Linux.
- Recovery fidelity after renderer/window loss.
- Web-app viewing UX for separately hosted environment Chromium sessions.
@@ -1,24 +0,0 @@
# ADR 001: Durable Renderer-Hosted Webview
## Status
Accepted with the failure-boundary amendment in `.plans/browser-phase-0-5/006-renderer-failure-boundary.md`.
## Decision
Keep Electron `<webview>` as the collaborative browser surface, but move it out of thread panel lifecycle into a route-durable app-level browser host. This does not survive host-renderer reload, renderer crash, owning-window close, or application restart.
The host owns one mounted webview per live browser tab. The visible browser panel supplies bounds and visibility intent. Hiding, switching routes, closing a sheet, or unmounting a panel must not remove the webview element or close its guest `WebContents`.
The desktop main process remains authoritative for navigation, CDP, recording, security policy, and guest `WebContents` validation. The renderer host is responsible only for maintaining the required DOM attachment and reporting presentation bounds.
## Hidden Presentation Policy
- Visible tab: place the webview at the panel bounds.
- Hidden idle tab: park it offscreen at its preserved viewport size; automation remains available but continuous screencast is not expected.
- Hidden recording tab: place it on a full-size in-window parking surface covered by an opaque application layer so Chromium continues producing compositor frames.
- Suspended tab: explicit lifecycle transition that may destroy and later reload the page; never perform silently while controlled or recording.
## Rejected Alternative
`WebContentsView` is not selected for this iteration. It is durable and Playwright-visible, but hidden/detached capture semantics failed the recording requirements and its native stacking model complicates overlays and clipping.
@@ -1,33 +0,0 @@
# ADR 002: Browser-Client-Style Semantic CDP Adapter
## Status
Superseded in implementation detail by `.plans/browser-phase-0-5/007-playwright-injected-runtime.md`.
## Decision
Build the primary automation adapter over a persistent Electron debugger connection using CDP accessibility, DOM, runtime, page, network, and input domains.
The adapter should offer Playwright-like concepts—role/name locators, text locators, frames, auto-waiting, stale references, dialogs, downloads, and actionability checks—but it must not depend on Playwright owning the browser or recognizing the guest as a `Page`.
Use two layers:
1. main-process CDP session and command/event transport
2. the version-pinned Playwright injected runtime behind a T3-owned compatibility adapter
Locator descriptions re-resolve at action time. Snapshot-scoped backend-node references are optional and ephemeral.
## Playwright Role
Use Playwright as:
- a behavior reference
- a test oracle against standalone test pages
- the initial injected selector/actionability runtime
- an optional adapter for future environment-hosted Chromium sessions
Do not expose a production Electron remote-debugging port merely to attach Playwright.
## agent-browser Role
agent-browser may be supported through a compatible CLI or command adapter backed by the same Browser Control Service. It must not launch an unrelated browser for collaborative preview sessions.
-33
View File
@@ -1,33 +0,0 @@
# ADR 003: CDP Capture with Chromium MediaRecorder
## Status
Accepted with the concurrency and soak gates in `.plans/browser-phase-0-5/008-recording-endurance.md`.
## Decision
Capture the collaborative guest page with `Page.startScreencast`, sample frames at the configured recording frame rate, draw them into an isolated recording canvas, and encode through Chromium MediaRecorder.
Initial artifact format:
- H.264 MP4
- `video/mp4;codecs=avc1.42E01E`
- default 12 fps
- default viewport resolution, bounded by recording policy
Encoding runs in a dedicated hidden renderer or utility surface, not in the primary React render path. Frame transport must be bounded and may drop intermediate frames under pressure rather than accumulating memory.
## Hidden Recording
An offscreen webview does not continuously produce screencast frames. While recording a hidden tab, the browser host temporarily places the full-size webview on a covered parking surface. The user continues seeing the normal application UI, not the frame stream.
## Artifact Semantics
Video is paired with structured action events and timestamps. Video is evidence, not browser state and not the interactive UX.
## Rejected Alternatives
- external ffmpeg as a required encoder
- `desktopCapturer` capture of the whole application window
- JPEG/video streaming as the browser UI
- recording only when the preview panel is open
@@ -1,38 +0,0 @@
# ADR 004: Raw TCP Preview Tunnel
## Status
Transport accepted; desktop ingress and authorization amended by `.plans/browser-phase-0-5/009-loopback-threat-model.md`.
## Decision
Remote environment ports are exposed to the desktop browser through:
```text
browser webview
-> browser-attributed stable desktop authority
-> dedicated authenticated WebSocket tunnel
-> environment server tunnel endpoint
-> environment loopback TCP target
```
Multiplex TCP streams over a bounded number of dedicated authenticated tunnel connections before relay rollout. The protocol must preserve backpressure, half-close, cancellation, and connection-specific errors.
The browser navigates to a stable desktop authority, preserving normal origin and root-relative URL behavior. A bare loopback listener is not an authorization boundary, and absolute redirects, OAuth callbacks, and HTTPS upstreams require explicit policy.
## Isolation
Tunnel data uses a dedicated connection and priority class. It must not share the normal RPC/event WebSocket because large responses or stalled browser streams must not delay thread control traffic.
## Authorization
Each listener is backed by a short-lived grant scoped to:
- environment
- browser session
- target loopback host
- target port
- protocol policy
- provider/thread authorization where agent-created
The environment server validates the grant before opening any TCP target.
@@ -1,24 +0,0 @@
# ADR 005: Retain Renderer Transport Relay Initially
## Status
Accepted for Phase 1; revisit after lifecycle migration.
## Decision
Do not add a second environment-server connection from desktop main solely to remove renderer IPC.
The current renderer-mediated transport can remain temporarily:
```text
environment server -> renderer connection -> typed IPC -> desktop Browser Control Service
```
The renderer must no longer decide browser existence, visible-only eligibility, or ownership. It relays authenticated commands and browser-host events between transports.
## Rationale
Measured renderer IPC overhead was approximately 0.04 ms at the median and approximately 0.20 ms at p95 above direct CDP for a no-op command. That is negligible compared with page work and remote network latency.
The architectural problem is lifecycle coupling and failure ownership, not local IPC performance. A direct desktop-main network connection may still be introduced later for reliability or background operation, but it is not required to begin the durable session migration.
-33
View File
@@ -1,33 +0,0 @@
# Browser Phase 0 Spikes
These spikes validate the architectural decisions recorded beside this file. They exercise Electron 41 against real browser surfaces rather than mocking browser lifecycle or CDP behavior.
## Environment Used for Recorded Results
- macOS 26.5.1, arm64
- Apple M4 Max, 64 GiB RAM
- Electron 41.5.0
- installed Playwright 1.60.0
- Node.js 25.8.2 orchestration process
Results are documented in `findings.md`. Generated frames, videos, screenshots, logs, and transient JSON files under `results/` are intentionally ignored.
## Commands
```bash
node .plans/browser-phase-0/spikes/run-electron-spikes.mjs automation
node .plans/browser-phase-0/spikes/run-electron-spikes.mjs view-automation
node .plans/browser-phase-0/spikes/run-electron-spikes.mjs hidden
node .plans/browser-phase-0/spikes/run-electron-spikes.mjs offscreen-recording
node .plans/browser-phase-0/spikes/run-electron-spikes.mjs covered-recording
node .plans/browser-phase-0/spikes/run-electron-spikes.mjs media-recorder
node .plans/browser-phase-0/spikes/run-electron-spikes.mjs latency
node .plans/browser-phase-0/spikes/run-gateway-spike.mjs
```
The Electron harness uses the repository's installed Electron and Playwright packages. The gateway harness uses the locked `ws` package already present in the pnpm installation.
## Scope
These are architectural probes, not production modules. They deliberately avoid changing application behavior. Production work must reimplement the selected patterns with typed contracts, Effect services, cancellation, security policy, tests, and resource cleanup.
-156
View File
@@ -1,156 +0,0 @@
# Browser Phase 0 Findings
## Executive Result
Phase 0 resolves the major architectural unknowns:
1. Keep a real Electron `<webview>` as the collaborative browser surface for the next iteration.
2. Move that webview into a durable app-level host independent of panel and route mounting.
3. Build a browser-client-style semantic automation adapter over persistent CDP, not direct Playwright attachment.
4. Use CDP screencast for capture and Chromium MediaRecorder for seekable H.264 MP4 encoding.
5. Use a desktop loopback listener plus a dedicated authenticated raw-TCP-over-WebSocket tunnel for remote environment ports.
6. Keep the renderer as the desktop/server transport relay initially; remove its browser lifecycle authority, not the relay itself.
## Automation Attachment
### Existing `<webview>`
Electron remote debugging exposed two targets:
- host renderer: target type `page`
- guest browser: target type `webview`
Playwright `chromium.connectOverCDP()` returned only the host renderer as a `Page`. Connecting directly to the guest target's debugger WebSocket succeeded at the transport level but produced zero Playwright pages.
Conclusion: direct Playwright locators cannot drive the current guest webview through the supported `connectOverCDP` API.
### Semantic CDP adapter
The spike used:
- `Accessibility.getFullAXTree`
- role and accessible-name matching
- `DOM.getBoxModel`
- `Input.dispatchMouseEvent`
- `DOM.resolveNode`
- `Runtime.callFunctionOn`
It located and clicked a button by role/name and filled a textbox by role/name against the exact guest page. The resulting page state was correct.
Conclusion: a browser-client-style adapter can provide semantic locators without Playwright owning or directly attaching to the guest page.
### `WebContentsView` comparison
A main-process-owned `WebContentsView` appears as a normal Playwright `Page`; Playwright role and textbox locators succeeded.
However:
- hidden or detached view capture was inconsistent or unavailable
- detached `capturePage()` reported no current display surface
- detached CDP screenshot could hang without an explicit timeout
- hidden/detached CDP screencast emitted zero frames
- native child views add clipping, stacking, and renderer-overlay integration costs
Conclusion: do not migrate the collaborative browser to `WebContentsView` in this iteration merely to obtain direct Playwright attachment.
## Hidden Lifecycle
For the existing `<webview>`:
- the window was hidden for 1.5 seconds
- the page timer advanced 15 ticks
- semantic automation incremented page state
- `capturePage()` returned a 1600×1200 Retina capture
- the page remained alive and controllable
Observed process snapshot for the minimal two-renderer harness:
- main-process private memory: approximately 43 MiB
- Electron Browser working set: approximately 172 MiB
- GPU process working set: approximately 100 MiB
- host renderer working set: approximately 88 MiB
- guest renderer working set: approximately 93 MiB
- measured main-process CPU during the 1.5-second hidden interval: approximately 0.04%
These are development-machine snapshots, not production budgets. They prove lifecycle behavior and establish that each retained page has meaningful renderer memory cost.
## Recording
### CDP screencast behavior
`Page.startScreencast` against the guest webview produced frames while:
- the whole BrowserWindow was hidden
- the webview remained full-size and was covered by an opaque renderer element
Moving the webview offscreen reduced the stream to one frame. Therefore hidden idle parking and hidden recording require different presentation policies.
### External ffmpeg proof
The initial proof sampled CDP frames at 12 fps and encoded H.264 MP4 with ffmpeg:
- 28 frames
- 800×600
- 12 fps
- 2.33-second duration
- valid seekable MP4
This proved the capture pipeline but is not the selected production encoder because shipping an external ffmpeg executable is unnecessary.
### Selected Chromium-native encoder
The final proof sent sampled CDP frames into an isolated canvas and used Chromium MediaRecorder:
- MIME: `video/mp4;codecs=avc1.42E01E`
- codec: H.264
- 800×600
- approximately 11 fps from a requested 12 fps
- 2.4617-second duration
- 12,823-byte seekable MP4 artifact
- no external ffmpeg process used for encoding
Conclusion: select CDP screencast plus Chromium MediaRecorder H.264 MP4 for the initial recording backend.
## Remote Preview Tunnel
Two proxy shapes were tested:
1. HTTP-aware reverse proxy with WebSocket upgrade handling.
2. Desktop loopback TCP listener forwarding raw streams over a dedicated WebSocket to an environment-side TCP dialer.
Both loaded the HTTP page and passed 100 WebSocket echo round trips. The raw TCP tunnel is selected because it preserves origin paths, root-relative assets, arbitrary HTTP semantics, HMR upgrades, and application WebSockets without rewriting response bodies.
Five local runs of the raw TCP tunnel produced:
- added HTTP median latency: 0.036–0.112 ms; median run 0.049 ms
- WebSocket median round-trip: 0.075–0.138 ms; median run 0.102 ms
- WebSocket p95 round-trip: 0.133–0.287 ms; median run 0.151 ms
Network latency will dominate in real remote environments. The local result shows the framing/proxy architecture itself is not a meaningful latency source.
## Desktop Routing Latency
The spike compared 100 no-op CDP evaluations:
- direct main-process CDP call
- renderer `ipcRenderer.invoke` relay to the same main-process CDP call
Across five runs:
- direct median: 0.058–0.066 ms; median run 0.060 ms
- renderer-relay median: 0.100 ms
- direct p95: 0.101–0.115 ms; median run 0.105 ms
- renderer-relay p95: approximately 0.300 ms
Conclusion: renderer IPC overhead is negligible compared with browser work and remote networking. The renderer should lose lifecycle and ownership authority, but replacing the existing server-to-renderer transport relay is not a Phase 1 performance requirement.
## Explicit Unsupported or Rejected Paths
- Direct Playwright `connectOverCDP` to an Electron `<webview>` guest.
- Enabling an unauthenticated process-wide Chromium remote-debugging port in production.
- Switching to `WebContentsView` solely for Playwright compatibility.
- Recording from an offscreen or detached surface without temporarily restoring a composited parking surface.
- Using screenshots, JPEG frames, or video as the interactive browser presentation.
- HTTP path-prefix rewriting as the general remote preview solution.
- Sending preview tunnel data over the normal control/event WebSocket.
@@ -1,3 +0,0 @@
*
!.gitignore
@@ -1,16 +0,0 @@
const { app } = require("electron");
const portArgument = process.argv.find((value) => value.startsWith("--port="));
if (portArgument) {
app.commandLine.appendSwitch("remote-debugging-address", "127.0.0.1");
app.commandLine.appendSwitch("remote-debugging-port", portArgument.slice("--port=".length));
}
app.commandLine.appendSwitch("disable-background-timer-throttling");
app
.whenReady()
.then(() => import("./electron-webview-host.mjs"))
.catch((error) => {
console.error(error);
app.exit(1);
});
@@ -1,736 +0,0 @@
import { spawnSync } from "node:child_process";
import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import electron from "electron";
const { app, BrowserWindow, ipcMain, WebContentsView } = electron;
const args = Object.fromEntries(
process.argv
.slice(2)
.filter((value) => value.startsWith("--"))
.map((value) => {
const [key, ...rest] = value.slice(2).split("=");
return [key, rest.join("=") || "true"];
}),
);
const mode = args.mode ?? "automation";
const debugPort = Number(args.port ?? 0);
const outputDirectory = args.output;
const playwrightCoreBundle = args["playwright-core-bundle"];
function debug(message) {
if (!outputDirectory) return;
mkdirSync(outputDirectory, { recursive: true });
appendFileSync(join(outputDirectory, "debug.log"), `${new Date().toISOString()} ${message}\n`);
}
debug(`startup electron=${process.versions.electron ?? "missing"}`);
const here = dirname(fileURLToPath(import.meta.url));
const guestUrl = new URL("./guest.html", import.meta.url).href;
function emitResult(result) {
if (outputDirectory) {
mkdirSync(outputDirectory, { recursive: true });
writeFileSync(join(outputDirectory, "result.json"), JSON.stringify(result, null, 2));
}
process.stdout.write(`PHASE0_RESULT ${JSON.stringify(result)}\n`);
}
function attachDebugger(contents) {
if (!contents.debugger.isAttached()) contents.debugger.attach("1.3");
return (method, params) => contents.debugger.sendCommand(method, params);
}
async function evaluate(send, expression) {
const result = await send("Runtime.evaluate", {
expression,
awaitPromise: true,
returnByValue: true,
});
if (result.exceptionDetails) {
const description = result.exceptionDetails.exception?.description;
throw new Error(description ?? result.exceptionDetails.text ?? "Evaluation failed");
}
return result.result?.value;
}
function axValue(node, key) {
return node[key]?.value ?? null;
}
async function runSemanticProbe(contents) {
const send = attachDebugger(contents);
await Promise.all([send("Runtime.enable"), send("DOM.enable"), send("Accessibility.enable")]);
const tree = await send("Accessibility.getFullAXTree");
const buttonNode = tree.nodes.find(
(node) => axValue(node, "role") === "button" && axValue(node, "name") === "Increment count",
);
const inputNode = tree.nodes.find(
(node) => axValue(node, "role") === "textbox" && axValue(node, "name") === "Message",
);
if (!buttonNode?.backendDOMNodeId || !inputNode?.backendDOMNodeId) {
throw new Error("Semantic nodes were not found in the accessibility tree");
}
const box = await send("DOM.getBoxModel", { backendNodeId: buttonNode.backendDOMNodeId });
const quad = box.model.content;
const x = (quad[0] + quad[2] + quad[4] + quad[6]) / 4;
const y = (quad[1] + quad[3] + quad[5] + quad[7]) / 4;
await send("Input.dispatchMouseEvent", { type: "mousePressed", x, y, button: "left", clickCount: 1 });
await send("Input.dispatchMouseEvent", { type: "mouseReleased", x, y, button: "left", clickCount: 1 });
const resolvedInput = await send("DOM.resolveNode", { backendNodeId: inputNode.backendDOMNodeId });
await send("Runtime.callFunctionOn", {
objectId: resolvedInput.object.objectId,
functionDeclaration: `function(value) {
this.focus();
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
setter.call(this, value);
this.dispatchEvent(new Event('input', { bubbles: true }));
this.dispatchEvent(new Event('change', { bubbles: true }));
}`,
arguments: [{ value: "semantic CDP attached" }],
});
const state = await evaluate(
send,
`({ count: document.querySelector('#count').textContent, value: document.querySelector('#message').value })`,
);
return {
success: state.count === "1" && state.value === "semantic CDP attached",
button: { role: axValue(buttonNode, "role"), name: axValue(buttonNode, "name") },
input: { role: axValue(inputNode, "role"), name: axValue(inputNode, "name") },
state,
};
}
function readPlaywrightInjectedSource() {
if (!playwrightCoreBundle) throw new Error("Playwright core bundle path is required");
const bundle = readFileSync(playwrightCoreBundle, "utf8");
const marker = "source3 = ";
const start = bundle.indexOf(marker);
const suffix = ";\n }\n});\n\n// packages/playwright-core/src/server/dom.ts";
const end = bundle.indexOf(suffix, start);
if (start === -1 || end === -1) throw new Error("Could not locate Playwright injected source");
const literal = bundle.slice(start + marker.length, end);
return Function(`"use strict"; return (${literal});`)();
}
async function runInjectedRuntimeSpike(contents) {
const send = attachDebugger(contents);
await send("Runtime.enable");
const injectedSource = readPlaywrightInjectedSource();
const installStartedAt = performance.now();
const install = await evaluate(
send,
`(() => {
const module = {};
${injectedSource}
const injected = new (module.exports.InjectedScript())(globalThis, {
isUnderTest: false,
sdkLanguage: "javascript",
testIdAttributeName: "data-testid",
stableRafCount: 2,
browserName: "chromium",
shouldPrependErrorPrefix: false,
isUtilityWorld: true,
customEngines: [],
});
globalThis.__phase05Injected = injected;
return {
methods: Object.getOwnPropertyNames(Object.getPrototypeOf(injected)).sort(),
bytes: ${Buffer.byteLength(injectedSource)},
};
})()`,
);
const installMs = performance.now() - installStartedAt;
const probe = await evaluate(
send,
`(async () => {
const injected = globalThis.__phase05Injected;
const resolve = (selector) => {
const parsed = injected.parseSelector(selector);
return injected.querySelectorAll(parsed, document.documentElement);
};
const roleSelector = 'internal:role=button[name="Increment count"i]';
const buttonBefore = resolve(roleSelector);
const shadow = resolve('internal:role=button[name="Shadow action"i]');
const inputLocator = 'internal:role=textbox[name="Message"i]';
const inputBefore = resolve(inputLocator)[0];
inputBefore.value = "before replacement";
document.querySelector("#replace").click();
const inputAfter = resolve(inputLocator)[0];
inputAfter.value = "after replacement";
const frame = document.querySelector("#same-origin-frame");
await new Promise((resolveReady) => {
if (frame.contentDocument?.readyState === "complete") resolveReady();
else frame.addEventListener("load", resolveReady, { once: true });
});
return {
roleMatches: buttonBefore.length,
shadowMatches: shadow.length,
locatorReresolvedAfterReplacement: inputBefore !== inputAfter && inputAfter.value === "after replacement",
sameOriginFrameRequiresSeparateRuntime: frame.contentDocument !== document,
};
})()`,
);
emitResult({ mode, install, installMs, probe });
app.quit();
}
let rendererReloadStarted = false;
let rendererReloadNextGuestResolve;
async function runRendererReloadSpike(window, firstGuest) {
rendererReloadStarted = true;
const firstSend = attachDebugger(firstGuest);
await firstSend("Runtime.enable");
await evaluate(firstSend, `document.querySelector("#increment").click()`);
const firstState = await evaluate(firstSend, `document.querySelector("#count").textContent`);
const firstGuestId = firstGuest.id;
const nativeView = new WebContentsView({
webPreferences: { contextIsolation: true, nodeIntegration: false, partition: "persist:t3-phase05-view" },
});
nativeView.setBounds({ x: 0, y: 0, width: 1, height: 1 });
window.contentView.addChildView(nativeView);
await nativeView.webContents.loadFile(join(here, "guest.html"));
await nativeView.webContents.executeJavaScript(`document.querySelector("#increment").click()`);
const nativeId = nativeView.webContents.id;
const nextGuest = new Promise((resolveGuest) => {
rendererReloadNextGuestResolve = resolveGuest;
});
await window.webContents.reload();
const secondGuest = await Promise.race([
nextGuest,
new Promise((_, reject) => setTimeout(() => reject(new Error("Replacement webview timed out")), 5_000)),
]);
const secondSend = attachDebugger(secondGuest);
await secondSend("Runtime.enable");
const secondState = await evaluate(secondSend, `document.querySelector("#count").textContent`);
const nativeState = await nativeView.webContents.executeJavaScript(
`document.querySelector("#count").textContent`,
);
emitResult({
mode,
webview: {
firstGuestId,
secondGuestId: secondGuest.id,
firstState,
secondState,
firstDestroyed: firstGuest.isDestroyed(),
survivedRendererReload: firstGuestId === secondGuest.id,
},
webContentsView: {
idBefore: nativeId,
idAfter: nativeView.webContents.id,
stateAfter: nativeState,
destroyed: nativeView.webContents.isDestroyed(),
},
});
app.quit();
}
async function runInputOriginSpike(contents) {
const send = attachDebugger(contents);
await send("Input.enable").catch(() => undefined);
const beforeInputEvents = [];
contents.on("before-input-event", (_event, input) => beforeInputEvents.push(input));
await send("Input.dispatchKeyEvent", { type: "keyDown", key: "a", code: "KeyA", text: "a" });
await send("Input.dispatchKeyEvent", { type: "keyUp", key: "a", code: "KeyA" });
await new Promise((resolveDelay) => setTimeout(resolveDelay, 100));
emitResult({
mode,
beforeInputEvents: beforeInputEvents.map(({ type, key, code, isAutoRepeat }) => ({
type,
key,
code,
isAutoRepeat,
})),
cdpDispatchVisibleAsBeforeInput: beforeInputEvents.length > 0,
});
app.quit();
}
async function runHiddenSpike(window, contents) {
const send = attachDebugger(contents);
await send("Runtime.enable");
contents.setBackgroundThrottling(false);
const before = await evaluate(send, `({ ticks: Number(document.querySelector('#timer').textContent), count: Number(document.querySelector('#count').textContent) })`);
const cpuStart = process.getCPUUsage();
window.hide();
await new Promise((resolve) => setTimeout(resolve, 1_500));
await evaluate(send, `document.querySelector('#increment').click()`);
const after = await evaluate(send, `({ ticks: Number(document.querySelector('#timer').textContent), count: Number(document.querySelector('#count').textContent), hidden: document.hidden })`);
const image = await contents.capturePage();
const processMemory = await process.getProcessMemoryInfo();
const cpuUsage = process.getCPUUsage(cpuStart);
const metrics = app.getAppMetrics().map((metric) => ({
type: metric.type,
cpuPercent: metric.cpu.percentCPUUsage,
memoryKb: metric.memory.workingSetSize,
}));
if (outputDirectory) {
mkdirSync(outputDirectory, { recursive: true });
writeFileSync(join(outputDirectory, "hidden-capture.png"), image.toPNG());
}
emitResult({
mode,
before,
after,
captureSize: image.getSize(),
processPrivateKb: processMemory.private,
mainProcessCpuPercent: cpuUsage.percentCPUUsage,
metrics,
});
app.quit();
}
async function runRecordingSpike(window, contents, hideWindow = true) {
if (!outputDirectory) throw new Error("recording mode requires --output");
mkdirSync(outputDirectory, { recursive: true });
const send = attachDebugger(contents);
await Promise.all([send("Runtime.enable"), send("Page.enable")]);
let frameIndex = 0;
const timestamps = [];
let lastWrittenTimestamp = Number.NEGATIVE_INFINITY;
const onMessage = async (_event, method, params) => {
if (method !== "Page.screencastFrame") return;
const timestamp = params.metadata?.timestamp ?? 0;
if (timestamp - lastWrittenTimestamp < 1 / 12) {
await send("Page.screencastFrameAck", { sessionId: params.sessionId });
return;
}
lastWrittenTimestamp = timestamp;
frameIndex += 1;
timestamps.push(timestamp);
writeFileSync(
join(outputDirectory, `frame-${String(frameIndex).padStart(4, "0")}.jpg`),
Buffer.from(params.data, "base64"),
);
await send("Page.screencastFrameAck", { sessionId: params.sessionId });
};
contents.debugger.on("message", onMessage);
await send("Page.startScreencast", {
format: "jpeg",
quality: 80,
maxWidth: 800,
maxHeight: 600,
everyNthFrame: 1,
});
if (hideWindow) window.hide();
await new Promise((resolve) => setTimeout(resolve, 2_500));
await send("Page.stopScreencast");
contents.debugger.off("message", onMessage);
const videoPath = join(outputDirectory, "webview-recording.mp4");
const ffmpeg = spawnSync(
"ffmpeg",
[
"-y",
"-loglevel",
"error",
"-framerate",
"12",
"-i",
join(outputDirectory, "frame-%04d.jpg"),
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
"-movflags",
"+faststart",
videoPath,
],
{ encoding: "utf8" },
);
const probe = spawnSync(
"ffprobe",
["-v", "error", "-show_entries", "format=duration,size", "-of", "json", videoPath],
{ encoding: "utf8" },
);
emitResult({
mode,
frames: frameIndex,
firstTimestamp: timestamps.at(0),
lastTimestamp: timestamps.at(-1),
ffmpegStatus: ffmpeg.status,
ffmpegError: ffmpeg.stderr.trim() || null,
probe: probe.status === 0 ? JSON.parse(probe.stdout) : { error: probe.stderr.trim() },
videoPath,
});
app.quit();
}
async function runMediaRecorderSpike(window, contents) {
if (!outputDirectory) throw new Error("media-recorder mode requires --output");
mkdirSync(outputDirectory, { recursive: true });
await window.webContents.executeJavaScript(`(() => {
const guest = document.querySelector('webview');
guest.style.position = 'fixed';
guest.style.left = '0';
guest.style.top = '0';
guest.style.width = '800px';
guest.style.height = '600px';
guest.style.zIndex = '1';
const cover = document.createElement('div');
cover.style.position = 'fixed';
cover.style.inset = '0';
cover.style.background = '#111827';
cover.style.zIndex = '2';
document.body.appendChild(cover);
})()`);
const recordingInfo = await window.webContents.executeJavaScript(
`window.phase0.startRecording({ width: 800, height: 600, fps: 12 })`,
);
const send = attachDebugger(contents);
await send("Page.enable");
let frameCount = 0;
let lastSentTimestamp = Number.NEGATIVE_INFINITY;
const onMessage = async (_event, method, params) => {
if (method !== "Page.screencastFrame") return;
const timestamp = params.metadata?.timestamp ?? 0;
if (timestamp - lastSentTimestamp >= 1 / 12) {
lastSentTimestamp = timestamp;
frameCount += 1;
window.webContents.send("phase0:recording-frame", `data:image/jpeg;base64,${params.data}`);
}
await send("Page.screencastFrameAck", { sessionId: params.sessionId });
};
contents.debugger.on("message", onMessage);
await send("Page.startScreencast", {
format: "jpeg",
quality: 80,
maxWidth: 800,
maxHeight: 600,
everyNthFrame: 1,
});
await new Promise((resolve) => setTimeout(resolve, 2_500));
await send("Page.stopScreencast");
contents.debugger.off("message", onMessage);
await new Promise((resolve) => setTimeout(resolve, 250));
const recordingResult = await window.webContents.executeJavaScript("window.phase0.stopRecording()");
const videoPath = join(
outputDirectory,
recordingResult.mimeType.startsWith("video/mp4")
? "webview-recording.mp4"
: "webview-recording.webm",
);
writeFileSync(videoPath, Buffer.from(recordingResult.bytes));
const probe = spawnSync(
"ffprobe",
["-v", "error", "-show_entries", "format=duration,size", "-show_entries", "stream=codec_name,width,height,avg_frame_rate", "-of", "json", videoPath],
{ encoding: "utf8" },
);
emitResult({
mode,
frameCount,
recordingInfo,
videoPath,
bytes: recordingResult.bytes.length,
probe: probe.status === 0 ? JSON.parse(probe.stdout) : { error: probe.stderr.trim() },
});
app.quit();
}
async function runRecordingEnduranceSpike(window, contents) {
if (!outputDirectory) throw new Error("recording-endurance mode requires --output");
const width = 1600;
const height = 1200;
const fps = 12;
const durationMs = 10_000;
window.setSize(1700, 1300);
contents.setBackgroundThrottling(false);
await window.webContents.executeJavaScript(`(() => {
const guest = document.querySelector('webview');
guest.style.position = 'fixed';
guest.style.left = '0';
guest.style.top = '0';
guest.style.width = '${width}px';
guest.style.height = '${height}px';
guest.style.zIndex = '1';
const cover = document.createElement('div');
cover.style.position = 'fixed';
cover.style.inset = '0';
cover.style.background = '#111827';
cover.style.zIndex = '2';
document.body.appendChild(cover);
})()`);
const recordingInfo = await window.webContents.executeJavaScript(
`window.phase0.startRecording({ width: ${width}, height: ${height}, fps: ${fps} })`,
);
const send = attachDebugger(contents);
await send("Page.enable");
let frameCount = 0;
let lastSentTimestamp = Number.NEGATIVE_INFINITY;
const cpuStart = process.getCPUUsage();
const onMessage = async (_event, method, params) => {
if (method !== "Page.screencastFrame") return;
const timestamp = params.metadata?.timestamp ?? 0;
if (timestamp - lastSentTimestamp >= 1 / fps) {
lastSentTimestamp = timestamp;
frameCount += 1;
window.webContents.send("phase0:recording-frame", `data:image/jpeg;base64,${params.data}`);
}
await send("Page.screencastFrameAck", { sessionId: params.sessionId });
};
contents.debugger.on("message", onMessage);
await send("Page.startScreencast", {
format: "jpeg",
quality: 75,
maxWidth: width,
maxHeight: height,
everyNthFrame: 1,
});
await new Promise((resolveDelay) => setTimeout(resolveDelay, durationMs));
await send("Page.stopScreencast");
contents.debugger.off("message", onMessage);
await new Promise((resolveDelay) => setTimeout(resolveDelay, 250));
const recordingResult = await window.webContents.executeJavaScript("window.phase0.stopRecording()");
const videoPath = join(outputDirectory, "recording-endurance.mp4");
writeFileSync(videoPath, Buffer.from(recordingResult.bytes));
const probe = spawnSync(
"ffprobe",
["-v", "error", "-show_entries", "format=duration,size", "-show_entries", "stream=codec_name,width,height,avg_frame_rate", "-of", "json", videoPath],
{ encoding: "utf8" },
);
emitResult({
mode,
width,
height,
fps,
durationMs,
frameCount,
achievedFps: frameCount / (durationMs / 1_000),
recordingInfo,
bytes: recordingResult.bytes.length,
mainProcessCpu: process.getCPUUsage(cpuStart),
metrics: app.getAppMetrics().map((metric) => ({
type: metric.type,
cpuPercent: metric.cpu.percentCPUUsage,
memoryKb: metric.memory.workingSetSize,
})),
probe: probe.status === 0 ? JSON.parse(probe.stdout) : { error: probe.stderr.trim() },
});
app.quit();
}
function summarizeDurations(values) {
const sorted = [...values].sort((left, right) => left - right);
const percentile = (fraction) => sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * fraction))];
return {
count: sorted.length,
minMs: sorted[0],
medianMs: percentile(0.5),
p95Ms: percentile(0.95),
maxMs: sorted.at(-1),
meanMs: sorted.reduce((sum, value) => sum + value, 0) / sorted.length,
};
}
async function runLatencySpike(window, contents) {
const send = attachDebugger(contents);
await send("Runtime.enable");
const evaluateNoop = () => send("Runtime.evaluate", { expression: "1 + 1", returnByValue: true });
for (let index = 0; index < 10; index += 1) await evaluateNoop();
const direct = [];
for (let index = 0; index < 100; index += 1) {
const startedAt = performance.now();
await evaluateNoop();
direct.push(performance.now() - startedAt);
}
ipcMain.removeHandler("phase0:cdp-evaluate");
ipcMain.handle("phase0:cdp-evaluate", evaluateNoop);
const rendererRelay = await window.webContents.executeJavaScript(`(async () => {
const durations = [];
for (let index = 0; index < 100; index += 1) {
const startedAt = performance.now();
await window.phase0.invokeCdp();
durations.push(performance.now() - startedAt);
}
return durations;
})()`);
emitResult({
mode,
direct: summarizeDurations(direct),
rendererRelay: summarizeDurations(rendererRelay),
});
app.quit();
}
async function runDetachedViewSpike(window, view, detach) {
const contents = view.webContents;
const send = attachDebugger(contents);
await send("Runtime.enable");
contents.setBackgroundThrottling(false);
const before = await evaluate(
send,
`({ ticks: Number(document.querySelector('#timer').textContent), count: Number(document.querySelector('#count').textContent) })`,
);
if (detach) window.contentView.removeChildView(view);
else view.setVisible(false);
await new Promise((resolve) => setTimeout(resolve, 1_500));
const semanticProbe = await runSemanticProbe(contents);
const after = await evaluate(
send,
`({ ticks: Number(document.querySelector('#timer').textContent), count: Number(document.querySelector('#count').textContent), hidden: document.hidden })`,
);
let capture;
try {
const image = await contents.capturePage();
if (outputDirectory) writeFileSync(join(outputDirectory, "detached-view-capture.png"), image.toPNG());
capture = { success: true, size: image.getSize() };
} catch (error) {
capture = { success: false, error: error instanceof Error ? error.message : String(error) };
}
let cdpScreenshot;
try {
await send("Page.enable");
const screenshot = await Promise.race([
send("Page.captureScreenshot", {
format: "png",
captureBeyondViewport: false,
fromSurface: false,
}),
new Promise((_, reject) => setTimeout(() => reject(new Error("CDP screenshot timed out")), 3_000)),
]);
const bytes = Buffer.from(screenshot.data, "base64");
if (outputDirectory) writeFileSync(join(outputDirectory, "hidden-cdp-screenshot.png"), bytes);
cdpScreenshot = { success: true, bytes: bytes.length };
} catch (error) {
cdpScreenshot = { success: false, error: error instanceof Error ? error.message : String(error) };
}
emitResult({
mode,
detach,
before,
after,
semanticProbe,
capture,
cdpScreenshot,
destroyed: contents.isDestroyed(),
});
contents.close();
app.quit();
}
await app.whenReady();
debug("app-ready");
const window = new BrowserWindow({
width: 900,
height: 700,
show: true,
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
preload: join(here, "host-preload.cjs"),
webviewTag: true,
},
});
app.on("web-contents-created", (_event, contents) => {
debug(`web-contents-created type=${contents.getType()} id=${contents.id}`);
if (contents.getType() !== "webview") return;
contents.once("dom-ready", () => {
if (mode === "renderer-reload" && rendererReloadStarted) {
rendererReloadNextGuestResolve?.(contents);
rendererReloadNextGuestResolve = undefined;
return;
}
if (mode === "automation") {
runSemanticProbe(contents)
.then((semanticProbe) =>
emitResult({ mode, debugPort, webContentsId: contents.id, guestUrl, semanticProbe }),
)
.catch((error) => {
emitResult({ mode, error: error instanceof Error ? error.stack : String(error) });
app.exit(1);
});
return;
}
const operation =
mode === "hidden"
? runHiddenSpike(window, contents)
: mode === "injected-runtime"
? runInjectedRuntimeSpike(contents)
: mode === "renderer-reload"
? runRendererReloadSpike(window, contents)
: mode === "input-origin"
? runInputOriginSpike(contents)
: mode === "recording-endurance"
? runRecordingEnduranceSpike(window, contents)
: mode === "recording"
? runRecordingSpike(window, contents)
: mode === "offscreen-recording"
? window.webContents
.executeJavaScript(`(() => {
const guest = document.querySelector('webview');
guest.style.position = 'fixed';
guest.style.left = '-10000px';
guest.style.top = '0';
guest.style.width = '800px';
guest.style.height = '600px';
})()`)
.then(() => runRecordingSpike(window, contents, false))
: mode === "covered-recording"
? window.webContents
.executeJavaScript(`(() => {
const guest = document.querySelector('webview');
guest.style.position = 'fixed';
guest.style.left = '0';
guest.style.top = '0';
guest.style.width = '800px';
guest.style.height = '600px';
guest.style.zIndex = '1';
const cover = document.createElement('div');
cover.style.position = 'fixed';
cover.style.inset = '0';
cover.style.background = '#111827';
cover.style.zIndex = '2';
document.body.appendChild(cover);
})()`)
.then(() => runRecordingSpike(window, contents, false))
: mode === "media-recorder"
? runMediaRecorderSpike(window, contents)
: runLatencySpike(window, contents);
operation.catch((error) => {
emitResult({ mode, error: error instanceof Error ? error.stack : String(error) });
app.exit(1);
});
});
});
if (mode.startsWith("view-")) {
await window.loadURL("data:text/html,<title>Phase0 View Host</title>");
const view = new WebContentsView({
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
partition: "persist:t3-phase0-view",
},
});
view.setBounds({ x: 0, y: 0, width: 800, height: 600 });
window.contentView.addChildView(view);
await view.webContents.loadFile(join(here, "guest.html"));
if (mode === "view-hidden" || mode === "view-detached") {
await runDetachedViewSpike(window, view, mode === "view-detached");
} else if (mode === "view-recording") {
await runRecordingSpike(window, view.webContents);
} else {
const semanticProbe = await runSemanticProbe(view.webContents);
emitResult({
mode,
debugPort,
webContentsId: view.webContents.id,
guestUrl,
semanticProbe,
});
}
} else {
await window.loadFile(join(here, "host.html"));
debug(`host-loaded url=${window.webContents.getURL()}`);
}
-41
View File
@@ -1,41 +0,0 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Phase0 Guest</title>
<style>
body { font-family: sans-serif; margin: 24px; }
#box { width: 80px; height: 80px; background: #7c3aed; position: relative; animation: move 1s infinite alternate linear; }
@keyframes move { from { left: 0; } to { left: 260px; } }
</style>
</head>
<body>
<button id="increment" aria-label="Increment count">Count: <span id="count">0</span></button>
<label>Message <input id="message" aria-label="Message" /></label>
<button id="replace" aria-label="Replace controls">Replace controls</button>
<div id="shadow-host"></div>
<iframe id="same-origin-frame" title="Same origin frame" srcdoc='<button aria-label="Frame action">Frame action</button>'></iframe>
<div id="timer">0</div>
<div id="box"></div>
<script>
let count = 0;
let ticks = 0;
document.querySelector("#increment").addEventListener("click", () => {
count += 1;
document.querySelector("#count").textContent = String(count);
});
document.querySelector("#replace").addEventListener("click", () => {
const input = document.querySelector("#message");
const replacement = input.cloneNode();
replacement.value = input.value;
input.replaceWith(replacement);
});
const shadowRoot = document.querySelector("#shadow-host").attachShadow({ mode: "open" });
shadowRoot.innerHTML = '<button aria-label="Shadow action">Shadow action</button>';
setInterval(() => {
ticks += 1;
document.querySelector("#timer").textContent = String(ticks);
}, 100);
</script>
</body>
</html>
@@ -1,51 +0,0 @@
const { contextBridge, ipcRenderer } = require("electron");
let recording = null;
ipcRenderer.on("phase0:recording-frame", async (_event, dataUrl) => {
if (!recording) return;
const response = await fetch(dataUrl);
const bitmap = await createImageBitmap(await response.blob());
recording.context.drawImage(bitmap, 0, 0, recording.canvas.width, recording.canvas.height);
bitmap.close();
});
contextBridge.exposeInMainWorld("phase0", {
invokeCdp: () => ipcRenderer.invoke("phase0:cdp-evaluate"),
startRecording: ({ width, height, fps }) => {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d");
const stream = canvas.captureStream(fps);
const mimeTypes = [
"video/mp4;codecs=avc1.42E01E",
"video/mp4;codecs=h264",
"video/mp4",
"video/webm;codecs=vp9",
"video/webm;codecs=vp8",
"video/webm",
];
const mimeType = mimeTypes.find((candidate) => MediaRecorder.isTypeSupported(candidate));
if (!mimeType) throw new Error("No supported WebM MediaRecorder codec");
const recorder = new MediaRecorder(stream, { mimeType, videoBitsPerSecond: 2_000_000 });
const chunks = [];
recorder.addEventListener("dataavailable", (event) => {
if (event.data.size > 0) chunks.push(event.data);
});
recorder.start(250);
recording = { canvas, context, recorder, chunks, mimeType };
return { mimeType };
},
stopRecording: async () => {
if (!recording) throw new Error("Recording was not started");
const activeRecording = recording;
recording = null;
await new Promise((resolve) => {
activeRecording.recorder.addEventListener("stop", resolve, { once: true });
activeRecording.recorder.stop();
});
const bytes = new Uint8Array(await new Blob(activeRecording.chunks).arrayBuffer());
return { mimeType: activeRecording.mimeType, bytes };
},
});
-12
View File
@@ -1,12 +0,0 @@
<!doctype html>
<html>
<head><meta charset="utf-8" /><title>Phase0 Host</title></head>
<body style="margin: 0">
<webview
id="guest"
src="./guest.html"
style="width: 800px; height: 600px"
partition="persist:t3-phase0"
></webview>
</body>
</html>
@@ -1,191 +0,0 @@
import { spawn } from "node:child_process";
import { createRequire } from "node:module";
import { createServer } from "node:net";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { readFile, rm } from "node:fs/promises";
const here = dirname(fileURLToPath(import.meta.url));
const repositoryRoot = resolve(here, "../../..");
const requireDesktop = createRequire(join(repositoryRoot, "apps/desktop/package.json"));
const requireWeb = createRequire(join(repositoryRoot, "apps/web/package.json"));
const electronBinary = requireDesktop("electron");
const { chromium } = requireWeb("playwright");
const playwrightPackage = requireWeb.resolve("playwright/package.json");
const playwrightVersion = JSON.parse(await readFile(playwrightPackage, "utf8")).version;
const playwrightCoreBundle = resolve(
dirname(playwrightPackage),
`../../../playwright-core@${playwrightVersion}/node_modules/playwright-core/lib/coreBundle.js`,
);
async function reservePort() {
return new Promise((resolvePort, reject) => {
const server = createServer();
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
const address = server.address();
const port = typeof address === "object" && address ? address.port : 0;
server.close(() => resolvePort(port));
});
});
}
function launchHost({ mode, port, output }) {
const childEnvironment = { ...process.env };
delete childEnvironment.ELECTRON_RUN_AS_NODE;
const command = {
electronPath: electronBinary,
args: [
join(here, "electron-webview-bootstrap.cjs"),
`--mode=${mode}`,
...(port ? [`--port=${port}`] : []),
...(output ? [`--output=${output}`] : []),
`--playwright-core-bundle=${playwrightCoreBundle}`,
],
};
const child = spawn(
command.electronPath,
command.args,
{ cwd: repositoryRoot, env: childEnvironment, stdio: ["ignore", "pipe", "pipe"] },
);
child.stderr.on("data", (chunk) => process.stderr.write(chunk));
return child;
}
async function waitForResult(child, output, timeoutMs = 20_000) {
const resultPath = join(output, "result.json");
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
try {
return JSON.parse(await readFile(resultPath, "utf8"));
} catch {
await new Promise((resolveDelay) => setTimeout(resolveDelay, 100));
}
}
child.kill("SIGTERM");
throw new Error(`Timed out waiting for ${resultPath}`);
}
async function runAutomation(hostMode = "automation") {
const port = await reservePort();
const output = join(repositoryRoot, ".plans/browser-phase-0/results", hostMode);
await rm(output, { recursive: true, force: true });
const child = launchHost({ mode: hostMode, port, output });
const hostResult = await waitForResult(child, output);
let browser;
try {
const endpoint = `http://127.0.0.1:${port}`;
let lastError;
for (let attempt = 0; attempt < 30; attempt += 1) {
try {
browser = await chromium.connectOverCDP(endpoint);
break;
} catch (error) {
lastError = error;
await new Promise((resolveDelay) => setTimeout(resolveDelay, 100));
}
}
if (!browser) throw lastError;
const targets = await fetch(`${endpoint}/json/list`).then((response) => response.json());
const pages = browser.contexts().flatMap((context) => context.pages());
const pageMetadata = await Promise.all(
pages.map(async (page) => ({ url: page.url(), title: await page.title().catch(() => "") })),
);
const guestPage = pages.find((page, index) => pageMetadata[index]?.title === "Phase0 Guest");
if (!guestPage) {
const guestTarget = targets.find((target) => target.title === "Phase0 Guest");
let directTargetAttachment;
if (guestTarget?.webSocketDebuggerUrl) {
try {
const directBrowser = await chromium.connectOverCDP(guestTarget.webSocketDebuggerUrl);
const directPages = directBrowser.contexts().flatMap((context) => context.pages());
directTargetAttachment = {
success: true,
pages: await Promise.all(
directPages.map(async (page) => ({ url: page.url(), title: await page.title().catch(() => "") })),
),
};
await directBrowser.close();
} catch (error) {
directTargetAttachment = {
success: false,
error: error instanceof Error ? error.message : String(error),
};
}
}
return {
hostResult,
targets: targets.map(({ id, title, type, url }) => ({ id, title, type, url })),
pageMetadata,
directTargetAttachment,
success: false,
reason: "Guest webview was not exposed as a Playwright Page",
};
}
const button = guestPage.getByRole("button", { name: "Increment count" });
await button.click();
const countAfterClick = await guestPage.locator("#count").textContent();
const input = guestPage.getByRole("textbox", { name: "Message" });
await input.fill("semantic locator attached");
const inputValue = await input.inputValue();
const expectedCount = String(Number(hostResult.semanticProbe?.state?.count ?? "0") + 1);
return {
hostResult,
pageMetadata,
success: countAfterClick === expectedCount && inputValue === "semantic locator attached",
countAfterClick,
inputValue,
};
} finally {
await browser?.close().catch(() => undefined);
child.kill("SIGTERM");
}
}
async function runManagedMode(mode) {
const output = join(repositoryRoot, ".plans/browser-phase-0/results", mode);
await rm(output, { recursive: true, force: true });
const child = launchHost({ mode, output });
return waitForResult(child, output, mode === "recording" ? 30_000 : 20_000);
}
const requestedMode = process.argv[2] ?? "all";
const result = {};
if (requestedMode === "all" || requestedMode === "automation") result.automation = await runAutomation();
if (requestedMode === "all" || requestedMode === "view-automation") {
result.viewAutomation = await runAutomation("view-automation");
}
if (requestedMode === "all" || requestedMode === "hidden") result.hidden = await runManagedMode("hidden");
if (requestedMode === "all" || requestedMode === "recording") result.recording = await runManagedMode("recording");
if (requestedMode === "all" || requestedMode === "offscreen-recording") {
result.offscreenRecording = await runManagedMode("offscreen-recording");
}
if (requestedMode === "all" || requestedMode === "covered-recording") {
result.coveredRecording = await runManagedMode("covered-recording");
}
if (requestedMode === "all" || requestedMode === "media-recorder") {
result.mediaRecorder = await runManagedMode("media-recorder");
}
if (requestedMode === "all" || requestedMode === "latency") result.latency = await runManagedMode("latency");
if (requestedMode === "all" || requestedMode === "injected-runtime") {
result.injectedRuntime = await runManagedMode("injected-runtime");
}
if (requestedMode === "all" || requestedMode === "renderer-reload") {
result.rendererReload = await runManagedMode("renderer-reload");
}
if (requestedMode === "all" || requestedMode === "input-origin") {
result.inputOrigin = await runManagedMode("input-origin");
}
if (requestedMode === "all" || requestedMode === "recording-endurance") {
result.recordingEndurance = await runManagedMode("recording-endurance");
}
if (requestedMode === "all" || requestedMode === "view-hidden") {
result.viewHidden = await runManagedMode("view-hidden");
}
if (requestedMode === "all" || requestedMode === "view-detached") {
result.viewDetached = await runManagedMode("view-detached");
}
if (requestedMode === "all" || requestedMode === "view-recording") {
result.viewRecording = await runManagedMode("view-recording");
}
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
@@ -1,243 +0,0 @@
import { createServer, request } from "node:http";
import { connect as connectTcp, createServer as createTcpServer } from "node:net";
import { createRequire } from "node:module";
import { readdirSync } from "node:fs";
import { join, resolve } from "node:path";
const repositoryRoot = resolve(import.meta.dirname, "../../..");
const pnpmDirectory = join(repositoryRoot, "node_modules/.pnpm");
const wsPackageDirectory = readdirSync(pnpmDirectory)
.filter((name) => name.startsWith("ws@8."))
.sort()
.at(-1);
if (!wsPackageDirectory) throw new Error("The locked ws 8 package is not installed");
const requireWs = createRequire(join(pnpmDirectory, wsPackageDirectory, "node_modules/ws/package.json"));
const { WebSocket, WebSocketServer } = requireWs("ws");
function listen(server) {
return new Promise((resolvePort, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
const address = server.address();
resolvePort(address.port);
});
});
}
function listenTcp(server) {
return new Promise((resolvePort, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", () => resolvePort(server.address().port));
});
}
function close(server) {
return new Promise((resolveClose, reject) => server.close((error) => (error ? reject(error) : resolveClose())));
}
function summarize(values) {
const sorted = [...values].sort((left, right) => left - right);
const percentile = (fraction) => sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * fraction))];
return {
count: sorted.length,
medianMs: percentile(0.5),
p95Ms: percentile(0.95),
maxMs: sorted.at(-1),
meanMs: sorted.reduce((sum, value) => sum + value, 0) / sorted.length,
};
}
const upstreamWebSockets = new WebSocketServer({ noServer: true });
upstreamWebSockets.on("connection", (socket) => {
socket.on("message", (message) => socket.send(`upstream:${message}`));
});
const upstream = createServer((incoming, response) => {
response.writeHead(200, {
"content-type": incoming.url === "/app" ? "text/html" : "application/json",
"x-upstream-host": incoming.headers.host ?? "",
});
response.end(
incoming.url === "/app"
? "<!doctype html><title>Remote Preview</title><h1>remote-loopback-ok</h1>"
: JSON.stringify({ ok: true, url: incoming.url }),
);
});
upstream.on("upgrade", (incoming, socket, head) => {
upstreamWebSockets.handleUpgrade(incoming, socket, head, (webSocket) => {
upstreamWebSockets.emit("connection", webSocket, incoming);
});
});
const upstreamPort = await listen(upstream);
const gatewayWebSockets = new WebSocketServer({ noServer: true });
gatewayWebSockets.on("connection", (clientSocket, incoming) => {
const upstreamSocket = new WebSocket(`ws://127.0.0.1:${upstreamPort}${incoming.url}`);
const pending = [];
clientSocket.on("message", (message) => {
if (upstreamSocket.readyState === WebSocket.OPEN) upstreamSocket.send(message);
else pending.push(message);
});
upstreamSocket.on("open", () => pending.splice(0).forEach((message) => upstreamSocket.send(message)));
upstreamSocket.on("message", (message) => clientSocket.send(message));
const closeBoth = () => {
if (clientSocket.readyState < WebSocket.CLOSING) clientSocket.close();
if (upstreamSocket.readyState < WebSocket.CLOSING) upstreamSocket.close();
};
clientSocket.on("close", closeBoth);
upstreamSocket.on("close", closeBoth);
upstreamSocket.on("error", closeBoth);
});
const gateway = createServer((incoming, response) => {
const upstreamRequest = request(
{
hostname: "127.0.0.1",
port: upstreamPort,
path: incoming.url,
method: incoming.method,
headers: { ...incoming.headers, host: `127.0.0.1:${upstreamPort}` },
},
(upstreamResponse) => {
response.writeHead(upstreamResponse.statusCode ?? 502, upstreamResponse.headers);
upstreamResponse.pipe(response);
},
);
upstreamRequest.on("error", (error) => response.destroy(error));
incoming.pipe(upstreamRequest);
});
gateway.on("upgrade", (incoming, socket, head) => {
gatewayWebSockets.handleUpgrade(incoming, socket, head, (webSocket) => {
gatewayWebSockets.emit("connection", webSocket, incoming);
});
});
const gatewayPort = await listen(gateway);
const tunnelWebSockets = new WebSocketServer({ noServer: true });
tunnelWebSockets.on("connection", (tunnelSocket) => {
const upstreamSocket = connectTcp({ host: "127.0.0.1", port: upstreamPort });
const pending = [];
tunnelSocket.on("message", (message) => {
const bytes = Buffer.from(message);
if (upstreamSocket.readyState === "open") upstreamSocket.write(bytes);
else pending.push(bytes);
});
upstreamSocket.on("connect", () => pending.splice(0).forEach((bytes) => upstreamSocket.write(bytes)));
upstreamSocket.on("data", (bytes) => {
if (tunnelSocket.readyState === WebSocket.OPEN) tunnelSocket.send(bytes, { binary: true });
});
const closeBoth = () => {
if (!upstreamSocket.destroyed) upstreamSocket.destroy();
if (tunnelSocket.readyState < WebSocket.CLOSING) tunnelSocket.close();
};
upstreamSocket.on("close", closeBoth);
upstreamSocket.on("error", closeBoth);
tunnelSocket.on("close", closeBoth);
});
const tunnelServer = createServer();
tunnelServer.on("upgrade", (incoming, socket, head) => {
tunnelWebSockets.handleUpgrade(incoming, socket, head, (webSocket) => {
tunnelWebSockets.emit("connection", webSocket, incoming);
});
});
const tunnelPort = await listen(tunnelServer);
const desktopLoopback = createTcpServer((browserSocket) => {
const tunnelSocket = new WebSocket(`ws://127.0.0.1:${tunnelPort}/tcp`);
const pending = [];
browserSocket.on("data", (bytes) => {
if (tunnelSocket.readyState === WebSocket.OPEN) tunnelSocket.send(bytes, { binary: true });
else pending.push(bytes);
});
tunnelSocket.on("open", () => pending.splice(0).forEach((bytes) => tunnelSocket.send(bytes, { binary: true })));
tunnelSocket.on("message", (message) => browserSocket.write(Buffer.from(message)));
const closeBoth = () => {
if (!browserSocket.destroyed) browserSocket.destroy();
if (tunnelSocket.readyState < WebSocket.CLOSING) tunnelSocket.close();
};
browserSocket.on("close", closeBoth);
browserSocket.on("error", closeBoth);
tunnelSocket.on("close", closeBoth);
tunnelSocket.on("error", closeBoth);
});
const desktopLoopbackPort = await listenTcp(desktopLoopback);
async function measureFetch(url, count) {
const durations = [];
for (let index = 0; index < count; index += 1) {
const startedAt = performance.now();
const response = await fetch(url);
await response.arrayBuffer();
durations.push(performance.now() - startedAt);
}
return summarize(durations);
}
function websocketRoundTrips(url, count) {
return new Promise((resolveResult, reject) => {
const socket = new WebSocket(url);
const durations = [];
let startedAt = 0;
let completed = 0;
socket.on("open", () => {
startedAt = performance.now();
socket.send(String(completed));
});
socket.on("message", (message) => {
durations.push(performance.now() - startedAt);
if (String(message) !== `upstream:${completed}`) {
reject(new Error(`Unexpected WebSocket response: ${message}`));
return;
}
completed += 1;
if (completed === count) {
socket.close();
resolveResult(summarize(durations));
return;
}
startedAt = performance.now();
socket.send(String(completed));
});
socket.on("error", reject);
});
}
try {
const appResponse = await fetch(`http://127.0.0.1:${gatewayPort}/app`);
const appBody = await appResponse.text();
const directHttp = await measureFetch(`http://127.0.0.1:${upstreamPort}/bench`, 100);
const gatewayHttp = await measureFetch(`http://127.0.0.1:${gatewayPort}/bench`, 100);
const gatewayWebSocket = await websocketRoundTrips(`ws://127.0.0.1:${gatewayPort}/hmr`, 100);
const tunnelAppResponse = await fetch(`http://127.0.0.1:${desktopLoopbackPort}/app`);
const tunnelAppBody = await tunnelAppResponse.text();
const rawTunnelHttp = await measureFetch(`http://127.0.0.1:${desktopLoopbackPort}/bench`, 100);
const rawTunnelWebSocket = await websocketRoundTrips(
`ws://127.0.0.1:${desktopLoopbackPort}/hmr`,
100,
);
process.stdout.write(
`${JSON.stringify(
{
success: appBody.includes("remote-loopback-ok"),
upstreamPort,
gatewayPort,
responseHeaders: Object.fromEntries(appResponse.headers),
directHttp,
gatewayHttp,
addedHttpMedianMs: gatewayHttp.medianMs - directHttp.medianMs,
gatewayWebSocket,
rawTcpTunnel: {
success: tunnelAppBody.includes("remote-loopback-ok"),
environmentTunnelPort: tunnelPort,
desktopLoopbackPort,
http: rawTunnelHttp,
addedHttpMedianMs: rawTunnelHttp.medianMs - directHttp.medianMs,
webSocket: rawTunnelWebSocket,
},
},
null,
2,
)}\n`,
);
} finally {
await Promise.all([close(desktopLoopback), close(tunnelServer), close(gateway), close(upstream)]);
}
@@ -1,98 +0,0 @@
import { spawn } from "node:child_process";
import { createServer } from "node:http";
import { createRequire } from "node:module";
import { join, resolve } from "node:path";
const repositoryRoot = resolve(import.meta.dirname, "../../..");
const requireDesktop = createRequire(join(repositoryRoot, "apps/desktop/package.json"));
const electronBinary = requireDesktop("electron");
function listen(server) {
return new Promise((resolvePort, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", () => resolvePort(server.address().port));
});
}
function close(server) {
return new Promise((resolveClose, reject) =>
server.close((error) => (error ? reject(error) : resolveClose())),
);
}
const observed = [];
const previewHandler = (request, response) => {
observed.push({ url: request.url, origin: request.headers.origin ?? null });
if (request.url === "/absolute-redirect") {
response.writeHead(302, { location: "https://remote.example.test/callback" });
response.end();
return;
}
response.writeHead(200, { "content-type": "text/html" });
response.end("<!doctype html><title>Preview target</title><h1>preview target</h1>");
};
const previewA = createServer(previewHandler);
const previewB = createServer(previewHandler);
const malicious = createServer((_request, response) => {
response.writeHead(200, { "content-type": "text/html" });
response.end("<!doctype html><title>Untrusted page</title><h1>untrusted page</h1>");
});
const [previewAPort, previewBPort, maliciousPort] = await Promise.all([
listen(previewA),
listen(previewB),
listen(malicious),
]);
const previewAUrl = `http://127.0.0.1:${previewAPort}`;
const previewBUrl = `http://127.0.0.1:${previewBPort}`;
const maliciousUrl = `http://127.0.0.1:${maliciousPort}`;
const childEnvironment = { ...process.env };
delete childEnvironment.ELECTRON_RUN_AS_NODE;
const child = spawn(
electronBinary,
[join(import.meta.dirname, "tunnel-security-electron.cjs"), maliciousUrl, previewAUrl, previewBUrl],
{ cwd: repositoryRoot, env: childEnvironment, stdio: ["ignore", "pipe", "pipe"] },
);
let stdout = "";
let stderr = "";
child.stdout.on("data", (bytes) => {
stdout += bytes;
});
child.stderr.on("data", (bytes) => {
stderr += bytes;
});
const exitCode = await new Promise((resolveExit) => child.once("exit", resolveExit));
try {
const resultLine = stdout
.split("\n")
.find((line) => line.startsWith("PHASE05_TUNNEL "));
if (!resultLine) throw new Error(`Electron probe did not emit a result: ${stderr || stdout}`);
const browserResult = JSON.parse(resultLine.slice("PHASE05_TUNNEL ".length));
const redirectResponse = await fetch(`${previewAUrl}/absolute-redirect`, { redirect: "manual" });
process.stdout.write(
`${JSON.stringify(
{
success: exitCode === 0,
browserResult,
untrustedPageCausedLoopbackRequest: observed.some((request) => request.url === "/secret"),
loopbackRequestOriginHeader: observed.find((request) => request.url === "/secret")?.origin ?? null,
observed,
originStickiness: {
sameAuthorityPreservedStorage: browserResult.originalPortValue === "sticky",
differentPortChangedOrigin: browserResult.otherPortValue === null,
},
absoluteRedirect: {
status: redirectResponse.status,
location: redirectResponse.headers.get("location"),
escapedLoopbackAuthority: redirectResponse.headers.get("location")?.startsWith("https://") ?? false,
},
},
null,
2,
)}\n`,
);
} finally {
await Promise.all([close(previewA), close(previewB), close(malicious)]);
}
@@ -1,16 +0,0 @@
const { app, BrowserWindow } = require('electron');
const [maliciousUrl, previewA, previewB] = process.argv.slice(2);
app.whenReady().then(async () => {
const window = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, nodeIntegration: false } });
await window.loadURL(maliciousUrl);
const maliciousFetch = await window.webContents.executeJavaScript(`fetch(${JSON.stringify(previewA + '/secret')}, { mode: 'no-cors' }).then(() => 'sent').catch(error => String(error))`);
await new Promise(resolve => setTimeout(resolve, 150));
await window.loadURL(previewA + '/storage');
await window.webContents.executeJavaScript(`localStorage.setItem('phase05', 'sticky')`);
await window.loadURL(previewB + '/storage');
const otherPortValue = await window.webContents.executeJavaScript(`localStorage.getItem('phase05')`);
await window.loadURL(previewA + '/storage');
const originalPortValue = await window.webContents.executeJavaScript(`localStorage.getItem('phase05')`);
process.stdout.write(`PHASE05_TUNNEL ${JSON.stringify({ maliciousFetch, otherPortValue, originalPortValue })}\n`);
app.quit();
}).catch(error => { console.error(error); app.exit(1); });
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,520 +0,0 @@
# Shared HTTP MCP Server with Preview Automation
## Summary
Embed one reusable HTTP MCP server in each T3 environment server. Every agent session connects to that shared MCP endpoint using a session-scoped bearer token.
Preview browser automation is the first MCP toolkit, not the purpose or boundary of the MCP server. Future T3 toolkits register with the same server.
Architecture:
`agent session` -> `shared T3 HTTP MCP server` -> `tool dispatcher` -> `preview broker` -> `focused desktop client` -> `Electron webview via CDP`
No per-thread MCP process, stdio transport, headless browser, or automatic remote port forwarding.
## Process Model
Each `apps/server` process owns exactly one MCP server instance.
- MCP transport: HTTP.
- MCP endpoint: `/mcp`.
- MCP lifetime: environment server lifetime.
- Agent sessions create MCP protocol sessions/connections, not OS processes.
- Toolkit registration happens once during server startup.
- Provider session termination revokes only its scoped credential.
Implement the endpoint with:
```ts
McpServer.layerHttp({
name: "T3 Code",
version,
path: "/mcp",
});
```
Use the API from:
`effect/unstable/ai/McpServer`
Reference source:
`.repos/effect-smol/packages/effect/src/unstable/ai/McpServer.ts`
Do not implement MCP framing, initialization, session management, or JSON-RPC manually.
## Invocation Identity
MCP `tools/call` does not include T3 thread identity. Bind identity to the MCP connection through authentication.
When starting or resuming a provider session, issue an opaque bearer token associated internally with:
```ts
interface McpInvocationScope {
environmentId: EnvironmentId;
threadId: ThreadId;
providerSessionId: string;
providerInstanceId: ProviderInstanceId;
allowedCapabilities: ReadonlySet<string>;
issuedAt: string;
expiresAt: string;
}
```
Provider MCP configuration:
```ts
{
type: "http",
name: "t3",
url: `${environmentHttpBaseUrl}/mcp`,
headers: [
{
name: "Authorization",
value: `Bearer ${token}`,
},
],
}
```
Requirements:
- Agents never receive or pass `threadId` as a tool argument.
- Tool handlers obtain `McpInvocationScope` from request authentication middleware.
- Tokens are cryptographically random opaque values.
- Store only a hash of each token server-side.
- Revoke tokens when the provider session stops.
- Expire tokens after inactivity and at a fixed maximum lifetime.
- Server restart invalidates all tokens.
- Resuming a provider session issues a fresh token.
## General MCP Architecture
Add server modules such as:
```text
apps/server/src/mcp/
Services/
McpSessionRegistry.ts
McpInvocationContext.ts
Layers/
McpSessionRegistry.ts
McpHttpServer.ts
toolkits/
preview/
tools.ts
handlers.ts
layer.ts
```
### Toolkit Registration
Define capabilities with Effect AI:
```ts
import { McpServer, Tool, Toolkit } from "effect/unstable/ai";
```
Each capability family owns:
- `Tool.make` definitions
- a `Toolkit.make` collection
- handler services/layers
- an MCP registration layer
Server startup merges all registration layers:
```ts
const T3McpToolkits = Layer.mergeAll(
PreviewToolkitRegistration,
// Future toolkit registrations
);
```
Future filesystem, terminal, source-control, or environment tools must not require changes to MCP transport or authentication.
### Naming
Use stable capability-prefixed names:
- `preview_status`
- `preview_open`
- `preview_navigate`
- `preview_snapshot`
- `preview_click`
- `preview_type`
- `preview_press`
- `preview_scroll`
- `preview_evaluate`
- `preview_wait_for`
## MCP Authentication
Integrate bearer authentication into the HTTP MCP route before MCP request handling.
Authentication flow:
1. Read `Authorization: Bearer <token>`.
2. Hash token and resolve it through `McpSessionRegistry`.
3. Verify expiration and provider-session liveness.
4. Provide `McpInvocationContext` to MCP toolkit handlers.
5. Reject invalid credentials without invoking MCP tools.
6. Update token activity timestamp after authenticated requests.
Capability authorization occurs inside handlers or common middleware:
```ts
yield* McpInvocationContext.requireCapability("preview");
```
## Preview Automation Contracts
Add `packages/contracts/src/previewAutomation.ts`.
Define schemas for:
- preview status
- opening/showing preview
- navigation
- page snapshot
- selector or coordinate click
- text entry
- key press
- scrolling
- JavaScript evaluation
- waiting for selector, text, or URL
Define tagged errors:
- `PreviewAutomationUnavailableError`
- `PreviewAutomationNoFocusedOwnerError`
- `PreviewAutomationUnsupportedClientError`
- `PreviewAutomationTabNotFoundError`
- `PreviewAutomationTimeoutError`
- `PreviewAutomationExecutionError`
- `PreviewAutomationInvalidSelectorError`
- `PreviewAutomationResultTooLargeError`
## Preview Toolkit
Implement preview tools as an independent Effect AI toolkit.
Apply annotations:
- `preview_status` and `preview_snapshot`: read-only
- `preview_status`: idempotent
- navigation and page interaction tools: open-world
- browser operations: non-destructive
- all tools: human-readable title and precise description
### `preview_open`
Input:
```ts
{
url?: string;
show?: boolean;
reuseExistingTab?: boolean;
}
```
Defaults:
- `show: true`
- `reuseExistingTab: true`
Behavior:
- Show the preview panel for the scoped thread.
- Reuse its active preview tab when available.
- Create and mount a tab otherwise.
- Navigate when `url` is supplied.
- Wait until the webview has registered before returning.
### `preview_snapshot`
Return:
- current URL, title, loading state
- bounded visible text
- up to 200 interactive elements
- accessibility tree
- PNG screenshot scaled to a maximum width of 1280 pixels
Expose the screenshot as MCP image content and metadata as structured content.
### Browser Controls
- `preview_click`: selector or viewport coordinates
- `preview_type`: optionally focus selector and clear existing value
- `preview_press`: common keys and modifiers
- `preview_scroll`: viewport or selector target
- `preview_evaluate`: execute bounded JavaScript
- `preview_wait_for`: selector, visible text, or URL substring
- `preview_navigate`: navigate and wait for selected readiness condition
Default operation timeout: 15 seconds.
Maximum serialized evaluation result: 64 KB.
Maximum visible text: 20 KB.
## Preview Broker
Add `PreviewAutomationBroker` to `apps/server`.
Responsibilities:
- Track automation-capable desktop clients.
- Track preview ownership by environment and thread.
- Route operations to the correct desktop client.
- Correlate requests and responses.
- Enforce timeouts.
- Fail pending calls when clients disconnect.
Owner state:
```ts
interface PreviewAutomationOwner {
clientId: string;
environmentId: EnvironmentId;
threadId: ThreadId;
tabId: PreviewTabId | null;
visible: boolean;
supportsAutomation: boolean;
focusedAt: string;
}
```
Routing policy:
- Use the most recently focused Electron window displaying the scoped thread.
- Never accept environment or thread overrides from tool arguments.
- Return `PreviewAutomationNoFocusedOwnerError` when no valid owner exists.
- Do not switch the UI to a different thread automatically.
## Server-to-Desktop Protocol
Add WS RPCs:
- `previewAutomation.connect`
- `previewAutomation.respond`
- `previewAutomation.reportOwner`
- `previewAutomation.clearOwner`
`connect` is a long-lived stream from the environment server to the desktop client.
Request:
```ts
{
requestId: string;
threadId: ThreadId;
tabId?: PreviewTabId;
operation: PreviewAutomationOperation;
input: unknown;
timeoutMs: number;
}
```
Response:
```ts
{
requestId: string;
ok: boolean;
result?: unknown;
error?: {
_tag: string;
message: string;
detail?: unknown;
};
}
```
## Desktop Automation
Extend `PreviewViewManager` using Electron `webContents.debugger`.
Use CDP domains:
- `Runtime`
- `DOM`
- `Page`
- `Accessibility`
- `Input`
Use `webContents.capturePage()` for screenshots.
Create a scoped CDP helper that:
1. Resolves the tab’s webContents.
2. Attaches lazily.
3. Enables required domains.
4. Executes one bounded operation.
5. Detaches in finalization.
6. Maps protocol failures to typed errors.
If DevTools or another debugger owns the target, return a typed automation error rather than disrupting it.
Place pure logic in separate modules:
- DOM summary extraction
- selector generation
- result clamping
- key mapping
- CDP response parsing
## Desktop IPC
Extend `DesktopPreviewBridge` with:
```ts
automation: {
status(...): Promise<...>;
snapshot(...): Promise<...>;
click(...): Promise<...>;
type(...): Promise<...>;
press(...): Promise<...>;
scroll(...): Promise<...>;
evaluate(...): Promise<...>;
waitFor(...): Promise<...>;
}
```
Add schema-validated IPC channels and handlers.
## Web Client
Add a preview ownership hook mounted with `PreviewView`.
Report changes to:
- active environment/thread
- tab id
- panel visibility
- window focus
- Electron automation availability
Handle broker requests:
- `preview_open` opens the right panel for the active scoped thread.
- Create a preview session and tab if needed.
- Wait for webview registration.
- Other operations invoke desktop automation IPC.
- Always send a correlated success or failure response.
Clear ownership on unmount, thread change, panel close, or desktop disconnect.
## Provider Integration
Add `McpSessionRegistry` integration to provider lifecycle.
For each provider session:
1. Issue a scoped MCP bearer token.
2. Add the shared HTTP MCP configuration to session startup.
3. Start or resume the agent session.
4. Revoke the token during provider-session finalization.
ACP providers use their existing HTTP MCP configuration fields.
Codex uses its supported MCP/config override mechanism to register the same shared HTTP endpoint.
Assume every supported provider can use HTTP MCP. Do not implement stdio fallback.
## Remote Environment Behavior
For a Mac mini environment viewed from a MacBook:
1. Mac mini runs the T3 environment server and shared MCP endpoint.
2. Agent session connects to that endpoint locally/remotely using its scoped token.
3. Preview tool calls enter the Mac mini preview broker.
4. Broker routes them over the existing T3 connection to the focused MacBook desktop.
5. MacBook controls its visible Electron webview.
URLs must already be reachable from the MacBook, such as:
- `http://mac-mini.local:5173`
- `http://192.168.1.42:5173`
Warn when a remote environment opens `localhost`, `127.0.0.1`, or `::1`, because loopback resolves on the preview client.
Preserve URL-resolution metadata:
```ts
{
requestedUrl: string;
resolvedUrl: string;
resolutionKind: "direct";
environmentId: EnvironmentId;
}
```
This leaves room for future SSH, relay, or Tailscale resolution.
## Tests
### MCP Server
- one MCP server layer starts per environment server
- multiple authenticated MCP clients share the same server instance
- each client receives its own invocation scope
- toolkit registration is independent of transport
- a mock future toolkit can register without changing server runtime
- malformed parameters are rejected by Effect schemas
- tool annotations appear in `tools/list`
### Authentication
- valid token resolves correct thread and provider session
- concurrent tokens remain isolated
- revoked and expired tokens fail
- token cannot call unauthorized capability family
- thread identity cannot be overridden in arguments
- server restart invalidates tokens
### Preview Broker
- focused owner receives operation
- most recently focused client wins
- wrong-thread client is never selected
- no owner returns typed error
- disconnect fails pending calls
- stale responses are ignored
### Desktop and Web
- agent can show and open preview
- webview registration is awaited
- CDP click, typing, key press, scroll, evaluation, and wait work
- snapshot bounds screenshot, text, and interactive elements
- ownership updates on focus and visibility changes
- background threads are not automatically activated
### End-to-End Integration
Run two mocked agent sessions against one HTTP MCP server:
1. Bind each bearer token to a different thread.
2. Call `preview_status` concurrently.
3. Verify each request routes to its own focused preview owner.
4. Verify no MCP child process is spawned.
5. Revoke one provider session and confirm only its MCP access fails.
## Validation
- `vp check`
- `vp run typecheck`
- `vp test`
## Assumptions
- HTTP MCP is supported by every target provider.
- One MCP server is embedded in each T3 environment server.
- MCP connection authentication supplies invocation identity.
- Agents never know or pass T3 thread IDs.
- Preview automation is the first of multiple future MCP toolkits.
- Only Electron desktop preview clients support browser automation in v1.
- No headless browser, stdio fallback, or automatic tunnel management is included.
@@ -1,670 +0,0 @@
# Visible Preview Browser Automation via CDP + MCP
## Summary
Implement agent control of the user-visible T3 preview browser only. Do not add headless browser support. Do not add SSH/relay/private forwarding in v1; preview URLs must already be reachable from the desktop client, such as a Mac mini private IP URL opened on a MacBook.
Architecture:
`agent` -> `stdio MCP server in environment` -> `private T3 server bridge` -> `focused desktop client/window` -> `Electron preview webview via CDP`
The stdio MCP server is the agent-facing integration because all target agents can speak MCP. The MCP server is intentionally thin: it does not automate Chromium directly. It calls the T3 environment server, which routes commands to the focused desktop client that owns the visible preview.
## Explicit Non-Goals
- No headless browser runner.
- No Playwright-managed browser.
- No arbitrary SSH dev-port forwarding in v1.
- No Cloudflare/Tailscale/relay URL rewriting in v1.
- No automation of browser/web clients that do not have Electron preview support.
- No per-action user approval prompts in v1.
## Key Decisions
- **Transport to agents:** stdio MCP.
- **Browser being controlled:** the actual integrated Electron preview webview.
- **Remote URL handling:** manual reachable URLs only. Agents may open `http://mac-mini.local:5173` or `http://192.168.x.y:5173`; T3 will not tunnel `127.0.0.1:5173` from remote to local yet.
- **Client routing:** route tool requests to the most recently focused desktop window/client for the agent’s thread. Return a typed error if no focused desktop preview owner is available.
- **Scope:** full control of preview browser, including opening/showing the preview panel.
- **Primary automation engine:** Chrome DevTools Protocol through Electron `webContents.debugger`, with `webContents.capturePage()` where it is simpler and more reliable.
## New Contracts
Add `packages/contracts/src/previewAutomation.ts`.
### Branded IDs
- `PreviewAutomationRequestId`
- `PreviewAutomationClientId`
- `PreviewAutomationOwnerId`
### Tool Input/Output Schemas
Add Effect schemas for these operations:
- `PreviewAutomationOpenInput`
- `url?: string`
- `show?: boolean` default `true`
- `reuseExistingTab?: boolean` default `true`
- `PreviewAutomationNavigateInput`
- `url: string`
- `waitUntil?: "load" | "domcontentloaded" | "network-idle" | "none"` default `"load"`
- `timeoutMs?: number` default `15000`
- `PreviewAutomationSnapshotInput`
- `includeScreenshot?: boolean` default `true`
- `includeDomSummary?: boolean` default `true`
- `includeAccessibilityTree?: boolean` default `true`
- `screenshotMaxWidth?: number` default `1280`
- `PreviewAutomationClickInput`
- one of:
- `{ selector: string }`
- `{ x: number; y: number }`
- `button?: "left" | "middle" | "right"` default `"left"`
- `clickCount?: number` default `1`
- `PreviewAutomationTypeInput`
- `text: string`
- `selector?: string`
- `clearFirst?: boolean` default `false`
- `PreviewAutomationPressInput`
- `key: string`
- `modifiers?: readonly ("alt" | "control" | "meta" | "shift")[]`
- `PreviewAutomationScrollInput`
- `deltaX?: number`
- `deltaY?: number`
- optional target `{ selector: string }`
- `PreviewAutomationEvaluateInput`
- `expression: string`
- `awaitPromise?: boolean` default `true`
- `returnByValue?: boolean` default `true`
- `PreviewAutomationWaitForInput`
- one of:
- `{ selector: string }`
- `{ text: string }`
- `{ urlIncludes: string }`
- `timeoutMs?: number` default `10000`
- `PreviewAutomationStatusResult`
- `available: boolean`
- `visible: boolean`
- `threadId`
- `tabId: string | null`
- `url: string | null`
- `title: string | null`
- `loading: boolean`
- `ownerClientId: string | null`
### Result Shape
Every mutating or stateful operation returns:
```ts
{
ok: boolean;
status: PreviewAutomationStatusResult;
message?: string;
}
```
`snapshot` additionally returns:
```ts
{
status: PreviewAutomationStatusResult;
screenshot?: {
mimeType: "image/png";
dataBase64: string;
width: number;
height: number;
};
domSummary?: {
url: string;
title: string;
activeElement: string | null;
text: string;
interactiveElements: readonly {
index: number;
tag: string;
role: string | null;
name: string;
text: string;
selector: string | null;
rect: { x: number; y: number; width: number; height: number } | null;
}[];
};
accessibilityTree?: unknown;
}
```
### Error Types
Add tagged errors:
- `PreviewAutomationUnavailableError`
- `PreviewAutomationNoFocusedOwnerError`
- `PreviewAutomationUnsupportedClientError`
- `PreviewAutomationTabNotFoundError`
- `PreviewAutomationTimeoutError`
- `PreviewAutomationExecutionError`
- `PreviewAutomationInvalidSelectorError`
## Server-Side Broker
Add `apps/server/src/previewAutomation/Services/PreviewAutomationBroker.ts`.
Responsibilities:
- Track connected desktop automation clients.
- Track focus ownership by `(environmentId, threadId)`.
- Accept tool calls from MCP/stdin proxy.
- Route each call to the focused owner for the thread.
- Enforce timeouts and cleanup pending requests on disconnect.
- Return typed failures when no client/window is available.
### Owner State
Store:
```ts
{
clientId: PreviewAutomationClientId;
environmentId: EnvironmentId;
threadId: ThreadId;
tabId: PreviewTabId | null;
focusedAt: string;
visible: boolean;
supportsAutomation: boolean;
}
```
Ownership updates come from the web/desktop client when:
- route/thread changes,
- preview panel opens/closes,
- window focus changes,
- tab id changes,
- desktop bridge availability changes.
## WS Bridge: Server to Desktop Client
The current preview RPCs are client-to-server plus server event streams. Add a request/response bridge using stream-style RPCs to avoid introducing bidirectional RPC infrastructure.
### New WS Methods
Add to `packages/contracts/src/rpc.ts`:
- `previewAutomation.connect`
- client calls this as a long-lived stream
- input:
- `clientId`
- `capabilities`
- stream output:
- `PreviewAutomationClientRequest`
- `previewAutomation.respond`
- client sends response for a request id
- `previewAutomation.reportOwner`
- client reports focus/visibility/thread ownership
- `previewAutomation.clearOwner`
- client clears stale ownership on unmount/disconnect
### Request Shape
```ts
{
requestId: string;
threadId: string;
tabId?: string;
operation:
| "open"
| "navigate"
| "snapshot"
| "click"
| "type"
| "press"
| "scroll"
| "evaluate"
| "waitFor"
| "status";
input: unknown;
timeoutMs: number;
}
```
### Response Shape
```ts
{
requestId: string;
ok: boolean;
result?: unknown;
error?: {
_tag: string;
message: string;
detail?: unknown;
};
}
```
## Desktop Preview Automation
Extend `apps/desktop/src/preview-view-manager.ts`.
### Add Methods
- `getAutomationStatus(tabId)`
- `captureSnapshot(tabId, options)`
- `click(tabId, input)`
- `type(tabId, input)`
- `press(tabId, input)`
- `scroll(tabId, input)`
- `evaluate(tabId, input)`
- `waitFor(tabId, input)`
### CDP Session Handling
Add a small helper inside desktop preview code:
- Attach `webContents.debugger` lazily per operation.
- Do not keep debugger attached forever unless needed.
- If already attached by DevTools or another debugger, return `PreviewAutomationExecutionError`.
- Use CDP domains:
- `Runtime.evaluate`
- `DOM.getDocument`
- `DOM.querySelector`
- `DOM.getBoxModel`
- `Accessibility.getFullAXTree`
- `Input.dispatchMouseEvent`
- `Input.dispatchKeyEvent`
- optionally `Page.captureScreenshot` if `webContents.capturePage()` is insufficient
For screenshots, prefer `webContents.capturePage()` first because it is already used safely for annotations.
### DOM Summary Script
Use `Runtime.evaluate` with a bounded page script that returns:
- `document.URL`
- `document.title`
- active element summary
- visible text truncated to a fixed limit, e.g. 20k chars
- up to 200 interactive elements:
- buttons
- links
- inputs
- selects
- textareas
- elements with roles
- elements with click handlers where detectable
- stable-ish CSS selectors generated in page context
- bounding rects
Do not return full HTML by default.
### Input Behavior
- `click(selector)`:
- resolve selector in page
- scroll into view
- compute center of bounding box
- dispatch mouse move/down/up through CDP
- `click(x, y)`:
- dispatch at viewport coordinates
- `type(selector, text)`:
- focus selector if provided
- optionally clear existing value with platform shortcut
- dispatch text via CDP keyboard events or `Input.insertText`
- `press(key)`:
- map common key names: Enter, Escape, Tab, Backspace, Arrow keys
- support modifiers
- `scroll`:
- use CDP mouse wheel or page `scrollBy` fallback
## Web Client Changes
Update `apps/web/src/components/preview`.
### Ownership Reporting
Add a hook, likely `usePreviewAutomationOwner`, mounted near `PreviewView`.
It reports owner state when:
- the current route thread ref changes,
- preview panel visibility changes,
- browser window focus/blur changes,
- tab id changes,
- desktop preview bridge exists.
Policy:
- Only Electron desktop clients with `window.desktopBridge.preview` can report `supportsAutomation: true`.
- A visible preview panel gets ownership.
- The most recently focused window wins.
- On unmount or preview close, clear ownership.
### Handling Server Requests
Add a client-side subscriber using the new `previewAutomation.connect` stream.
When a request arrives:
- if operation is `open`, ensure preview panel is visible for the thread, call `api.preview.open` if needed, mount/create desktop tab, then navigate if URL is provided.
- for browser operations, call new `desktopBridge.preview.automation.*` methods.
- send `previewAutomation.respond`.
Opening behavior:
- If the right panel is closed, open it to preview.
- If the thread is not currently active in the UI, do not navigate the whole app in v1. Return `PreviewAutomationNoFocusedOwnerError`.
- If preview is supported but no tab exists and the agent calls `open`, create one.
- If no tab exists and the agent calls `snapshot/click/type/...`, return a clear “preview not open” error suggesting `preview_open`.
## Desktop IPC / Preload
Extend `packages/contracts/src/ipc.ts` `DesktopPreviewBridge`.
Add:
```ts
automation: {
status(tabId: string): Promise<PreviewAutomationStatusResult>;
snapshot(tabId: string, input: PreviewAutomationSnapshotInput): Promise<PreviewAutomationSnapshotResult>;
click(tabId: string, input: PreviewAutomationClickInput): Promise<PreviewAutomationActionResult>;
type(tabId: string, input: PreviewAutomationTypeInput): Promise<PreviewAutomationActionResult>;
press(tabId: string, input: PreviewAutomationPressInput): Promise<PreviewAutomationActionResult>;
scroll(tabId: string, input: PreviewAutomationScrollInput): Promise<PreviewAutomationActionResult>;
evaluate(tabId: string, input: PreviewAutomationEvaluateInput): Promise<PreviewAutomationEvaluateResult>;
waitFor(tabId: string, input: PreviewAutomationWaitForInput): Promise<PreviewAutomationActionResult>;
}
```
Add IPC channels in `apps/desktop/src/ipc/channels.ts` and handlers in `apps/desktop/src/ipc/methods/preview.ts`.
## Stdio MCP Server
Add package: `packages/preview-mcp`.
Purpose:
- Implements the MCP stdio protocol.
- Exposes T3 preview tools.
- Calls a private loopback endpoint or local JSON-RPC bridge on the environment server.
- Does not know Electron/CDP details.
### Binary
Expose bin:
```json
{
"bin": {
"t3-preview-mcp": "./dist/index.js"
}
}
```
During local dev, provider config can call the source runner via workspace package script; production package uses built JS.
### MCP Environment Variables
Provider sessions launch the MCP server with:
- `T3_PREVIEW_MCP_SERVER_URL`
- environment server loopback URL
- `T3_PREVIEW_MCP_TOKEN`
- short-lived token scoped to the provider session/thread
- `T3_PREVIEW_ENVIRONMENT_ID`
- `T3_PREVIEW_THREAD_ID`
The token must be generated by the environment server and expire when the provider session ends.
### MCP Tools
Expose these tools:
- `preview_status`
- `preview_open`
- `preview_navigate`
- `preview_snapshot`
- `preview_click`
- `preview_type`
- `preview_press`
- `preview_scroll`
- `preview_evaluate`
- `preview_wait_for`
Tool descriptions must explicitly say they operate the visible T3 preview browser for the current thread.
### MCP Output
- Text results include concise status and URL/title.
- `preview_snapshot` returns:
- text summary
- MCP image content for screenshot when available
- Errors are MCP tool errors with the tagged T3 error message included.
## Private MCP Bridge Endpoint
Add an internal server route under `apps/server`, not public app UI:
- `POST /internal/preview-automation/tool`
- Auth: bearer `T3_PREVIEW_MCP_TOKEN`
- Body:
- `{ tool: string, input: unknown }`
- Response:
- `{ ok: true, result } | { ok: false, error }`
This endpoint is only for the stdio MCP proxy. It calls `PreviewAutomationBroker`.
Bind it to the same host/port as the environment server, but require the short-lived token. The endpoint must reject requests without a token or with an expired/stale thread/session.
## Provider Integration
### Codex
When starting a Codex provider session, add the T3 preview MCP server to Codex configuration if the app-server config path supports per-thread MCP injection.
Implementation path:
1. Add `PreviewMcpSessionService` in `apps/server`.
2. On provider session start:
- create scoped MCP token for `(environmentId, threadId, providerSessionId)`.
- build MCP server config:
- name: `t3-preview`
- command: `t3-preview-mcp`
- env vars listed above
3. Thread/session start passes the MCP server config through the provider’s supported config field.
4. If Codex app-server cannot accept injected MCP servers through typed params, use its `config` override field with Codex-compatible MCP config.
### ACP Providers
ACP session creation already passes `mcpServers: []`. Replace that with the same `t3-preview` MCP server config for providers that support MCP.
### Provider Fallback
If a provider does not support MCP injection yet, do not add provider-specific native tools in v1. The shared MCP server remains available for later provider wiring.
## Remote Environment Behavior
### Mac mini dev server viewed from MacBook
Expected v1 workflow:
1. Agent runs dev server on Mac mini.
2. Agent or user opens a reachable URL, e.g.:
- `http://mac-mini.local:5173`
- `http://192.168.1.42:5173`
3. T3 desktop on MacBook opens that URL in the local Electron preview.
4. Agent uses MCP tools.
5. T3 routes tool calls from Mac mini environment server to the focused MacBook preview client.
### `localhost` Caveat
In v1, if an agent opens `http://localhost:5173` from a remote environment, the MacBook preview will interpret that as MacBook localhost. The tool result should include a warning when:
- environment is not the primary/local environment, and
- URL hostname is `localhost`, `127.0.0.1`, or `::1`.
Warning text:
`This URL is loopback on the preview client, not necessarily the remote environment. Use a client-reachable host/IP for remote dev servers.`
### Future-Proofing
Do not bake manual URL assumptions into the automation layer. Represent opened URLs as:
```ts
{
displayUrl: string;
requestedUrl: string;
resolutionKind: "direct";
environmentId: string;
}
```
Later `resolutionKind` can add:
- `ssh-forward`
- `relay`
- `tailscale`
- `cloudflare-tunnel`
## Security and Safety
- MCP tokens are scoped to one provider session/thread.
- MCP tokens expire on provider session stop and server restart.
- Browser automation only routes to focused desktop owner for that same thread.
- Do not allow MCP input to specify arbitrary `environmentId` or `threadId`; infer both from token/session.
- `preview_evaluate` is powerful. Keep it enabled in v1 because the user requested full control, but:
- limit result serialization size, e.g. 64 KB
- timeout evaluation
- return by value by default
- document that it executes in the preview page context
- Screenshot output should be bounded:
- max dimensions
- max base64 size
- return error if too large after scaling attempts
- Clear pending broker requests when desktop disconnects.
- CDP operations must timeout and detach debugger in `finally`.
## Failure Modes
Return typed errors for:
- no desktop client connected
- desktop client connected but preview unsupported
- no focused owner for thread
- preview panel not open and operation is not `preview_open`
- webview not initialized yet
- navigation timeout
- selector not found
- CDP debugger unavailable
- page execution error
- screenshot too large
- stale request id or response after timeout
## Tests
### Contracts
Add tests for:
- schema decoding for every preview automation input/result
- error schema decoding
- invalid selector/click union inputs rejected
- snapshot options defaulting
### Desktop Unit Tests
Add tests around `PreviewViewManager` helpers:
- owner-independent status when tab exists/does not exist
- selector summary script clamps output
- selector generation handles ids/classes/nth-child fallback
- error mapping for missing webContents
- screenshot result shape
Where Electron/CDP is hard to unit test, isolate pure helpers and cover IPC handler validation.
### Server Broker Tests
Add tests for:
- registering clients
- ownership updates
- focused owner wins
- request routed to focused owner
- request timeout
- client disconnect fails pending requests
- response with unknown request id ignored/rejected
- token scoped to thread/session
- remote loopback URL warning generated
### Web Client Tests
Add tests for:
- ownership report sent only in Electron preview-supported runtime
- opening preview panel on `preview_open`
- no route switch for background thread
- clear ownership on unmount
- response sent for successful and failed desktop bridge calls
### MCP Tests
Add tests for:
- tool list includes all expected preview tools
- each tool maps to internal bridge request
- token missing/invalid returns MCP error
- snapshot maps screenshot to MCP image content
- tool errors preserve tagged T3 error message
### Integration Tests
Add a focused integration test using mocked desktop client:
1. Start server broker.
2. Register fake desktop automation client.
3. Mark it focused for thread.
4. Invoke MCP `preview_open`.
5. Assert fake client received open request.
6. Respond success.
7. Assert MCP response is successful.
Add a second integration test:
1. No focused owner.
2. Invoke `preview_snapshot`.
3. Assert `PreviewAutomationNoFocusedOwnerError`.
## Validation Commands
Before completion:
- `vp check`
- `vp run typecheck`
- `vp test`
No `vp run lint:mobile` required unless mobile code is changed.
## Implementation Order
1. Add contracts for preview automation schemas and WS methods.
2. Add `PreviewAutomationBroker` server service.
3. Add WS stream bridge for desktop clients.
4. Add desktop IPC and `PreviewViewManager` CDP automation methods.
5. Add web ownership reporting and request handling.
6. Add private `/internal/preview-automation/tool` endpoint with scoped token auth.
7. Add `packages/preview-mcp` stdio MCP server.
8. Wire provider sessions to launch/register `t3-preview` MCP server where provider protocols support MCP config.
9. Add remote loopback URL warning.
10. Add tests.
11. Run validation commands.
## Assumptions
- v1 only supports Electron desktop preview clients.
- The active/focused thread preview is the right target for agent control.
- Manual client-reachable URLs are acceptable for remote dev servers.
- Full browser control includes `evaluate`.
- Stdio MCP is the agent-facing transport.
- A private server bridge behind the stdio MCP server is acceptable and necessary because the browser lives on the desktop client, not beside the remote agent.