@full-self-browsing/phantom-stream 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +263 -0
  3. package/bin/phantom-stream.js +193 -0
  4. package/dist/types/adapters/bookmarklet.d.ts +22 -0
  5. package/dist/types/adapters/bookmarklet.d.ts.map +1 -0
  6. package/dist/types/adapters/browser-inject.d.ts +7 -0
  7. package/dist/types/adapters/browser-inject.d.ts.map +1 -0
  8. package/dist/types/adapters/extension.d.ts +43 -0
  9. package/dist/types/adapters/extension.d.ts.map +1 -0
  10. package/dist/types/adapters/playwright-inject.d.ts +2 -0
  11. package/dist/types/adapters/playwright-inject.d.ts.map +1 -0
  12. package/dist/types/adapters/playwright.d.ts +14 -0
  13. package/dist/types/adapters/playwright.d.ts.map +1 -0
  14. package/dist/types/capture/index.d.ts +241 -0
  15. package/dist/types/capture/index.d.ts.map +1 -0
  16. package/dist/types/index.d.ts +6 -0
  17. package/dist/types/index.d.ts.map +1 -0
  18. package/dist/types/protocol/constants.d.ts +35 -0
  19. package/dist/types/protocol/constants.d.ts.map +1 -0
  20. package/dist/types/protocol/envelope.d.ts +41 -0
  21. package/dist/types/protocol/envelope.d.ts.map +1 -0
  22. package/dist/types/protocol/index.d.ts +5 -0
  23. package/dist/types/protocol/index.d.ts.map +1 -0
  24. package/dist/types/protocol/messages.d.ts +520 -0
  25. package/dist/types/protocol/messages.d.ts.map +1 -0
  26. package/dist/types/protocol/remote-control.d.ts +70 -0
  27. package/dist/types/protocol/remote-control.d.ts.map +1 -0
  28. package/dist/types/relay/backends/ws.d.ts +39 -0
  29. package/dist/types/relay/backends/ws.d.ts.map +1 -0
  30. package/dist/types/relay/index.d.ts +4 -0
  31. package/dist/types/relay/index.d.ts.map +1 -0
  32. package/dist/types/relay/limits.d.ts +54 -0
  33. package/dist/types/relay/limits.d.ts.map +1 -0
  34. package/dist/types/relay/relay.d.ts +73 -0
  35. package/dist/types/relay/relay.d.ts.map +1 -0
  36. package/dist/types/renderer/diff.d.ts +62 -0
  37. package/dist/types/renderer/diff.d.ts.map +1 -0
  38. package/dist/types/renderer/index.d.ts +211 -0
  39. package/dist/types/renderer/index.d.ts.map +1 -0
  40. package/dist/types/renderer/overlays.d.ts +166 -0
  41. package/dist/types/renderer/overlays.d.ts.map +1 -0
  42. package/dist/types/renderer/sanitize.d.ts +73 -0
  43. package/dist/types/renderer/sanitize.d.ts.map +1 -0
  44. package/dist/types/renderer/snapshot.d.ts +41 -0
  45. package/dist/types/renderer/snapshot.d.ts.map +1 -0
  46. package/dist/types/transport/websocket.d.ts +44 -0
  47. package/dist/types/transport/websocket.d.ts.map +1 -0
  48. package/docs/ARCHITECTURE.md +273 -0
  49. package/docs/DESIGN-HISTORY.md +120 -0
  50. package/docs/QUICKSTARTS.md +289 -0
  51. package/docs/RELEASE.md +60 -0
  52. package/docs/SECURITY.md +156 -0
  53. package/docs/paper/OUTLINE.md +100 -0
  54. package/examples/bookmarklet-demo/demo.css +102 -0
  55. package/examples/bookmarklet-demo/server.js +297 -0
  56. package/examples/bookmarklet-demo/source.html +52 -0
  57. package/examples/bookmarklet-demo/viewer.html +48 -0
  58. package/examples/extension-mv3/demo.css +102 -0
  59. package/examples/extension-mv3/server.js +350 -0
  60. package/examples/extension-mv3/source.html +48 -0
  61. package/examples/extension-mv3/viewer.html +48 -0
  62. package/examples/loopback-mirror.html +369 -0
  63. package/examples/loopback-transport.js +65 -0
  64. package/examples/playwright-demo/demo.css +462 -0
  65. package/examples/playwright-demo/fixture.html +56 -0
  66. package/examples/playwright-demo/fixture.js +57 -0
  67. package/examples/playwright-demo/server.js +517 -0
  68. package/examples/playwright-demo/viewer.html +112 -0
  69. package/examples/playwright-demo/viewer.js +414 -0
  70. package/examples/serve.js +97 -0
  71. package/examples/two-tab-demo/demo.css +266 -0
  72. package/examples/two-tab-demo/server.js +233 -0
  73. package/examples/two-tab-demo/source.html +70 -0
  74. package/examples/two-tab-demo/source.js +213 -0
  75. package/examples/two-tab-demo/viewer.html +72 -0
  76. package/examples/two-tab-demo/viewer.js +121 -0
  77. package/package.json +107 -0
  78. package/src/adapters/bookmarklet.js +98 -0
  79. package/src/adapters/browser-inject.js +17 -0
  80. package/src/adapters/extension.js +322 -0
  81. package/src/adapters/playwright-inject.js +4401 -0
  82. package/src/adapters/playwright.js +540 -0
  83. package/src/capture/README.md +302 -0
  84. package/src/capture/index.js +4361 -0
  85. package/src/index.js +5 -0
  86. package/src/protocol/constants.js +49 -0
  87. package/src/protocol/envelope.js +75 -0
  88. package/src/protocol/index.js +4 -0
  89. package/src/protocol/messages.js +268 -0
  90. package/src/protocol/remote-control.js +300 -0
  91. package/src/relay/README.md +22 -0
  92. package/src/relay/backends/ws.js +186 -0
  93. package/src/relay/index.js +3 -0
  94. package/src/relay/limits.js +105 -0
  95. package/src/relay/relay.js +397 -0
  96. package/src/renderer/README.md +443 -0
  97. package/src/renderer/diff.js +389 -0
  98. package/src/renderer/index.js +1401 -0
  99. package/src/renderer/overlays.js +528 -0
  100. package/src/renderer/sanitize.js +366 -0
  101. package/src/renderer/snapshot.js +202 -0
  102. package/src/transport/websocket.js +553 -0
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Escape a value for inclusion inside a double-quoted HTML attribute.
3
+ * Renamed port of escapePreviewAttribute (dashboard.js:2671-2677): null and
4
+ * undefined map to '', then &, ", <, > are escaped in that exact order
5
+ * (&-first so the other replacements are never themselves re-escaped).
6
+ * @param {*} value
7
+ * @returns {string}
8
+ */
9
+ export function escapeAttribute(value: any): string;
10
+ /**
11
+ * Build the attribute string for an html/body shell tag. Verbatim port of
12
+ * dashboard.js:2679-2694: names are lowercased and must match
13
+ * /^[a-z][a-z0-9_:.~-]*$/; 'style' and any on*-prefixed name are dropped
14
+ * (shell event-handler attributes never reach the mirror); null/undefined
15
+ * values are dropped; trimmed styleText is scrubbed and appended last as
16
+ * style="...". Values are escaped via escapeAttribute.
17
+ * @param {Object|null|undefined} attrs Captured shell attributes (name -> value)
18
+ * @param {string|null|undefined} styleText Shell computed style text
19
+ * @returns {string} ' name="value" ...' (leading-space-prefixed) or ''
20
+ */
21
+ export function buildShellAttributeString(attrs: any | null | undefined, styleText: string | null | undefined): string;
22
+ /**
23
+ * Build the full mirror srcdoc string for a snapshot payload. Assembly per
24
+ * dashboard.js:2785-2800 extended by 03-02, in order: doctype + html shell
25
+ * attrs (from payload.htmlAttrs/payload.htmlStyle) + head with the adopted
26
+ * CSP meta FIRST, charset meta, viewport meta
27
+ * width=(parseInt(payload.viewportWidth, 10) || 1920) -- numerically
28
+ * coerced, never raw (review WR-03), stylesheet links (each with
29
+ * ONLY double quotes escaped to &quot;), inline style tags CSS-scrubbed
30
+ * via scrubCssText, the exact parity reset-CSS style tag (02-UI-SPEC
31
+ * "Mirror page reset CSS") + body shell attrs
32
+ * (payload.bodyAttrs/payload.bodyStyle) + payload.html raw at the string
33
+ * layer (see the insertion-point inventory above) + closing tags.
34
+ * Pure transform: no DOM access anywhere.
35
+ * @param {SnapshotPayload} payload
36
+ * @returns {string}
37
+ */
38
+ export function buildSnapshotHtml(payload: SnapshotPayload): string;
39
+ export function buildFramePlaceholderHtml(frame: any): string;
40
+ export type SnapshotPayload = import("../protocol/messages.js").SnapshotPayload;
41
+ //# sourceMappingURL=snapshot.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"snapshot.d.ts","sourceRoot":"","sources":["../../../src/renderer/snapshot.js"],"names":[],"mappings":"AA+FA;;;;;;;GAOG;AACH,uCAHW,GAAC,GACC,MAAM,CAQlB;AAED;;;;;;;;;;GAUG;AACH,iDAJW,MAAO,IAAI,GAAC,SAAS,aACrB,MAAM,GAAC,IAAI,GAAC,SAAS,GACnB,MAAM,CAiBlB;AAED;;;;;;;;;;;;;;;GAeG;AACH,2CAHW,eAAe,GACb,MAAM,CA+BlB;AAED,8DAeC;8BAjKa,OAAO,yBAAyB,EAAE,eAAe"}
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Encode a full PhantomStream message for WebSocket transport.
3
+ *
4
+ * @param {Object} msg Full message object `{ type, payload, ts }`.
5
+ * @param {Object} [options]
6
+ * @returns {Promise<string>}
7
+ */
8
+ export function encodeWireMessage(msg: any, options?: any): Promise<string>;
9
+ /**
10
+ * Decode a WebSocket wire frame into a PhantomStream message object.
11
+ *
12
+ * @param {string|ArrayBuffer|ArrayBufferView|Blob} raw
13
+ * @param {Object} [options]
14
+ * @returns {Promise<{ok: true, msg: Object} | {ok: false, error: string}>}
15
+ */
16
+ export function decodeWireMessage(raw: string | ArrayBuffer | ArrayBufferView | Blob, options?: any): Promise<{
17
+ ok: true;
18
+ msg: any;
19
+ } | {
20
+ ok: false;
21
+ error: string;
22
+ }>;
23
+ /**
24
+ * Create a browser-compatible WebSocket transport for capture and viewer.
25
+ *
26
+ * @param {Object} options
27
+ * @returns {{
28
+ * send: (type: string, payload: Object) => void,
29
+ * flush: () => Promise<void>,
30
+ * onMessage: (handler: (type: string, payload: Object) => void) => (() => void),
31
+ * onStatus: (handler: (status: Object) => void) => (() => void),
32
+ * close: () => void,
33
+ * getHealth: () => Object
34
+ * }}
35
+ */
36
+ export function createWebSocketTransport(options: any): {
37
+ send: (type: string, payload: any) => void;
38
+ flush: () => Promise<void>;
39
+ onMessage: (handler: (type: string, payload: any) => void) => (() => void);
40
+ onStatus: (handler: (status: any) => void) => (() => void);
41
+ close: () => void;
42
+ getHealth: () => any;
43
+ };
44
+ //# sourceMappingURL=websocket.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../../../src/transport/websocket.js"],"names":[],"mappings":"AA8LA;;;;;;GAMG;AACH,4DAFa,OAAO,CAAC,MAAM,CAAC,CA4B3B;AAED;;;;;;GAMG;AACH,uCAJW,MAAM,GAAC,WAAW,GAAC,eAAe,GAAC,IAAI,kBAErC,OAAO,CAAC;IAAC,EAAE,EAAE,IAAI,CAAC;IAAC,GAAG,MAAQ;CAAC,GAAG;IAAC,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAC,CAAC,CAmDzE;AAgCD;;;;;;;;;;;;GAYG;AACH,wDATa;IACR,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,KAAQ,KAAK,IAAI,CAAC;IAC9C,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3B,SAAS,EAAE,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,KAAQ,KAAK,IAAI,KAAK,CAAC,MAAM,IAAI,CAAC,CAAC;IAC9E,QAAQ,EAAE,CAAC,OAAO,EAAE,CAAC,MAAM,KAAQ,KAAK,IAAI,KAAK,CAAC,MAAM,IAAI,CAAC,CAAC;IAC9D,KAAK,EAAE,MAAM,IAAI,CAAC;IAClB,SAAS,EAAE,SAAY,CAAA;CACxB,CAoOH"}
@@ -0,0 +1,273 @@
1
+ # PhantomStream Architecture
2
+
3
+ This document describes the system as it shipped inside FSB (milestone v0.9.9.1 "Phantom
4
+ Stream" plus the reliability hardening of phases 211 and 276). File references point at the
5
+ verbatim copies under `reference/`.
6
+
7
+ For runnable package setup paths, see [QUICKSTARTS.md](QUICKSTARTS.md).
8
+
9
+ ## 1. Overview
10
+
11
+ PhantomStream mirrors a live browser tab to a remote viewer by streaming the page as
12
+ **structured DOM data** rather than pixels:
13
+
14
+ 1. **Snapshot** — a one-time serialization of `document.body`, rebuilt by the
15
+ viewer into a sandboxed iframe. Default `styleMode: 'computed'` inlines
16
+ curated computed styles; opt-in `styleMode: 'cssom'` transports scoped
17
+ `styleSources[]` and `styleStrategy`. Standalone Phase 8 extends the
18
+ snapshot with `nodeIds`, `shadowRoots[]`, and `frames[]` sidecars for
19
+ scoped identity.
20
+ 2. **Diffs** — incremental MutationObserver batches (`add` / `rm` / `attr` / `text` ops)
21
+ addressed by stable node IDs, applied surgically to the mirror. Phase 8 also
22
+ streams `shadow-root` replacement ops and narrow `value` ops; Phase 9 adds
23
+ CSSOM `style-source` ops.
24
+ 3. **Side channels** — scroll position, automation overlays (action glow, progress), and
25
+ native dialog mirroring.
26
+ 4. **Reverse path** — remote control: clicks, typing, and scrolling performed on the mirror
27
+ are reverse-mapped and replayed in the real browser.
28
+
29
+ ```
30
+ page (content script) extension SW relay server viewer (dashboard)
31
+ dom-stream.js → background.js → ws-handler.js → dashboard.js
32
+ snapshot + rAF-batched LZ envelope, fan-out, decompress, iframe
33
+ diffs, scroll, overlay, session stamps, 1 MiB/msg cap srcdoc render, nid-
34
+ dialogs, watchdog #1 watchdog #2 addressed diff apply
35
+ ```
36
+
37
+ ## 2. Capture (`reference/extension/dom-stream.js`)
38
+
39
+ ### 2.1 Node identity
40
+
41
+ The original FSB reference design stamped every serialized element with
42
+ `data-fsb-nid`, a monotonically increasing string ID, on **both** the live DOM
43
+ and the serialized clone (`assignNodeId`). That attribute was the original
44
+ addressing keystone: every diff op, overlay rect, and remote-control action
45
+ addressed nodes by nid, and nodes added after the snapshot got nids in
46
+ `processAddedNode`.
47
+
48
+ The standalone framework design after Phase 7 keeps the same opaque nid wire
49
+ contract but removes live-page identity mutation. Capture owns identity in an
50
+ internal `WeakMap<Element, string>` plus reverse lookup, emits `nodeIds`
51
+ sidecars on snapshots and add ops, and exposes `getNodeId(element)` for trusted
52
+ host code. The renderer rebuilds a private `Map<nid, Node>` from `nodeIds`
53
+ after sanitization, so page-owned `data-fsb-nid` attributes remain ordinary
54
+ page data rather than PhantomStream identity.
55
+
56
+ ### 2.2 Full snapshot (`serializeDOM`)
57
+
58
+ - Clones `document.body`, then walks original and clone **in parallel** with two
59
+ TreeWalkers so live state can be read while the copy is transformed.
60
+ - Strips `<script>`/`<noscript>` and the host's own overlay elements.
61
+ - Absolutifies URL attributes (`src`, `href`, `action`, `poster`, `data`, `srcset`,
62
+ SVG `xlink:href`) against `document.baseURI`.
63
+ - Converts `<canvas>` to a data-URL `<img>` (tainted canvases degrade gracefully).
64
+ - In the FSB reference, iframes stayed live with absolutified `src` and
65
+ `pointer-events:none`. In the standalone Phase 8 framework, same-origin
66
+ iframes serialize as scoped `frames[]` sidecars keyed by `frameNid`, while
67
+ cross-origin iframe content remains a content-free placeholder.
68
+ - Open shadow roots serialize as `shadowRoots[]` sidecars keyed by `hostNid`.
69
+ Shadow slots remain slots; slotted light-DOM children are not duplicated.
70
+ - Captures **curated computed styles**: ~85 visual-fidelity CSS properties
71
+ (`CURATED_PROPS`) inlined as a `style` attribute, with common default values elided
72
+ (`STYLE_DEFAULTS`). Iterating all 300+ computed properties made a YouTube serialize take
73
+ ~45 s; the curated list restored interactivity.
74
+ - Captures `<html>`/`<body>` attributes and a smaller shell style set (`SHELL_PROPS`) so
75
+ the viewer can reproduce page-level background/typography.
76
+ - Collects stylesheet URLs (`<link rel=stylesheet>`) and inline `<style>` text (< 500 KB
77
+ each) from `<head>` for the viewer to re-link. In opt-in CSSOM mode this expands
78
+ to scoped `styleSources[]` for document, open shadow root, and same-origin frame
79
+ stylesheets instead of generated computed inline declarations.
80
+
81
+ ### 2.3 Snapshot size budget
82
+
83
+ The relay enforces a hard 1 MiB per-message cap. Snapshots truncate to 80% of that
84
+ (`RELAY_PER_MESSAGE_LIMIT_BYTES * 0.8`) in two passes:
85
+
86
+ 1. Drop complete subtrees whose live `getBoundingClientRect().top` exceeds 3× the viewport
87
+ height. Crucially, all rect reads happen in **one TreeWalker pre-pass over the live DOM
88
+ into a Map before any clone mutation** — collapsing N forced layout flushes into 1.
89
+ 2. If still over budget, drop remaining annotated subtrees last-to-first until under cap.
90
+
91
+ Only whole subtrees are removed, never a mid-element cut; `truncated` and
92
+ `missingDescendants` counts ship with the snapshot.
93
+
94
+ ### 2.4 Incremental diffs
95
+
96
+ A `MutationObserver` on `document.body` (childList + attributes + characterData, subtree)
97
+ accumulates records; flushes are batched on `requestAnimationFrame` so diff delivery is
98
+ matched to the page's paint cadence. `processMutationBatch` converts records to wire ops:
99
+
100
+ | op | payload | meaning |
101
+ |----|---------|---------|
102
+ | `add` | `parentNid`, `html`, `beforeNid` | insert serialized subtree |
103
+ | `rm` | `nid` | remove subtree |
104
+ | `attr` | `nid`, `attr`, `val` | attribute change (URLs re-absolutified) |
105
+ | `text` | `nid`, `text` | character data change (addressed via parent nid) |
106
+ | `shadow-root` | `hostNid`, `html`, `nodeIds` | replace a mirrored open shadow root after sanitization |
107
+ | `value` | `nid`, `value` / `checked` / `selectedValues` | apply property-only form value drift |
108
+ | `style-source` | `action`, `sourceId`, `scope`, `source` | upsert, replace, or remove a scoped CSSOM source |
109
+
110
+ Mutations on untracked nodes (no nid) and on the host's own overlay are skipped.
111
+ Open shadow roots and same-origin frame documents are observed explicitly, so
112
+ their mutations do not depend on `document.body` observer reachability.
113
+ Newly added subtrees carry curated computed styles in add-op HTML, collected in
114
+ a read pass before detached clone mutation.
115
+
116
+ ### 2.5 CSSOM style mode
117
+
118
+ Phase 9 adds `styleMode: 'computed' | 'cssom'`. The default remains computed
119
+ style inlining for backward-compatible visual fidelity. CSSOM mode serializes
120
+ document, open-shadow-root, and same-origin-frame stylesheets as sanitized
121
+ `styleSources[]` entries with `styleStrategy` diagnostics. `sourceId` and
122
+ `scope` make stylesheet sources addressable without CSS selectors.
123
+
124
+ Fallbacks are explicit: `cssRules-blocked`, `href-relinked`, `adapter-fetch`,
125
+ or `computed-fallback`. `fetchStylesheet({ href, scope, ownerKind })` is an
126
+ optional host hook; PhantomStream does not perform hidden network fetches.
127
+ Live stylesheet edits stream as `DIFF_OP.STYLE_SOURCE` with
128
+ `action: 'upsert' | 'replace' | 'remove'`. CSSOM hook failures report
129
+ `cssom-hook-unavailable` and fall back to a fresh snapshot; unreconciled style
130
+ owners use `cssom-style-source-stale`, and renderer misses surface as
131
+ `stale-style-scope`.
132
+
133
+ ### 2.6 Subtree recovery
134
+
135
+ Standalone Phase 8 makes truncation interactive instead of purely passive.
136
+ Dropped snapshot roots are replaced by `data-phantomstream-truncated="true"`
137
+ markers whose nids stay in `nodeIds`. The viewer or host can request a single
138
+ nid with `CONTROL.SUBTREE_REQUEST`; capture answers with
139
+ `STREAM.SUBTREE_RESPONSE` carrying either content-free miss status or an `ok`
140
+ payload that reuses add-op serialization: sanitized HTML, masking, URL
141
+ absolutification, curated styles, `nodeIds`, `shadowRoots[]`, and `frames[]`.
142
+ Requests are session/snapshot checked and are bounded by renderer-side latches.
143
+
144
+ ### 2.7 Watchdog #1 (content script)
145
+
146
+ A 5 s self-watchdog (a `setTimeout` chain, not `setInterval`, so cadence resets on every
147
+ drain) force-flushes a stuck mutation queue and increments `staleFlushCount`, which rides
148
+ the next flush envelope so the host can observe rescue frequency.
149
+
150
+ ### 2.8 Side channels
151
+
152
+ - **Scroll** — passive listener, throttled to 1 event / 200 ms.
153
+ - **Overlay** — broadcasts the automation action-glow rect and progress card state,
154
+ throttled to 1 / 500 ms, forced on snapshot/resume.
155
+ - **Dialogs** — a page-level injected script monkey-patches `window.alert` / `confirm` /
156
+ `prompt` to dispatch `CustomEvent`s before/after the native call; the content script
157
+ relays open/closed states so the viewer can show styled dialog cards.
158
+
159
+ ### 2.9 Lifecycle & readiness
160
+
161
+ Control messages: `domStreamStart` (fresh session + snapshot + observers),
162
+ `domStreamStop`, `domStreamPause` (observers off, session retained),
163
+ `domStreamResume` (observers re-armed, same session/snapshot, no snapshot),
164
+ `pingDomStream` (synchronous readiness probe).
165
+
166
+ Auto-start chain: module load → `domStreamReady` ping → host issues stream start. If the
167
+ viewer's start request arrives before the module loads (slow pages), the host parks it in
168
+ `_pendingStreamStart` and re-arms on the ready ping (`reference/extension/ws-client.js`).
169
+
170
+ ## 3. Transport
171
+
172
+ ### 3.1 Session identity
173
+
174
+ `beginStreamSession()` mints `streamSessionId` (`stream_<ts36>_<rand>`) and a `snapshotId`
175
+ per session; **every** message type carries both. The viewer tracks the active identity,
176
+ rejects stale messages, and detects stream replacement (new session/snapshot/tab) to reset
177
+ overlays and scroll state. This is what makes late diffs from a previous page harmless.
178
+
179
+ ### 3.2 Compression envelope
180
+
181
+ Payloads ≥ threshold travel as a self-identifying envelope `{_lz: true, d: <base64>}`
182
+ (LZ-string), with plain JSON fallback for small payloads and backward compatibility —
183
+ 90%+ reduction on 100 KB+ snapshots. Decompression failure is recorded as a transport
184
+ error, never a crash.
185
+
186
+ ### 3.3 Relay (`reference/server/ws-handler.js`)
187
+
188
+ A thin WebSocket fan-out between extension and dashboard clients. Enforces the per-message
189
+ size cap (the capture-side truncation budget is derived from it) and classifies oversized
190
+ messages by envelope type for diagnostics.
191
+
192
+ ### 3.4 Watchdog #2 (service worker)
193
+
194
+ A `chrome.alarms` 1-minute alarm (`fsb-domstream-watchdog`) — armed idempotently on every
195
+ mutation dispatch — survives MV3 service-worker eviction. On fire, if streaming should be
196
+ active, it sends `ext:request-snapshot` so the viewer re-issues a stream start. The
197
+ content-script watchdog is the trip wire; this is the safety net for a wedged content
198
+ script.
199
+
200
+ ## 4. Renderer (`reference/dashboard/dashboard.js`)
201
+
202
+ - **Snapshot** (`handleDOMSnapshot`): rebuilds a full HTML document — stylesheet links,
203
+ inline styles, captured shell attributes — and writes it to a preview iframe via
204
+ `srcdoc`. On load, scales the page to the stage and applies the captured scroll offset.
205
+ - **Diff apply**: the FSB reference resolved each op with
206
+ `doc.querySelector('[data-fsb-nid="…"]')`. In the standalone framework after
207
+ Phase 7, snapshots/add ops carry `nodeIds` sidecars and the viewer resolves
208
+ nids through an internal `Map<nid, Node>` index. Misses are still recorded
209
+ (a consequence of truncation or lost messages) and degrade to awaiting the
210
+ next snapshot.
211
+ - **Shadow/frame reconstruction**: Phase 8 installs real open mirror shadow
212
+ roots from sanitized sidecars and reconstructs same-origin frame payloads as
213
+ inert nested `srcdoc` documents. Cross-origin iframe content is rendered only
214
+ as a safe placeholder label; no origin bypass is attempted.
215
+ - **Value/subtree handling**: `DIFF_OP.VALUE` updates form-control properties
216
+ through the identity index. `requestSubtree()` sends bounded
217
+ `CONTROL.SUBTREE_REQUEST` frames and applies current `STREAM.SUBTREE_RESPONSE`
218
+ payloads only after render-side sanitization.
219
+ - **Layout modes**: inline, maximized, picture-in-picture (drag-to-reposition), fullscreen
220
+ (mouse-tracked exit overlay), with viewport-adaptive scale math per mode.
221
+ - **Overlays**: action glow rect, progress card, and dialog cards positioned in mirror
222
+ coordinates.
223
+ - **Remote control**: pointer/keyboard/scroll events on the mirror are reverse-scaled from
224
+ stage coordinates to page coordinates and replayed in the real tab; an active-control
225
+ state is signaled with a visible border.
226
+
227
+ ## 5. Reliability inventory
228
+
229
+ | Failure mode | Defense |
230
+ |---|---|
231
+ | Mutation queue stalls (rAF starvation, tab throttling) | content-script watchdog force-flush + `staleFlushCount` telemetry |
232
+ | Content script wedged entirely | SW alarm watchdog → `ext:request-snapshot` |
233
+ | MV3 service-worker eviction | watchdog lives in `chrome.alarms`; re-armed on every dispatch |
234
+ | Snapshot exceeds relay cap | 2-pass whole-subtree truncation at 80% of cap |
235
+ | Snapshot/diff payload too big even compressed | relay-side cap + diagnostics classification |
236
+ | Late diffs from a previous page | session/snapshot identity stamped on every message, viewer-side rejection |
237
+ | Start requested before capture module loads | readiness probe + parked pending-intent re-arm |
238
+ | Forced layout thrash during truncation | single read-pass into a Map before any write |
239
+ | Heavy pages (300+ computed props/element) | curated 85-property style list + default elision |
240
+
241
+ ## 6. Resolved limitations and residual boundaries
242
+
243
+ These were weaknesses of the shipped/reference design. The standalone package
244
+ has resolved the high-value framework gaps; the remaining items below are
245
+ explicit browser/security boundaries or intentional default-mode tradeoffs:
246
+
247
+ 1. **Computed mode still freezes styles by design.** In default computed mode,
248
+ inlined styles are snapshot-time state. Class-flip diffs (`attr` ops) can
249
+ still drift until the next full snapshot. Opt-in CSSOM mode addresses
250
+ stylesheet-driven drift for readable, safely re-linkable, or host-fetched
251
+ sources, with explicit fallback reasons when a source cannot be represented.
252
+ 2. **Added-node computed styles resolved in standalone Phase 8.** Add ops now
253
+ carry curated computed styles using the same default-elision discipline as
254
+ snapshots. CSSOM mode remains opt-in rather than replacing the default.
255
+ 3. **Former nid stamping limitation resolved in standalone Phase 7.** The
256
+ reference `data-fsb-nid` live-page mutation is now replaced by WeakMap
257
+ capture identity and `nodeIds` sidecars in the standalone framework. This
258
+ entry remains here as design history for the FSB reference behavior, not as
259
+ a current framework limitation.
260
+ 4. **Truncation recovery resolved in standalone Phase 8 for explicit requests.**
261
+ Diff targets inside dropped subtrees no longer have to wait for the next full
262
+ snapshot when the host/viewer calls `requestSubtree`. Recovery is still
263
+ bounded and explicit; PhantomStream does not automatically crawl every miss.
264
+ 5. **Blocklist sanitizer coverage is intentionally conservative.** Capture and renderer
265
+ chokepoints now strip event handlers, dangerous URL schemes, `srcdoc`,
266
+ object/embed/script-like subtrees, and hostile CSS before mirrored content is
267
+ transported or inserted. This is still a framework-maintained blocklist, so the
268
+ viewer iframe remains sandboxed without `allow-scripts` as defense in depth.
269
+ 6. **Open shadow DOM and same-origin iframes resolved in standalone Phase 8.**
270
+ Remaining limits are closed shadow roots, cross-origin iframe content,
271
+ and `<video>`/`<audio>` media pixels/streams. Closed shadow roots and
272
+ cross-origin iframe content are browser security boundaries; the framework
273
+ documents them as non-captured content rather than faking or bypassing them.
@@ -0,0 +1,120 @@
1
+ # Design History
2
+
3
+ PhantomStream was built inside [FSB](https://github.com/fullselfbrowsing/FSB) as milestone
4
+ **v0.9.9.1 "Phantom Stream"** (shipped 2026-03-31), then hardened by two later phases. This
5
+ repository was extracted from FSB at commit `867d6f0c` (2026-06-09). The original planning
6
+ artifacts — plans, summaries, UAT scripts, verification reports — are preserved verbatim
7
+ under `reference/planning/`.
8
+
9
+ ## Milestone v0.9.9.1 — Phantom Stream (Mar 2026)
10
+
11
+ **Goal:** make the FSB dashboard's DOM stream fully functional — auto-connect on WebSocket,
12
+ full-fidelity live preview, display-matched frame rate, remote browser control.
13
+
14
+ 9 phases (5 planned + 4 inserted fixes), 16 plans:
15
+
16
+ | Phase | What it delivered |
17
+ |---|---|
18
+ | 122 Connection & Auto-Start | Stream starts on WS handshake, active-tab tracking, disconnect recovery, 4-state health badge |
19
+ | 122.1 Stream Overlay Fix *(inserted)* | Action glow rect mirrored into the preview during automation |
20
+ | 122.2 Stop Signal & Final Outcome *(inserted)* | Idempotent stop signals, promise resolution on stop, single task-complete delivery |
21
+ | 122.3 WS Payload Compression *(inserted)* | LZ-string envelope (`{_lz, d}`), 90%+ reduction on 100 KB+ snapshots, backward-compatible |
22
+ | 122.4 Dashboard Relay Fix *(inserted)* | End-to-end relay delivery investigation and fix |
23
+ | 123 Layout Modes | Inline / maximized / PiP (drag) / fullscreen (mouse-tracked exit), viewport-adaptive scaling |
24
+ | 123.1 Stream Fidelity Fix *(inserted)* | Broken layouts on complex sites — computed style capture overhaul |
25
+ | 124 Visual Fidelity | Dialog mirroring, rAF-synced mutation batching, curated computed-style capture |
26
+ | 125 Remote Control | Click/type/scroll through the preview with coordinate reverse-scaling |
27
+
28
+ The inserted phases are the interesting part of the history: each one is a real-world
29
+ failure mode discovered in use (payloads silently dropped by the relay, styles too heavy
30
+ for complex sites, overlays invisible in the mirror) and its root-cause fix.
31
+
32
+ ## Phase 211 — Stream Reliability & Diagnostic Logging
33
+
34
+ Added the dual-watchdog design:
35
+
36
+ - **STREAM-01:** 5 s content-script self-watchdog (setTimeout chain) + SW-side
37
+ `chrome.alarms` safety net surviving MV3 eviction.
38
+ - **STREAM-02:** `staleFlushCount` telemetry riding the mutation envelope.
39
+ - **STREAM-03/04:** snapshot truncation under the relay's 1 MiB cap with single-pass
40
+ batched layout reads (read-then-write discipline).
41
+
42
+ ## Phase 276 — Streaming Diagnostic Minimum Patch
43
+
44
+ Defensive hardening of the start-up handshake:
45
+
46
+ - **STREAM-DEFENSIVE-02:** `pingDomStream` synchronous readiness probe (200 ms polls, 5 s
47
+ budget).
48
+ - **STREAM-DEFENSIVE-04:** pending-intent parking — a stream-start arriving before the
49
+ capture module loads is parked and re-armed on the module's ready ping.
50
+ - **STREAM-DEFENSIVE-05:** watchdog auto-resnapshot via `ext:request-snapshot`.
51
+
52
+ ## Performance lessons (encoded in the code)
53
+
54
+ 1. **Curate, don't enumerate.** Iterating all 300+ computed CSS properties per element made
55
+ a YouTube DOM serialize take ~45 s. The curated ~85-property list with default-value
56
+ elision restored interactivity. (`CURATED_PROPS`, D-04/D-07/D-08)
57
+ 2. **Batch your layout reads.** Reading `getBoundingClientRect()` interleaved with clone
58
+ mutation forced N layout flushes; a single TreeWalker pre-pass into a Map collapsed them
59
+ to 1. (Phase 211-02)
60
+ 3. **Match the display, not a timer.** rAF-batched mutation flushes deliver diffs at paint
61
+ cadence — no faster than useful, no slower than visible. (FIDELITY-03)
62
+ 4. **Whole subtrees only.** Truncation never cuts mid-element, so the mirror is always a
63
+ valid document — just a shorter one.
64
+ 5. **Identity beats ordering.** Session/snapshot IDs on every message turned a class of
65
+ ghost-mutation corruption bugs into silent, correct rejections.
66
+ 6. **Late-added styles follow the curated path.** Phase 8 fixed post-snapshot
67
+ added-node style drift by reusing the curated computed property list and
68
+ batching reads before clone mutation. It deliberately did not enumerate all
69
+ computed properties; Phase 9 adds stylesheet-centric CSSOM mode as an
70
+ opt-in path rather than replacing the computed-style default.
71
+
72
+ ## Standalone Phase 8 — Fidelity Completion (Jun 2026)
73
+
74
+ Phase 8 closed the remaining high-value DOM fidelity gaps without changing the
75
+ core architecture:
76
+
77
+ - Open shadow roots are transported as `shadowRoots[]` sidecars tied to host
78
+ nids, then reconstructed as real mirror shadow roots. Slots stay slots; light
79
+ children are not duplicated.
80
+ - Same-origin iframes are transported as scoped `frames[]` sidecars and rendered
81
+ as inert nested srcdoc mirrors. Cross-origin iframe content remains a
82
+ content-free placeholder.
83
+ - Input/change events emit narrow, masked `DIFF_OP.VALUE` updates for form
84
+ property drift instead of replacing nodes.
85
+ - Add ops use curated computed styles collected in batched reads. This preserves
86
+ the original "curate, don't enumerate" lesson while fixing late-added visual
87
+ drift.
88
+ - Truncated snapshot regions now keep requestable placeholder nids and can be
89
+ recovered by bounded `requestSubtree` / `STREAM.SUBTREE_RESPONSE` flows.
90
+
91
+ ## Standalone Phase 9 — CSSOM Capture Mode (Jun 2026)
92
+
93
+ Phase 9 added optional stylesheet-centric capture:
94
+
95
+ - `styleMode: 'computed' | 'cssom'` keeps the historical computed path as the
96
+ default and makes CSSOM capture an explicit opt-in.
97
+ - CSSOM snapshots carry scoped `styleSources[]` and `styleStrategy` metadata
98
+ for document, open-shadow-root, and same-origin-frame stylesheets.
99
+ - `fetchStylesheet({ href, scope, ownerKind })` is a host-owned hook for
100
+ explicit stylesheet text supply; PhantomStream does not perform hidden
101
+ network fetches.
102
+ - Live stylesheet edits stream as `DIFF_OP.STYLE_SOURCE` with
103
+ `action: 'upsert' | 'replace' | 'remove'`.
104
+ - Fallback reasons (`cssRules-blocked`, `href-relinked`, `adapter-fetch`,
105
+ `computed-fallback`) and recovery diagnostics (`cssom-hook-unavailable`,
106
+ `cssom-style-source-stale`, `stale-style-scope`) keep CSSOM failures
107
+ visible instead of silently drifting.
108
+
109
+ ## Where the standalone framework goes from here
110
+
111
+ The standalone framework now has package quickstarts in
112
+ `docs/QUICKSTARTS.md`. The remaining roadmap is publication and research
113
+ work, not another capture fidelity pass:
114
+
115
+ 1. **0.x package release** — validated npm package, trusted publishing setup,
116
+ and quickstarts.
117
+ 2. **FSB swap-in** — consume the published package in the original downstream
118
+ app before freezing 1.0.
119
+ 3. **Evaluation harness** — bandwidth/latency/fidelity benchmarks vs. video
120
+ streaming and rrweb-style record/replay, for the paper.