Document browser preview phase 0.5 findings and plans
- Add phase 0 and 0.5 ADRs, findings, and spike notes - Update browser preview docs and supporting UI/test files - Record the chosen renderer, automation, recording, tunnel, and input decisions
This commit is contained in:
1 parent
c1792bc9a6
commit
d4ba9e9618
35 files changed
+5534
-90
No files matched your search
@@ -0,0 +1,35 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,40 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,32 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,33 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,23 @@
|
||||
# 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`.
|
||||
@@ -0,0 +1,23 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,27 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,24 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,33 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,33 @@
|
||||
# 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
|
||||
@@ -0,0 +1,38 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,24 @@
|
||||
# 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.
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# 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.
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
# 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.
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
*
|
||||
!.gitignore
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
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);
|
||||
});
|
||||
@@ -0,0 +1,736 @@
|
||||
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()}`);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<!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>
|
||||
@@ -0,0 +1,51 @@
|
||||
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 };
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
<!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>
|
||||
@@ -0,0 +1,191 @@
|
||||
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`);
|
||||
@@ -0,0 +1,243 @@
|
||||
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)]);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
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)]);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
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
@@ -161,6 +161,7 @@ import {
|
||||
type ElementContextDraft,
|
||||
formatElementContextLabel,
|
||||
} from "../lib/elementContext";
|
||||
import { appendPreviewAnnotationPrompt } from "../lib/previewAnnotation";
|
||||
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
|
||||
import { ExpandedImageDialog } from "./chat/ExpandedImageDialog";
|
||||
import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
|
||||
@@ -1111,6 +1112,9 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const setComposerDraftElementContexts = useComposerDraftStore(
|
||||
(store) => store.setElementContexts,
|
||||
);
|
||||
const setComposerDraftPreviewAnnotations = useComposerDraftStore(
|
||||
(store) => store.setPreviewAnnotations,
|
||||
);
|
||||
const setComposerDraftModelSelection = useComposerDraftStore((store) => store.setModelSelection);
|
||||
const setComposerDraftRuntimeMode = useComposerDraftStore((store) => store.setRuntimeMode);
|
||||
const setComposerDraftInteractionMode = useComposerDraftStore(
|
||||
@@ -3555,6 +3559,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
images: composerImages,
|
||||
terminalContexts: composerTerminalContexts,
|
||||
elementContexts: composerElementContexts,
|
||||
previewAnnotations: composerPreviewAnnotations,
|
||||
selectedProvider: ctxSelectedProvider,
|
||||
selectedModel: ctxSelectedModel,
|
||||
selectedProviderModels: ctxSelectedProviderModels,
|
||||
@@ -3571,7 +3576,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
prompt: promptForSend,
|
||||
imageCount: composerImages.length,
|
||||
terminalContexts: composerTerminalContexts,
|
||||
elementContextCount: composerElementContexts.length,
|
||||
elementContextCount: composerElementContexts.length + composerPreviewAnnotations.length,
|
||||
});
|
||||
if (showPlanFollowUpPrompt && activeProposedPlan) {
|
||||
const followUp = resolvePlanFollowUpSubmission({
|
||||
@@ -3590,7 +3595,8 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const standaloneSlashCommand =
|
||||
composerImages.length === 0 &&
|
||||
sendableComposerTerminalContexts.length === 0 &&
|
||||
composerElementContexts.length === 0
|
||||
composerElementContexts.length === 0 &&
|
||||
composerPreviewAnnotations.length === 0
|
||||
? parseStandaloneComposerSlashCommand(trimmed)
|
||||
: null;
|
||||
if (standaloneSlashCommand) {
|
||||
@@ -3639,10 +3645,15 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const composerImagesSnapshot = [...composerImages];
|
||||
const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts];
|
||||
const composerElementContextsSnapshot = [...composerElementContexts];
|
||||
const messageTextForSend = appendElementContextsToPrompt(
|
||||
const composerPreviewAnnotationsSnapshot = [...composerPreviewAnnotations];
|
||||
const messageTextWithContexts = appendElementContextsToPrompt(
|
||||
appendTerminalContextsToPrompt(promptForSend, composerTerminalContextsSnapshot),
|
||||
composerElementContextsSnapshot,
|
||||
);
|
||||
const messageTextForSend = composerPreviewAnnotationsSnapshot.reduce(
|
||||
(text, annotation) => appendPreviewAnnotationPrompt(text, annotation),
|
||||
messageTextWithContexts,
|
||||
);
|
||||
const messageIdForSend = newMessageId();
|
||||
const messageCreatedAt = new Date().toISOString();
|
||||
const outgoingMessageText = formatOutgoingPrompt({
|
||||
@@ -3810,7 +3821,9 @@ export default function ChatView(props: ChatViewProps) {
|
||||
promptRef.current.length === 0 &&
|
||||
composerImagesRef.current.length === 0 &&
|
||||
composerTerminalContextsRef.current.length === 0 &&
|
||||
composerElementContextsRef.current.length === 0
|
||||
composerElementContextsRef.current.length === 0 &&
|
||||
(useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.previewAnnotations
|
||||
.length ?? 0) === 0
|
||||
) {
|
||||
setOptimisticUserMessages((existing) => {
|
||||
const removed = existing.filter((message) => message.id === messageIdForSend);
|
||||
@@ -3829,6 +3842,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
addComposerDraftImages(composerDraftTarget, retryComposerImages);
|
||||
setComposerDraftTerminalContexts(composerDraftTarget, composerTerminalContextsSnapshot);
|
||||
setComposerDraftElementContexts(composerDraftTarget, composerElementContextsSnapshot);
|
||||
setComposerDraftPreviewAnnotations(composerDraftTarget, composerPreviewAnnotationsSnapshot);
|
||||
composerRef.current?.resetCursorState({
|
||||
cursor: collapseExpandedComposerCursor(promptForSend, promptForSend.length),
|
||||
prompt: promptForSend,
|
||||
|
||||
@@ -2,6 +2,7 @@ import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
ModelSelection,
|
||||
PreviewAnnotationPayload,
|
||||
ProviderApprovalDecision,
|
||||
ProviderInteractionMode,
|
||||
ResolvedKeybindingsConfig,
|
||||
@@ -55,6 +56,7 @@ import {
|
||||
import { useComposerPathSearch } from "../../lib/composerPathSearchState";
|
||||
import { type ElementContextDraft } from "../../lib/elementContext";
|
||||
import { ComposerPendingElementContexts } from "./ComposerPendingElementContexts";
|
||||
import { ComposerPreviewAnnotationCards } from "./ComposerPreviewAnnotationCards";
|
||||
import {
|
||||
shouldUseCompactComposerPrimaryActions,
|
||||
shouldUseCompactComposerFooter,
|
||||
@@ -403,6 +405,7 @@ export interface ChatComposerHandle {
|
||||
images: ComposerImageAttachment[];
|
||||
terminalContexts: TerminalContextDraft[];
|
||||
elementContexts: ElementContextDraft[];
|
||||
previewAnnotations: PreviewAnnotationPayload[];
|
||||
selectedPromptEffort: string | null;
|
||||
selectedModelOptionsForDispatch: unknown;
|
||||
selectedModelSelection: ModelSelection;
|
||||
@@ -611,6 +614,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const composerImages = composerDraft.images;
|
||||
const composerTerminalContexts = composerDraft.terminalContexts;
|
||||
const composerElementContexts = composerDraft.elementContexts;
|
||||
const composerPreviewAnnotations = composerDraft.previewAnnotations;
|
||||
const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds;
|
||||
|
||||
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
|
||||
@@ -629,6 +633,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const removeComposerDraftElementContext = useComposerDraftStore(
|
||||
(store) => store.removeElementContext,
|
||||
);
|
||||
const removeComposerDraftPreviewAnnotation = useComposerDraftStore(
|
||||
(store) => store.removePreviewAnnotation,
|
||||
);
|
||||
const clearComposerDraftPersistedAttachments = useComposerDraftStore(
|
||||
(store) => store.clearPersistedAttachments,
|
||||
);
|
||||
@@ -889,9 +896,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
prompt,
|
||||
imageCount: composerImages.length,
|
||||
terminalContexts: composerTerminalContexts,
|
||||
elementContextCount: composerElementContexts.length,
|
||||
elementContextCount: composerElementContexts.length + composerPreviewAnnotations.length,
|
||||
}),
|
||||
[composerElementContexts.length, composerImages.length, composerTerminalContexts, prompt],
|
||||
[
|
||||
composerElementContexts.length,
|
||||
composerImages.length,
|
||||
composerPreviewAnnotations.length,
|
||||
composerTerminalContexts,
|
||||
prompt,
|
||||
],
|
||||
);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -1984,6 +1997,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
images: composerImagesRef.current,
|
||||
terminalContexts: composerTerminalContextsRef.current,
|
||||
elementContexts: composerElementContextsRef.current,
|
||||
previewAnnotations: composerPreviewAnnotations,
|
||||
selectedPromptEffort,
|
||||
selectedModelOptionsForDispatch,
|
||||
selectedModelSelection,
|
||||
@@ -2002,6 +2016,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
composerImagesRef,
|
||||
composerTerminalContextsRef,
|
||||
composerElementContextsRef,
|
||||
composerPreviewAnnotations,
|
||||
isConnecting,
|
||||
isComposerApprovalState,
|
||||
pendingUserInputs.length,
|
||||
@@ -2239,6 +2254,24 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isComposerCollapsedMobile &&
|
||||
!isComposerApprovalState &&
|
||||
pendingUserInputs.length === 0 &&
|
||||
composerPreviewAnnotations.length > 0 && (
|
||||
<ComposerPreviewAnnotationCards
|
||||
annotations={composerPreviewAnnotations}
|
||||
images={composerImages}
|
||||
onRemove={(annotationId) =>
|
||||
removeComposerDraftPreviewAnnotation(composerDraftTarget, annotationId)
|
||||
}
|
||||
onExpandImage={(imageId) => {
|
||||
const preview = buildExpandedImagePreview(composerImages, imageId);
|
||||
if (preview) onExpandImage(preview);
|
||||
}}
|
||||
className="mb-3"
|
||||
/>
|
||||
)}
|
||||
|
||||
{!isComposerCollapsedMobile &&
|
||||
!isComposerApprovalState &&
|
||||
pendingUserInputs.length === 0 &&
|
||||
@@ -2255,68 +2288,78 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
{!isComposerCollapsedMobile &&
|
||||
!isComposerApprovalState &&
|
||||
pendingUserInputs.length === 0 &&
|
||||
composerImages.length > 0 && (
|
||||
composerImages.some(
|
||||
(image) =>
|
||||
!composerPreviewAnnotations.some((annotation) => annotation.id === image.id),
|
||||
) && (
|
||||
<div className="mb-3 flex flex-wrap gap-2">
|
||||
{composerImages.map((image) => (
|
||||
<div
|
||||
key={image.id}
|
||||
className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
|
||||
>
|
||||
{image.previewUrl ? (
|
||||
<button
|
||||
type="button"
|
||||
className="h-full w-full cursor-zoom-in"
|
||||
aria-label={`Preview ${image.name}`}
|
||||
onClick={() => {
|
||||
const preview = buildExpandedImagePreview(composerImages, image.id);
|
||||
if (!preview) return;
|
||||
onExpandImage(preview);
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={image.previewUrl}
|
||||
alt={image.name}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-muted-foreground/70">
|
||||
{image.name}
|
||||
</div>
|
||||
)}
|
||||
{nonPersistedComposerImageIdSet.has(image.id) && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
role="img"
|
||||
aria-label="Draft attachment may not persist"
|
||||
className="absolute left-1 top-1 inline-flex items-center justify-center rounded bg-background/85 p-0.5 text-amber-600"
|
||||
>
|
||||
<CircleAlertIcon className="size-3" />
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup
|
||||
side="top"
|
||||
className="max-w-64 whitespace-normal leading-tight"
|
||||
>
|
||||
Draft attachment could not be saved locally and may be lost on
|
||||
navigation.
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="absolute right-1 top-1 bg-background/80 hover:bg-background/90"
|
||||
onClick={() => removeComposerImage(image.id)}
|
||||
aria-label={`Remove ${image.name}`}
|
||||
{composerImages
|
||||
.filter(
|
||||
(image) =>
|
||||
!composerPreviewAnnotations.some(
|
||||
(annotation) => annotation.id === image.id,
|
||||
),
|
||||
)
|
||||
.map((image) => (
|
||||
<div
|
||||
key={image.id}
|
||||
className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
|
||||
>
|
||||
<XIcon />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
{image.previewUrl ? (
|
||||
<button
|
||||
type="button"
|
||||
className="h-full w-full cursor-zoom-in"
|
||||
aria-label={`Preview ${image.name}`}
|
||||
onClick={() => {
|
||||
const preview = buildExpandedImagePreview(composerImages, image.id);
|
||||
if (!preview) return;
|
||||
onExpandImage(preview);
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={image.previewUrl}
|
||||
alt={image.name}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-muted-foreground/70">
|
||||
{image.name}
|
||||
</div>
|
||||
)}
|
||||
{nonPersistedComposerImageIdSet.has(image.id) && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
role="img"
|
||||
aria-label="Draft attachment may not persist"
|
||||
className="absolute left-1 top-1 inline-flex items-center justify-center rounded bg-background/85 p-0.5 text-amber-600"
|
||||
>
|
||||
<CircleAlertIcon className="size-3" />
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup
|
||||
side="top"
|
||||
className="max-w-64 whitespace-normal leading-tight"
|
||||
>
|
||||
Draft attachment could not be saved locally and may be lost on
|
||||
navigation.
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="absolute right-1 top-1 bg-background/80 hover:bg-background/90"
|
||||
onClick={() => removeComposerImage(image.id)}
|
||||
aria-label={`Remove ${image.name}`}
|
||||
>
|
||||
<XIcon />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { PreviewAnnotationPayload } from "@t3tools/contracts";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { ComposerPreviewAnnotationCards } from "./ComposerPreviewAnnotationCards";
|
||||
|
||||
const annotation: PreviewAnnotationPayload = {
|
||||
id: "annotation_1",
|
||||
pageUrl: "http://localhost:3000/welcome",
|
||||
pageTitle: "Welcome",
|
||||
comment: "Make this headline feel intentional.",
|
||||
elements: [],
|
||||
regions: [{ id: "region_1", rect: { x: 1, y: 2, width: 30, height: 20 } }],
|
||||
strokes: [],
|
||||
styleChanges: [
|
||||
{
|
||||
targetId: "element_1",
|
||||
selector: "h1",
|
||||
property: "font-size",
|
||||
previousValue: "32px",
|
||||
value: "40px",
|
||||
},
|
||||
],
|
||||
screenshot: null,
|
||||
createdAt: "2026-06-13T00:00:00.000Z",
|
||||
};
|
||||
|
||||
describe("ComposerPreviewAnnotationCards", () => {
|
||||
it("presents the annotation as one contextual attachment", () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ComposerPreviewAnnotationCards
|
||||
annotations={[annotation]}
|
||||
images={[]}
|
||||
onRemove={vi.fn()}
|
||||
onExpandImage={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("Make this headline feel intentional.");
|
||||
expect(markup).toContain('title="1 region"');
|
||||
expect(markup).toContain('title="1 style change"');
|
||||
expect(markup).not.toContain("Welcome");
|
||||
expect(markup).not.toContain("localhost:3000");
|
||||
expect(markup).not.toContain("Preview annotation");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
import type { PreviewAnnotationPayload } from "@t3tools/contracts";
|
||||
import { Frame, MousePointerClick, Paintbrush, PenLine, X } from "lucide-react";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import type { ComposerImageAttachment } from "~/composerDraftStore";
|
||||
import { formatElementContextLabel, normalizeElementContextSelection } from "~/lib/elementContext";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
interface ComposerPreviewAnnotationCardsProps {
|
||||
annotations: ReadonlyArray<PreviewAnnotationPayload>;
|
||||
images: ReadonlyArray<ComposerImageAttachment>;
|
||||
onRemove: (annotationId: string) => void;
|
||||
onExpandImage: (imageId: string) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function TargetStat(props: { icon: ReactNode; count: number; label: string }) {
|
||||
return (
|
||||
<span
|
||||
className="inline-flex items-center gap-1 text-[10px] font-medium text-muted-foreground"
|
||||
title={`${props.count} ${props.label}${props.count === 1 ? "" : "s"}`}
|
||||
>
|
||||
{props.icon}
|
||||
{props.count}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function ComposerPreviewAnnotationCards({
|
||||
annotations,
|
||||
images,
|
||||
onRemove,
|
||||
onExpandImage,
|
||||
className,
|
||||
}: ComposerPreviewAnnotationCardsProps) {
|
||||
if (annotations.length === 0) return null;
|
||||
const imagesById = new Map(images.map((image) => [image.id, image]));
|
||||
|
||||
return (
|
||||
<div className={cn("flex flex-wrap gap-1.5", className)}>
|
||||
{annotations.map((annotation) => {
|
||||
const image = imagesById.get(annotation.id);
|
||||
const elementLabels = annotation.elements.flatMap((target) => {
|
||||
const context = normalizeElementContextSelection(target.element);
|
||||
return context ? [{ id: target.id, label: formatElementContextLabel(context) }] : [];
|
||||
});
|
||||
return (
|
||||
<section
|
||||
key={annotation.id}
|
||||
className="group/preview-annotation relative flex min-w-0 max-w-full items-center overflow-hidden rounded-lg border border-border/80 bg-background/72"
|
||||
>
|
||||
{image?.previewUrl ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Preview ${image.name}`}
|
||||
className="size-14 shrink-0 cursor-zoom-in overflow-hidden border-r border-border/70 bg-muted"
|
||||
onClick={() => onExpandImage(image.id)}
|
||||
>
|
||||
<img
|
||||
src={image.previewUrl}
|
||||
alt="Annotated preview crop"
|
||||
className="size-full object-cover transition duration-200 group-hover/preview-annotation:scale-[1.03]"
|
||||
/>
|
||||
</button>
|
||||
) : (
|
||||
<span className="grid size-10 shrink-0 place-items-center border-r border-border/70 text-blue-500">
|
||||
<MousePointerClick className="size-3.5" />
|
||||
</span>
|
||||
)}
|
||||
<div className="min-w-0 px-2.5 py-2 pr-8">
|
||||
{annotation.comment.trim() ? (
|
||||
<p className="max-w-80 truncate text-xs font-medium text-foreground/90">
|
||||
{annotation.comment.trim()}
|
||||
</p>
|
||||
) : null}
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-w-0 items-center gap-2",
|
||||
annotation.comment.trim() && "mt-1",
|
||||
)}
|
||||
>
|
||||
{elementLabels.length > 0 ? (
|
||||
<div className="flex min-w-0 items-center gap-1">
|
||||
{elementLabels.slice(0, 2).map(({ id, label }) => (
|
||||
<span
|
||||
key={id}
|
||||
className="max-w-40 truncate font-mono text-[10px] text-foreground/65"
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
))}
|
||||
{elementLabels.length > 2 ? (
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
+{elementLabels.length - 2}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{annotation.elements.length > 0 ? (
|
||||
<TargetStat
|
||||
icon={<MousePointerClick className="size-3" />}
|
||||
count={annotation.elements.length}
|
||||
label="element"
|
||||
/>
|
||||
) : null}
|
||||
{annotation.regions.length > 0 ? (
|
||||
<TargetStat
|
||||
icon={<Frame className="size-3" />}
|
||||
count={annotation.regions.length}
|
||||
label="region"
|
||||
/>
|
||||
) : null}
|
||||
{annotation.strokes.length > 0 ? (
|
||||
<TargetStat
|
||||
icon={<PenLine className="size-3" />}
|
||||
count={annotation.strokes.length}
|
||||
label="drawing"
|
||||
/>
|
||||
) : null}
|
||||
{annotation.styleChanges.length > 0 ? (
|
||||
<TargetStat
|
||||
icon={<Paintbrush className="size-3" />}
|
||||
count={annotation.styleChanges.length}
|
||||
label="style change"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Remove preview annotation"
|
||||
className="absolute right-1.5 top-1.5 grid size-5 place-items-center rounded text-muted-foreground/60 transition hover:bg-muted hover:text-foreground"
|
||||
onClick={() => onRemove(annotation.id)}
|
||||
>
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -49,6 +49,7 @@ import {
|
||||
HammerIcon,
|
||||
MessageCircleIcon,
|
||||
MousePointerClickIcon,
|
||||
PaintbrushIcon,
|
||||
MinusIcon,
|
||||
SquarePenIcon,
|
||||
TerminalIcon,
|
||||
@@ -83,6 +84,10 @@ import {
|
||||
extractTrailingElementContexts,
|
||||
type ParsedElementContextEntry,
|
||||
} from "~/lib/elementContext";
|
||||
import {
|
||||
extractTrailingPreviewAnnotation,
|
||||
type ParsedPreviewAnnotation,
|
||||
} from "~/lib/previewAnnotation";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { useUiStateStore } from "~/uiStateStore";
|
||||
import { type TimestampFormat } from "@t3tools/contracts/settings";
|
||||
@@ -433,15 +438,25 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
|
||||
const userImages = row.message.attachments ?? [];
|
||||
const displayedUserMessage = deriveDisplayedUserMessageState(row.message.text);
|
||||
const terminalContexts = displayedUserMessage.contexts;
|
||||
const elementContextState = extractTrailingElementContexts(displayedUserMessage.visibleText);
|
||||
const previewAnnotations: ParsedPreviewAnnotation[] = [];
|
||||
let visibleText = displayedUserMessage.visibleText;
|
||||
while (true) {
|
||||
const extracted = extractTrailingPreviewAnnotation(visibleText);
|
||||
if (!extracted.annotation) break;
|
||||
previewAnnotations.unshift(extracted.annotation);
|
||||
visibleText = extracted.promptText;
|
||||
}
|
||||
const elementContextState = extractTrailingElementContexts(visibleText);
|
||||
const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));
|
||||
const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-"));
|
||||
const canRevertAgentWork = typeof row.revertTurnCount === "number";
|
||||
|
||||
return (
|
||||
<div className="group flex flex-col items-end gap-1">
|
||||
<div className="relative max-w-[80%] rounded-2xl border border-border bg-secondary p-3">
|
||||
{userImages.length > 0 && (
|
||||
{regularImages.length > 0 && (
|
||||
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
|
||||
{userImages.map((image: NonNullable<TimelineMessage["attachments"]>[number]) => (
|
||||
{regularImages.map((image: NonNullable<TimelineMessage["attachments"]>[number]) => (
|
||||
<div
|
||||
key={image.id}
|
||||
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
|
||||
@@ -452,7 +467,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
|
||||
className="h-full w-full cursor-zoom-in"
|
||||
aria-label={`Preview ${image.name}`}
|
||||
onClick={() => {
|
||||
const preview = buildExpandedImagePreview(userImages, image.id);
|
||||
const preview = buildExpandedImagePreview(regularImages, image.id);
|
||||
if (!preview) return;
|
||||
ctx.onImageExpand(preview);
|
||||
}}
|
||||
@@ -472,6 +487,13 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{previewAnnotations.map((annotation, index) => (
|
||||
<UserMessagePreviewAnnotationCard
|
||||
key={annotation.id}
|
||||
annotation={annotation}
|
||||
image={previewImages[index] ?? null}
|
||||
/>
|
||||
))}
|
||||
{elementContextState.contexts.length > 0 ? (
|
||||
<div className="mb-2 flex flex-wrap gap-1.5">
|
||||
{elementContextState.contexts.map((context) => (
|
||||
@@ -944,6 +966,58 @@ const UserMessageElementContextChip = memo(function UserMessageElementContextChi
|
||||
);
|
||||
});
|
||||
|
||||
function UserMessagePreviewAnnotationCard(props: {
|
||||
annotation: ParsedPreviewAnnotation;
|
||||
image: NonNullable<TimelineMessage["attachments"]>[number] | null;
|
||||
}) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
return (
|
||||
<div className="mb-2 flex max-w-full items-center overflow-hidden rounded-lg border border-border/70 bg-background/70">
|
||||
{props.image?.previewUrl ? (
|
||||
<button
|
||||
type="button"
|
||||
className="size-14 shrink-0 cursor-zoom-in overflow-hidden border-r border-border/70 bg-muted"
|
||||
aria-label={`Preview ${props.image.name}`}
|
||||
onClick={() => {
|
||||
if (!props.image) return;
|
||||
const preview = buildExpandedImagePreview([props.image], props.image.id);
|
||||
if (preview) ctx.onImageExpand(preview);
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={props.image.previewUrl}
|
||||
alt="Annotated preview crop"
|
||||
className="size-full object-cover"
|
||||
/>
|
||||
</button>
|
||||
) : null}
|
||||
<div className="min-w-0 px-2.5 py-2">
|
||||
{props.annotation.comment ? (
|
||||
<div className="max-w-80 truncate text-xs font-medium text-foreground/90">
|
||||
{props.annotation.comment}
|
||||
</div>
|
||||
) : null}
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-[10px] text-muted-foreground",
|
||||
props.annotation.comment && "mt-1",
|
||||
)}
|
||||
>
|
||||
{props.annotation.targetSummary ? (
|
||||
<span className="truncate">{props.annotation.targetSummary}</span>
|
||||
) : null}
|
||||
{props.annotation.styleChanges.length > 0 ? (
|
||||
<span className="inline-flex shrink-0 items-center gap-1">
|
||||
<PaintbrushIcon className="size-3" />
|
||||
{props.annotation.styleChanges.length}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const MAX_COLLAPSED_USER_MESSAGE_LINES = 8;
|
||||
const MAX_COLLAPSED_USER_MESSAGE_LENGTH = 600;
|
||||
const COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM = 1.75;
|
||||
|
||||
@@ -6,11 +6,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { useComposerDraftStore } from "~/composerDraftStore";
|
||||
import { ensureEnvironmentApi } from "~/environmentApi";
|
||||
import { normalizeElementContextSelection } from "~/lib/elementContext";
|
||||
import {
|
||||
appendPreviewAnnotationPrompt,
|
||||
previewAnnotationScreenshotFile,
|
||||
} from "~/lib/previewAnnotation";
|
||||
import { previewAnnotationScreenshotFile } from "~/lib/previewAnnotation";
|
||||
import { ensureLocalApi } from "~/localApi";
|
||||
import { selectThreadPreviewState, usePreviewStateStore } from "~/previewStateStore";
|
||||
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
|
||||
@@ -62,10 +58,8 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
);
|
||||
const applyServerSnapshot = usePreviewStateStore((state) => state.applyServerSnapshot);
|
||||
const rememberUrl = usePreviewStateStore((state) => state.rememberUrl);
|
||||
const addElementContext = useComposerDraftStore((store) => store.addElementContext);
|
||||
const addPreviewAnnotation = useComposerDraftStore((store) => store.addPreviewAnnotation);
|
||||
const addImage = useComposerDraftStore((store) => store.addImage);
|
||||
const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft);
|
||||
const setPrompt = useComposerDraftStore((store) => store.setPrompt);
|
||||
|
||||
usePreviewSession(threadRef);
|
||||
|
||||
@@ -421,12 +415,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
try {
|
||||
const annotation = await previewBridge.pickElement(tabId);
|
||||
if (!annotation) return;
|
||||
for (const target of annotation.elements) {
|
||||
const selection = normalizeElementContextSelection(target.element);
|
||||
if (selection) addElementContext(threadRef, selection);
|
||||
}
|
||||
const currentPrompt = getComposerDraft(threadRef)?.prompt ?? "";
|
||||
setPrompt(threadRef, appendPreviewAnnotationPrompt(currentPrompt, annotation));
|
||||
addPreviewAnnotation(threadRef, annotation);
|
||||
const screenshotFile = await previewAnnotationScreenshotFile(annotation);
|
||||
if (screenshotFile && annotation.screenshot) {
|
||||
addImage(threadRef, {
|
||||
@@ -462,7 +451,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
}
|
||||
}
|
||||
})();
|
||||
}, [addElementContext, addImage, getComposerDraft, setPrompt, tabId, threadRef]);
|
||||
}, [addImage, addPreviewAnnotation, tabId, threadRef]);
|
||||
|
||||
// If the active tab changes mid-pick (close, thread switch, hot restart),
|
||||
// tell main to tear down the in-flight session AND reset our local toggle
|
||||
|
||||
@@ -9,6 +9,8 @@ import {
|
||||
ProviderInteractionMode,
|
||||
ProviderDriverKind,
|
||||
ProviderOptionSelection,
|
||||
PreviewAnnotationPayloadSchema,
|
||||
type PreviewAnnotationPayload,
|
||||
RuntimeMode,
|
||||
type ServerProvider,
|
||||
type ScopedProjectRef,
|
||||
@@ -52,7 +54,7 @@ const isRuntimeMode = Schema.is(RuntimeMode);
|
||||
const isProviderDriverKind = Schema.is(ProviderDriverKind);
|
||||
|
||||
export const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1";
|
||||
const COMPOSER_DRAFT_STORAGE_VERSION = 6;
|
||||
const COMPOSER_DRAFT_STORAGE_VERSION = 7;
|
||||
const DraftThreadEnvModeSchema = Schema.Literals(["local", "worktree"]);
|
||||
export type DraftThreadEnvMode = typeof DraftThreadEnvModeSchema.Type;
|
||||
|
||||
@@ -125,6 +127,7 @@ const PersistedComposerThreadDraftState = Schema.Struct({
|
||||
attachments: Schema.Array(PersistedComposerImageAttachment),
|
||||
terminalContexts: Schema.optionalKey(Schema.Array(PersistedTerminalContextDraft)),
|
||||
elementContexts: Schema.optionalKey(Schema.Array(PersistedElementContextDraft)),
|
||||
previewAnnotations: Schema.optionalKey(Schema.Array(PreviewAnnotationPayloadSchema)),
|
||||
// Keyed by `ProviderInstanceId` (open branded slug) so custom provider
|
||||
// instances (e.g. `codex_personal`) round-trip alongside the built-in
|
||||
// `codex` / `claudeAgent` / ... entries. Every prior `ProviderDriverKind`
|
||||
@@ -252,6 +255,7 @@ export interface ComposerThreadDraftState {
|
||||
* re-derive the snapshot from on reload.
|
||||
*/
|
||||
elementContexts: ElementContextDraft[];
|
||||
previewAnnotations: PreviewAnnotationPayload[];
|
||||
/**
|
||||
* Per-instance model selection. Keyed by `ProviderInstanceId` (open
|
||||
* branded slug) so a default `codex` instance and a user-authored
|
||||
@@ -451,6 +455,15 @@ interface ComposerDraftStoreState {
|
||||
) => void;
|
||||
removeElementContext: (threadRef: ComposerThreadTarget, contextId: string) => void;
|
||||
clearElementContexts: (threadRef: ComposerThreadTarget) => void;
|
||||
addPreviewAnnotation: (
|
||||
threadRef: ComposerThreadTarget,
|
||||
annotation: PreviewAnnotationPayload,
|
||||
) => void;
|
||||
setPreviewAnnotations: (
|
||||
threadRef: ComposerThreadTarget,
|
||||
annotations: ReadonlyArray<PreviewAnnotationPayload>,
|
||||
) => void;
|
||||
removePreviewAnnotation: (threadRef: ComposerThreadTarget, annotationId: string) => void;
|
||||
clearPersistedAttachments: (threadRef: ComposerThreadTarget) => void;
|
||||
syncPersistedAttachments: (
|
||||
threadRef: ComposerThreadTarget,
|
||||
@@ -527,10 +540,12 @@ const EMPTY_IDS: string[] = [];
|
||||
const EMPTY_PERSISTED_ATTACHMENTS: PersistedComposerImageAttachment[] = [];
|
||||
const EMPTY_TERMINAL_CONTEXTS: TerminalContextDraft[] = [];
|
||||
const EMPTY_ELEMENT_CONTEXTS: ElementContextDraft[] = [];
|
||||
const EMPTY_PREVIEW_ANNOTATIONS: PreviewAnnotationPayload[] = [];
|
||||
Object.freeze(EMPTY_IMAGES);
|
||||
Object.freeze(EMPTY_IDS);
|
||||
Object.freeze(EMPTY_PERSISTED_ATTACHMENTS);
|
||||
Object.freeze(EMPTY_ELEMENT_CONTEXTS);
|
||||
Object.freeze(EMPTY_PREVIEW_ANNOTATIONS);
|
||||
const EMPTY_MODEL_SELECTION_BY_PROVIDER: Partial<Record<ProviderDriverKind, ModelSelection>> =
|
||||
Object.freeze({});
|
||||
const EMPTY_COMPOSER_DRAFT_MODEL_STATE = Object.freeze<ComposerDraftModelState>({
|
||||
@@ -545,6 +560,7 @@ const EMPTY_THREAD_DRAFT = Object.freeze<ComposerThreadDraftState>({
|
||||
persistedAttachments: EMPTY_PERSISTED_ATTACHMENTS,
|
||||
terminalContexts: EMPTY_TERMINAL_CONTEXTS,
|
||||
elementContexts: EMPTY_ELEMENT_CONTEXTS,
|
||||
previewAnnotations: EMPTY_PREVIEW_ANNOTATIONS,
|
||||
modelSelectionByProvider: EMPTY_MODEL_SELECTION_BY_PROVIDER,
|
||||
activeProvider: null,
|
||||
runtimeMode: null,
|
||||
@@ -565,6 +581,7 @@ export function createEmptyThreadDraft(): ComposerThreadDraftState {
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
elementContexts: [],
|
||||
previewAnnotations: [],
|
||||
modelSelectionByProvider: {},
|
||||
activeProvider: null,
|
||||
runtimeMode: null,
|
||||
@@ -636,6 +653,7 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
|
||||
draft.persistedAttachments.length === 0 &&
|
||||
draft.terminalContexts.length === 0 &&
|
||||
draft.elementContexts.length === 0 &&
|
||||
draft.previewAnnotations.length === 0 &&
|
||||
Object.keys(draft.modelSelectionByProvider).length === 0 &&
|
||||
draft.activeProvider === null &&
|
||||
draft.runtimeMode === null &&
|
||||
@@ -1776,6 +1794,7 @@ function partializeComposerDraftStoreState(
|
||||
draft.persistedAttachments.length === 0 &&
|
||||
draft.terminalContexts.length === 0 &&
|
||||
draft.elementContexts.length === 0 &&
|
||||
draft.previewAnnotations.length === 0 &&
|
||||
!hasModelData &&
|
||||
draft.runtimeMode === null &&
|
||||
draft.interactionMode === null
|
||||
@@ -1815,6 +1834,13 @@ function partializeComposerDraftStoreState(
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
...(draft.previewAnnotations.length > 0
|
||||
? {
|
||||
previewAnnotations: draft.previewAnnotations.map(
|
||||
(annotation) => ({ ...annotation }) as DeepMutable<PreviewAnnotationPayload>,
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
...(hasModelData
|
||||
? {
|
||||
modelSelectionByProvider: compactModelSelectionByProvider(
|
||||
@@ -2055,6 +2081,8 @@ function toHydratedThreadDraft(
|
||||
persistedDraft.elementContexts?.map((context) => ({
|
||||
...context,
|
||||
})) ?? [],
|
||||
previewAnnotations:
|
||||
persistedDraft.previewAnnotations?.map((annotation) => ({ ...annotation })) ?? [],
|
||||
modelSelectionByProvider,
|
||||
activeProvider,
|
||||
runtimeMode: persistedDraft.runtimeMode ?? null,
|
||||
@@ -3057,6 +3085,69 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
return { draftsByThreadKey: nextDraftsByThreadKey };
|
||||
});
|
||||
},
|
||||
addPreviewAnnotation: (threadRef, annotation) => {
|
||||
const threadKey = resolveComposerDraftKey(get(), threadRef);
|
||||
if (!threadKey) return;
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
|
||||
const nextAnnotations = existing.previewAnnotations.filter(
|
||||
(entry) => entry.id !== annotation.id,
|
||||
);
|
||||
const compactAnnotation: PreviewAnnotationPayload = {
|
||||
...annotation,
|
||||
screenshot: annotation.screenshot ? { ...annotation.screenshot, dataUrl: "" } : null,
|
||||
};
|
||||
return {
|
||||
draftsByThreadKey: {
|
||||
...state.draftsByThreadKey,
|
||||
[threadKey]: {
|
||||
...existing,
|
||||
previewAnnotations: [...nextAnnotations, compactAnnotation],
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
setPreviewAnnotations: (threadRef, annotations) => {
|
||||
const threadKey = resolveComposerDraftKey(get(), threadRef);
|
||||
if (!threadKey) return;
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadKey[threadKey] ?? createEmptyThreadDraft();
|
||||
return {
|
||||
draftsByThreadKey: {
|
||||
...state.draftsByThreadKey,
|
||||
[threadKey]: { ...existing, previewAnnotations: [...annotations] },
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
removePreviewAnnotation: (threadRef, annotationId) => {
|
||||
const threadKey = resolveComposerDraftKey(get(), threadRef);
|
||||
if (!threadKey || !annotationId) return;
|
||||
set((state) => {
|
||||
const current = state.draftsByThreadKey[threadKey];
|
||||
if (!current) return state;
|
||||
const previewAnnotations = current.previewAnnotations.filter(
|
||||
(entry) => entry.id !== annotationId,
|
||||
);
|
||||
if (previewAnnotations.length === current.previewAnnotations.length) return state;
|
||||
const nextDraft = {
|
||||
...current,
|
||||
previewAnnotations,
|
||||
images: current.images.filter((image) => image.id !== annotationId),
|
||||
persistedAttachments: current.persistedAttachments.filter(
|
||||
(image) => image.id !== annotationId,
|
||||
),
|
||||
nonPersistedImageIds: current.nonPersistedImageIds.filter(
|
||||
(imageId) => imageId !== annotationId,
|
||||
),
|
||||
};
|
||||
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
||||
if (shouldRemoveDraft(nextDraft)) delete nextDraftsByThreadKey[threadKey];
|
||||
else nextDraftsByThreadKey[threadKey] = nextDraft;
|
||||
return { draftsByThreadKey: nextDraftsByThreadKey };
|
||||
});
|
||||
},
|
||||
clearPersistedAttachments: (threadRef) => {
|
||||
const threadKey = resolveComposerDraftKey(get(), threadRef) ?? "";
|
||||
if (threadKey.length === 0) {
|
||||
@@ -3130,6 +3221,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
elementContexts: [],
|
||||
previewAnnotations: [],
|
||||
};
|
||||
const nextDraftsByThreadKey = { ...state.draftsByThreadKey };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import type { PreviewAnnotationPayload } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { appendPreviewAnnotationPrompt, buildPreviewAnnotationPrompt } from "./previewAnnotation";
|
||||
import {
|
||||
appendPreviewAnnotationPrompt,
|
||||
buildPreviewAnnotationPrompt,
|
||||
extractTrailingPreviewAnnotation,
|
||||
} from "./previewAnnotation";
|
||||
|
||||
const annotation: PreviewAnnotationPayload = {
|
||||
id: "annotation_1",
|
||||
@@ -53,8 +57,31 @@ describe("preview annotations", () => {
|
||||
it("appends to an existing composer prompt", () => {
|
||||
expect(
|
||||
appendPreviewAnnotationPrompt("Fix this", annotation).startsWith(
|
||||
"Fix this\n\nPreview annotation:",
|
||||
"Fix this\n\n<preview_annotation>",
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("extracts annotation presentation from a sent prompt", () => {
|
||||
const result = extractTrailingPreviewAnnotation(
|
||||
appendPreviewAnnotationPrompt("Fix this", annotation),
|
||||
);
|
||||
expect(result.promptText).toBe("Fix this");
|
||||
expect(result.annotation).toMatchObject({
|
||||
title: "Example",
|
||||
targetSummary: "1 marked region, 1 drawing.",
|
||||
hasScreenshot: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("extracts multiple trailing annotations one at a time", () => {
|
||||
const first = appendPreviewAnnotationPrompt("Fix this", annotation);
|
||||
const secondAnnotation = { ...annotation, id: "annotation_2", pageTitle: "Details" };
|
||||
const second = appendPreviewAnnotationPrompt(first, secondAnnotation);
|
||||
const extractedSecond = extractTrailingPreviewAnnotation(second);
|
||||
const extractedFirst = extractTrailingPreviewAnnotation(extractedSecond.promptText);
|
||||
expect(extractedSecond.annotation?.id).toBe("annotation_2");
|
||||
expect(extractedFirst.annotation?.id).toBe("annotation_1");
|
||||
expect(extractedFirst.promptText).toBe("Fix this");
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,29 @@
|
||||
import type { PreviewAnnotationPayload } from "@t3tools/contracts";
|
||||
import { buildElementContextBlock, normalizeElementContextSelection } from "./elementContext";
|
||||
|
||||
const TRAILING_PREVIEW_ANNOTATION_BLOCK_PATTERN =
|
||||
/\n*<preview_annotation>\n((?:(?!<preview_annotation>)[\s\S])*)\n<\/preview_annotation>\s*$/;
|
||||
|
||||
export interface ParsedPreviewAnnotation {
|
||||
id: string;
|
||||
title: string;
|
||||
comment: string;
|
||||
targetSummary: string;
|
||||
styleChanges: string[];
|
||||
hasScreenshot: boolean;
|
||||
}
|
||||
|
||||
export interface ExtractedPreviewAnnotation {
|
||||
promptText: string;
|
||||
annotation: ParsedPreviewAnnotation | null;
|
||||
}
|
||||
|
||||
export function buildPreviewAnnotationPrompt(annotation: PreviewAnnotationPayload): string {
|
||||
const lines = ["Preview annotation:"];
|
||||
if (annotation.comment.trim()) lines.push(annotation.comment.trim());
|
||||
lines.push(`Id: ${annotation.id}`);
|
||||
const title = annotation.pageTitle?.trim() || annotation.pageUrl.trim() || "Preview";
|
||||
lines.push(`Page: ${title}`);
|
||||
if (annotation.comment.trim()) lines.push(`Comment: ${annotation.comment.trim()}`);
|
||||
const targets: string[] = [];
|
||||
if (annotation.elements.length > 0) {
|
||||
targets.push(
|
||||
@@ -29,7 +50,12 @@ export function buildPreviewAnnotationPrompt(annotation: PreviewAnnotationPayloa
|
||||
if (annotation.screenshot) {
|
||||
lines.push("The attached screenshot is the annotated preview crop.");
|
||||
}
|
||||
return lines.join("\n");
|
||||
const elementContexts = annotation.elements
|
||||
.map((target) => normalizeElementContextSelection(target.element))
|
||||
.filter((context) => context !== null);
|
||||
const elementBlock = buildElementContextBlock(elementContexts);
|
||||
if (elementBlock) lines.push(elementBlock);
|
||||
return ["<preview_annotation>", ...lines, "</preview_annotation>"].join("\n");
|
||||
}
|
||||
|
||||
export function appendPreviewAnnotationPrompt(
|
||||
@@ -41,6 +67,38 @@ export function appendPreviewAnnotationPrompt(
|
||||
return trimmed ? `${trimmed}\n\n${annotationText}` : annotationText;
|
||||
}
|
||||
|
||||
export function extractTrailingPreviewAnnotation(prompt: string): ExtractedPreviewAnnotation {
|
||||
const match = TRAILING_PREVIEW_ANNOTATION_BLOCK_PATTERN.exec(prompt);
|
||||
if (!match) return { promptText: prompt, annotation: null };
|
||||
const body = match[1] ?? "";
|
||||
const lines = body.split("\n");
|
||||
const pageLine = lines.find((line) => line.startsWith("Page: "));
|
||||
const idLine = lines.find((line) => line.startsWith("Id: "));
|
||||
const commentLine = lines.find((line) => line.startsWith("Comment: "));
|
||||
const targetsLine = lines.find((line) => line.startsWith("Targets: "));
|
||||
const styleHeadingIndex = lines.indexOf("Requested visual changes:");
|
||||
const linesAfterStyleHeading = lines.slice(styleHeadingIndex + 1);
|
||||
const elementContextIndex = linesAfterStyleHeading.indexOf("<element_context>");
|
||||
const styleChanges =
|
||||
styleHeadingIndex < 0
|
||||
? []
|
||||
: linesAfterStyleHeading
|
||||
.slice(0, elementContextIndex < 0 ? undefined : elementContextIndex)
|
||||
.filter((line) => line.startsWith("- "))
|
||||
.map((line) => line.slice(2));
|
||||
return {
|
||||
promptText: prompt.slice(0, match.index).replace(/\n+$/, ""),
|
||||
annotation: {
|
||||
id: idLine?.slice("Id: ".length).trim() || `${match.index}`,
|
||||
title: pageLine?.slice("Page: ".length).trim() || "Preview annotation",
|
||||
comment: commentLine?.slice("Comment: ".length).trim() || "",
|
||||
targetSummary: targetsLine?.slice("Targets: ".length).trim() || "",
|
||||
styleChanges,
|
||||
hasScreenshot: body.includes("The attached screenshot is the annotated preview crop."),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function previewAnnotationScreenshotFile(
|
||||
annotation: PreviewAnnotationPayload,
|
||||
): Promise<File | null> {
|
||||
|
||||
Reference in new issue
Block a user