Skip to content

The agent that grows with you

fix(webapp): preserve SandboxedFrame guest parity

dokterdokbd78ca4afaab
diff --git a/apps/desktop/src/components/ui/guest-shell.test.ts b/apps/desktop/src/components/ui/guest-shell.test.ts
new file mode 100644
index 00000000000..3d15f9e9fa1
--- /dev/null
+++ b/apps/desktop/src/components/ui/guest-shell.test.ts
@@ -0,0 +1,222 @@
+// @vitest-environment jsdom
+import { once } from 'node:events'
+import { readFileSync } from 'node:fs'
+import { ReadableStream, TransformStream, WritableStream } from 'node:stream/web'
+import { runInNewContext } from 'node:vm'
+import { MessageChannel, MessagePort } from 'node:worker_threads'
+
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+const source = readFileSync('../../hermes_cli/webapp_previews.py', 'utf8')
+const html = source.match(/PREVIEW_HTML = """([\s\S]*?)"""/)![1]
+const scripts = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)]
+
+expect(scripts).toHaveLength(1)
+
+interface RelayEvent {
+ data: unknown
+ origin: string
+ ports: MessagePort[]
+ source: unknown
+}
+
+const ports: MessagePort[] = []
+
+afterEach(() => {
+ ports.splice(0).forEach(port => port.close())
+})
+
+function channel() {
+ const result = new MessageChannel()
+
+ ports.push(result.port1, result.port2)
+
+ return result
+}
+
+function shell(direction: 'down' | 'up') {
+ const parent = { postMessage: vi.fn<(data: unknown, origin: string, transfers?: object[]) => void>() }
+ const guest = { postMessage: vi.fn<(data: unknown, origin: string, transfers?: object[]) => void>() }
+ const frame: { contentWindow: typeof guest | null } = { contentWindow: guest }
+ let receive!: (event: RelayEvent) => void
+
+ runInNewContext(scripts[0][1], {
+ document: { createElement: () => frame },
+ parent,
+ window: {},
+ location: { href: 'https://hermes.test/assets/webapp-guest.html' },
+ addEventListener: (_type: string, listener: typeof receive) => {
+ receive = listener
+ },
+ URL,
+ Object,
+ Array,
+ Map,
+ Set,
+ Error,
+ ArrayBuffer,
+ SharedArrayBuffer,
+ MessagePort,
+ ReadableStream,
+ WritableStream,
+ TransformStream
+ })
+
+ return {
+ frame,
+ post: direction === 'down' ? guest.postMessage : parent.postMessage,
+ send: (data: unknown, transferredPorts: MessagePort[] = []) =>
+ receive({
+ data,
+ origin: direction === 'down' ? 'https://hermes.test' : 'null',
+ ports: transferredPorts,
+ source: direction === 'down' ? parent : guest
+ })
+ }
+}
+
+function clone<T>(data: T, transfers: object[]) {
+ return structuredClone(data, { transfer: transfers as Transferable[] })
+}
+
+function expectTransfer(post: ReturnType<typeof shell>['post'], data: unknown, expected: object[]) {
+ expect(post).toHaveBeenCalledTimes(1)
+ expect(post.mock.calls[0][0]).toBe(data)
+ expect(post.mock.calls[0][1]).toBe('*')
+ const actual = post.mock.calls[0][2]!
+
+ expect(actual).toHaveLength(expected.length)
+ expected.forEach((value, index) => expect(actual[index]).toBe(value))
+}
+
+function stream() {
+ return new ReadableStream<string>({
+ start(controller) {
+ controller.enqueue('delivered')
+ controller.close()
+ }
+ })
+}
+
+describe.each(['down', 'up'] as const)('guest shell relay %s', direction => {
+ it('delivers ports and streams across both structured-clone hops', async () => {
+ const { send, post } = shell(direction)
+ const { port1, port2 } = channel()
+ const original = { port: port1, stream: stream() }
+ const incoming = clone(original, [port1, original.stream])
+ let delivered!: typeof incoming
+
+ ports.push(incoming.port)
+ post.mockImplementation((data, _origin, transfers) => {
+ delivered = clone(data as typeof incoming, transfers!)
+ ports.push(delivered.port)
+ })
+ send(incoming, [incoming.port])
+ expectTransfer(post, incoming, [incoming.port, incoming.stream])
+ expect(await delivered.stream.getReader().read()).toEqual({ done: false, value: 'delivered' })
+ const message = once(delivered.port, 'message')
+
+ port2.postMessage('connected')
+ expect(await message).toEqual(['connected'])
+ })
+
+ it('walks cloneable containers with cycles and duplicates, but never inside transferables or shared buffers', () => {
+ const { send, post } = shell(direction)
+ const { port1, port2 } = channel()
+ const named = stream()
+ const cause = stream()
+ const errors = stream()
+ const key = new ArrayBuffer(8)
+ const value = new WritableStream()
+ const member = new TransformStream()
+ const array = Object.assign([port1], { named })
+
+ const data = {
+ array,
+ error: new Error('cause', { cause }),
+ aggregate: new AggregateError([errors]),
+ map: new Map([[key, value]]),
+ set: new Set([member]),
+ plain: Object.assign(Object.create(null), { port1 }),
+ shared: new SharedArrayBuffer(8)
+ }
+
+ Object.assign(array, { cycle: data })
+ Object.assign(port1, { ignored: stream() })
+ send(data, [port1, port2, port1])
+ expectTransfer(post, data, [port1, port2, named, cause, errors, key, value, member])
+ })
+
+ it.each(['array property', 'Error.cause'] as const)(
+ 'delivers a stream under %s across two real clone hops',
+ async shape => {
+ const { send, post } = shell(direction)
+ const readable = stream()
+
+ const original =
+ shape === 'array property' ? Object.assign([], { stream: readable }) : new Error('wrapped', { cause: readable })
+
+ const incoming = clone(original, [readable])
+ let delivered!: typeof incoming
+
+ post.mockImplementation((data, _origin, transfers) => {
+ delivered = clone(data as typeof incoming, transfers!)
+ })
+ send(incoming)
+ expect(post).toHaveBeenCalledTimes(1)
+ const received = delivered instanceof Error ? (delivered.cause as ReadableStream) : delivered.stream
+
+ expect(await received.getReader().read()).toEqual({ done: false, value: 'delivered' })
+ }
+ )
+
+ it('walks a payload nested deeper than the call stack', () => {
+ const { send, post } = shell(direction)
+ const { port1 } = channel()
+ let data: unknown = { port1 }
+
+ for (let depth = 0; depth < 20000; depth += 1) {
+ data = new Map([['next', data]])
+ }
+
+ send(data)
+ expectTransfer(post, data, [port1])
+ })
+
+ it.each([false, true])('retries without transfers and closes ports only if both posts fail (both=%s)', both => {
+ const { send, post } = shell(direction)
+ const { port1, port2 } = channel()
+ const close1 = vi.spyOn(port1, 'close')
+ const close2 = vi.spyOn(port2, 'close')
+ const data = { port: port2, buffer: new ArrayBuffer(8) }
+
+ const fail = () => {
+ throw new DOMException('cannot transfer', 'DataCloneError')
+ }
+
+ post.mockImplementationOnce(fail)
+
+ if (both) {
+ post.mockImplementationOnce(fail)
+ }
+
+ expect(() => send(data, [port1])).not.toThrow()
+ expect(post.mock.calls).toEqual([
+ [data, '*', [port1, port2, data.buffer]],
+ [data, '*']
+ ])
+ expect(close1).toHaveBeenCalledTimes(both ? 1 : 0)
+ expect(close2).toHaveBeenCalledTimes(both ? 1 : 0)
+ })
+})
+
+it('closes the ports of a parent message that arrives before the guest frame exists', () => {
+ const { frame, send } = shell('down')
+ const { port1, port2 } = channel()
+ const close = vi.spyOn(port1, 'close')
+
+ frame.contentWindow = null
+ expect(() => send({ early: true }, [port1])).not.toThrow()
+ expect(close).toHaveBeenCalledOnce()
+ port2.close()
+})
diff --git a/apps/desktop/src/components/ui/sandboxed-frame.test.tsx b/apps/desktop/src/components/ui/sandboxed-frame.test.tsx
index 35febadaecd..1e4d8a295bc 100644
--- a/apps/desktop/src/components/ui/sandboxed-frame.test.tsx
+++ b/apps/desktop/src/components/ui/sandboxed-frame.test.tsx
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import { act, cleanup, fireEvent, render } from '@testing-library/react'
-import { createRef } from 'react'
+import { Activity, createRef, type SyntheticEvent } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { SANDBOXED_FRAME_DEFAULT_SANDBOX, SandboxedFrame, sanitizeFrameSandbox } from './sandboxed-frame'
@@ -112,6 +112,218 @@ describe('SandboxedFrame in the Webapp', () => {
vi.stubGlobal('__HERMES_UI_SURFACE__', 'webapp')
}
+ function guestLoaded(frame: HTMLIFrameElement) {
+ act(() => {
+ window.dispatchEvent(
+ new MessageEvent('message', { data: { type: 'hermes-guest-loaded' }, source: frame.contentWindow })
+ )
+ })
+ }
+
+ it.each([false, true])('dispatches fresh guest loads with normal propagation (stopPropagation=%s)', stop => {
+ browserHost()
+ const order: string[] = []
+ const events: SyntheticEvent<HTMLIFrameElement>[] = []
+ const targets: (EventTarget | null)[] = []
+
+ const onLoad = (event: SyntheticEvent<HTMLIFrameElement>) => {
+ order.push('sdk')
+ events.push(event)
+ targets.push(event.currentTarget, event.nativeEvent.target)
+ event.currentTarget.contentWindow!.postMessage('initialize', '*')
+
+ if (stop) {
+ event.stopPropagation()
+ }
+ }
+
+ const { container } = render(
+ <div onLoad={() => order.push('ancestor')}>
+ <SandboxedFrame onLoad={onLoad} src={guest} title="Widget" />
+ </div>
+ )
+
+ const frame = container.querySelector('iframe')!
+
+ frame.addEventListener('load', () => order.push('native'))
+ fireEvent.load(frame)
+ expect(order).toEqual([])
+
+ for (let count = 1; count <= 3; count += 1) {
+ guestLoaded(frame)
+ expect(order.splice(0)).toEqual(stop ? ['sdk', 'native'] : ['sdk', 'ancestor', 'native'])
+ expect(targets.splice(0)).toEqual([frame, frame])
+ expect(new Set(events).size).toBe(count)
+ expect(new Set(events.map(event => event.nativeEvent)).size).toBe(count)
+ }
+ })
+
+ it('remounts only when the sanitized sandbox changes', () => {
+ browserHost()
+ const { container, rerender } = render(<SandboxedFrame sandbox="allow-scripts" src={guest} title="Widget" />)
+ const initial = container.querySelector('iframe')!
+
+ rerender(<SandboxedFrame sandbox="ALLOW-SCRIPTS allow-same-origin" src={guest} title="Widget" />)
+ expect(container.querySelector('iframe')).toBe(initial)
+ rerender(<SandboxedFrame sandbox="allow-scripts allow-forms" src={guest} title="Widget" />)
+ const replacement = container.querySelector('iframe')!
+
+ expect(replacement).not.toBe(initial)
+ expect(replacement.getAttribute('sandbox')).toBe('allow-scripts allow-forms')
+ rerender(<SandboxedFrame sandbox="allow-scripts allow-forms" src={guest} title="Widget" />)
+ expect(container.querySelector('iframe')).toBe(replacement)
+ })
+
+ it('preserves an unchanged document across Activity reveals but sends changes and shell reloads', () => {
+ browserHost()
+
+ const view = (mode: 'hidden' | 'visible', src = guest) => (
+ <Activity mode={mode}>
+ <SandboxedFrame src={src} title="Widget" />
+ </Activity>
+ )
+
+ const { container, rerender } = render(view('visible'))
+ const frame = container.querySelector('iframe')!
+ const send = vi.spyOn(frame.contentWindow!, 'postMessage')
+
+ fireEvent.load(frame)
+ expect(send).toHaveBeenCalledTimes(1)
+ rerender(view('hidden'))
+ rerender(view('visible'))
+ expect(container.querySelector('iframe')).toBe(frame)
+ expect(send).toHaveBeenCalledTimes(1)
+
+ const changed = 'data:text/html,<p>changed</p>'
+
+ rerender(view('visible', changed))
+ expect(send).toHaveBeenCalledTimes(2)
+ expect(send).toHaveBeenLastCalledWith(
+ { type: 'hermes-preview-document', html: '<p>changed</p>', sandbox: 'allow-scripts' },
+ '*'
+ )
+ rerender(view('hidden', guest))
+ rerender(view('visible'))
+ expect(send).toHaveBeenCalledTimes(3)
+ fireEvent.load(frame)
+ expect(send).toHaveBeenCalledTimes(4)
+ })
+
+ it('sends the document for a shell that loads while hidden, and reports a guest that loads while hidden', () => {
+ browserHost()
+ const onLoad = vi.fn()
+
+ const view = (mode: 'hidden' | 'visible') => (
+ <Activity mode={mode}>
+ <SandboxedFrame onLoad={onLoad} src={guest} title="Widget" />
+ </Activity>
+ )
+
+ const { container, rerender } = render(view('visible'))
+ const frame = container.querySelector('iframe')!
+ const send = vi.spyOn(frame.contentWindow!, 'postMessage')
+
+ rerender(view('hidden'))
+ fireEvent.load(frame)
+ expect(send).toHaveBeenCalledExactlyOnceWith(
+ { type: 'hermes-preview-document', html: '<script>parent.postMessage("ready", "*")</script>', sandbox: 'allow-scripts' },
+ '*'
+ )
+ rerender(view('visible'))
+ rerender(view('hidden'))
+ guestLoaded(frame)
+ expect(onLoad).toHaveBeenCalledOnce()
+ rerender(view('visible'))
+ expect(send).toHaveBeenCalledOnce()
+ })
+
+ it('starts a frame inside a shadow root, where the shell load never reaches the document', () => {
+ browserHost()
+ const onLoad = vi.fn()
+ const shell = { postMessage: vi.fn() }
+ const host = window.document.createElement('div')
+ const mount = window.document.createElement('div')
+
+ window.document.body.append(host)
+ host.attachShadow({ mode: 'open' }).append(mount)
+ // jsdom gives an iframe inside a shadow root no window.
+ const windows = vi.spyOn(HTMLIFrameElement.prototype, 'contentWindow', 'get').mockReturnValue(shell as unknown as Window)
+
+ try {
+ const { unmount } = render(<SandboxedFrame onLoad={onLoad} src={guest} title="Widget" />, { container: mount })
+
+ fireEvent.load(mount.querySelector('iframe')!)
+ expect(shell.postMessage).toHaveBeenCalledOnce()
+ expect(onLoad).not.toHaveBeenCalled()
+ act(() => {
+ window.dispatchEvent(
+ new MessageEvent('message', { data: { type: 'hermes-guest-loaded' }, source: shell as unknown as Window })
+ )
+ })
+ expect(onLoad).toHaveBeenCalledOnce()
+ unmount()
+ } finally {
+ windows.mockRestore()
+ host.remove()
+ }
+ })
+
+ it.each([false, true])(
+ 'starts a frame mounted hidden on reveal, even under a cancelling ancestor capture (cancel=%s)',
+ cancel => {
+ browserHost()
+ const onLoad = vi.fn()
+ const capture = vi.fn((event: SyntheticEvent) => cancel && event.stopPropagation())
+
+ const view = (mode: 'hidden' | 'visible') => (
+ <div onLoadCapture={capture}>
+ <Activity mode={mode}>
+ <SandboxedFrame onLoad={onLoad} src={guest} title="Widget" />
+ </Activity>
+ </div>
+ )
+
+ const { container, rerender } = render(view('hidden'))
+ const frame = container.querySelector('iframe')!
+ const send = vi.spyOn(frame.contentWindow!, 'postMessage')
+
+ fireEvent.load(frame)
+ expect(capture).not.toHaveBeenCalled()
+ rerender(view('visible'))
+ expect(send).toHaveBeenCalledOnce()
+ rerender(view('visible'))
+ expect(send).toHaveBeenCalledOnce()
+ guestLoaded(frame)
+ expect(capture).toHaveBeenCalledOnce()
+ expect(onLoad).toHaveBeenCalledTimes(cancel ? 0 : 1)
+ }
+ )
+
+ it('keeps the shell load from ancestor capture handlers, which cannot stop the document', () => {
+ browserHost()
+ const order: string[] = []
+
+ const { container } = render(
+ <div
+ onLoadCapture={event => {
+ order.push('capture')
+ event.stopPropagation()
+ }}
+ >
+ <SandboxedFrame onLoad={() => order.push('sdk')} src={guest} title="Widget" />
+ </div>
+ )
+
+ const frame = container.querySelector('iframe')!
+ const send = vi.spyOn(frame.contentWindow!, 'postMessage')
+
+ fireEvent.load(frame)
+ expect(order).toEqual([])
+ expect(send).toHaveBeenCalledOnce()
+ guestLoaded(frame)
+ expect(order).toEqual(['capture'])
+ })
+
it('serves data: HTML through the guest shell with the caller tokens, and fires onLoad for the guest', () => {
browserHost()
const onLoad = vi.fn()
diff --git a/apps/desktop/src/components/ui/sandboxed-frame.tsx b/apps/desktop/src/components/ui/sandboxed-frame.tsx
index 15ae4676206..cf28a4f65a6 100644
--- a/apps/desktop/src/components/ui/sandboxed-frame.tsx
+++ b/apps/desktop/src/components/ui/sandboxed-frame.tsx
@@ -1,5 +1,5 @@
import type * as React from 'react'
-import { useCallback, useEffect, useRef } from 'react'
+import { useCallback, useEffect, useLayoutEffect, useRef } from 'react'
import { htmlFromDataUrl } from '@/lib/browser-guest-document'
import { browserBootstrap, endpointUrl } from '@/lib/browser-transport'
@@ -104,6 +104,7 @@ export function SandboxedFrame({ className, onError, onLoad, ref, sandbox, src,
<BrowserGuestFrame
className={className}
html={html}
+ key={sanitizeFrameSandbox(sandbox)}
onError={onError}
onLoad={onLoad}
ref={ref}
@@ -134,6 +135,50 @@ interface BrowserGuestFrameProps extends Omit<SandboxedFrameProps, 'src'> {
html: string
}
+// A shell's own load is taken at the document in the capture phase (load
+// events never reach the window), before React or a consumer's handler sees
+// it (inside a shadow root, the frame's own handler takes it instead); guest
+// loads are dispatched on the shell's frame as marked load events.
+// Both keep working while an <Activity> or Suspense boundary hides the frame
+// and detaches its ref and effects. A frame mounted hidden has no handler yet:
+// its shell load is only recorded, and the frame starts when first shown.
+const shellLoads = new WeakMap<HTMLIFrameElement, (frame: HTMLIFrameElement) => void>()
+const loadedShells = new WeakSet<HTMLIFrameElement>()
+const shellFrames = new WeakMap<object, HTMLIFrameElement>()
+const guestLoadEvents = new WeakSet<Event>()
+let listening = false
+
+function listenForGuestShells() {
+ if (listening) {
+ return
+ }
+
+ listening = true
+ document.addEventListener(
+ 'load',
+ event => {
+ const frame = event.target
+
+ if (frame instanceof HTMLIFrameElement && frame.hasAttribute('data-guest-shell') && !guestLoadEvents.has(event)) {
+ event.stopImmediatePropagation()
+ loadedShells.add(frame)
+ shellLoads.get(frame)?.(frame)
+ }
+ },
+ true
+ )
+ window.addEventListener('message', event => {
+ const frame = event.source && event.data?.type === 'hermes-guest-loaded' ? shellFrames.get(event.source) : undefined
+
+ if (frame?.isConnected && frame.contentWindow === event.source) {
+ const load = new Event('load')
+
+ guestLoadEvents.add(load)
+ frame.dispatchEvent(load)
+ }
+ })
+}
+
/** Webapp only: a `data:text/html` document would inherit the page CSP, which
* never runs guest inline scripts. The gateway's guest shell is served with
* its own policy and the SDK allowlist as its sandbox ceiling; this frame's
@@ -145,29 +190,57 @@ interface BrowserGuestFrameProps extends Omit<SandboxedFrameProps, 'src'> {
* document (not the shell) has loaded. */
function BrowserGuestFrame({ className, html, onError, onLoad, ref, sandbox, style, title }: BrowserGuestFrameProps) {
const frame = useRef<HTMLIFrameElement | null>(null)
- const shellLoad = useRef<React.SyntheticEvent<HTMLIFrameElement> | null>(null)
const guestSandbox = sanitizeFrameSandbox(sandbox)
+ // Before the first commit, so no shell can load unseen.
+ listenForGuestShells()
+ const lastDocument = useRef<{ html: string; sandbox: string } | null>(null)
const src = endpointUrl('/assets/webapp-guest.html', browserBootstrap()?.basePath || '').href
- const send = useCallback(() => {
- frame.current?.contentWindow?.postMessage({ type: 'hermes-preview-document', html, sandbox: guestSandbox }, '*')
- }, [html, guestSandbox])
+ const send = useCallback(
+ (node: HTMLIFrameElement) => {
+ const target = node.contentWindow
+
+ if (!target || (lastDocument.current?.html === html && lastDocument.current.sandbox === guestSandbox)) {
+ return
+ }
- useEffect(send, [send])
+ target.postMessage({ type: 'hermes-preview-document', html, sandbox: guestSandbox }, '*')
+ lastDocument.current = { html, sandbox: guestSandbox }
+ },
+ [html, guestSandbox]
+ )
- useEffect(() => {
- const guestLoaded = (event: MessageEvent) => {
- const loaded = shellLoad.current
+ const shellLoaded = useCallback(
+ (node: HTMLIFrameElement) => {
+ shellFrames.set(node.contentWindow!, node)
+ lastDocument.current = null
+ send(node)
+ },
+ [send]
+ )
+
+ // Registered again with each document, so a shell that loads while hidden
+ // still gets the latest one this frame showed; a shell that loaded before
+ // this frame was first shown is started now.
+ useLayoutEffect(() => {
+ const node = frame.current
- if (loaded && event.source === frame.current?.contentWindow && event.data?.type === 'hermes-guest-loaded') {
- onLoad?.(loaded)
+ if (node) {
+ shellLoads.set(node, shellLoaded)
+
+ if (loadedShells.has(node) && shellFrames.get(node.contentWindow!) !== node) {
+ shellLoaded(node)
}
}
+ }, [shellLoaded])
- window.addEventListener('message', guestLoaded)
+ useEffect(() => {
+ const node = frame.current
- return () => window.removeEventListener('message', guestLoaded)
- }, [onLoad])
+ if (node?.contentWindow && shellFrames.get(node.contentWindow) === node) {
+ send(node)
+ }
+ }, [send])
const attach = useCallback(
(node: HTMLIFrameElement | null) => {
@@ -196,11 +269,21 @@ function BrowserGuestFrame({ className, html, onError, onLoad, ref, sandbox, sty
return (
<iframe
className={cn('size-full border-0 bg-transparent', className)}
+ data-guest-shell=""
loading="lazy"
onError={onError}
onLoad={event => {
- shellLoad.current = event
- send()
+ if (guestLoadEvents.has(event.nativeEvent)) {
+ onLoad?.(event)
+
+ return
+ }
+
+ // Only a shell load the document never saw (a load is not composed, so
+ // inside a shadow root it stops there) reaches React.
+ event.stopPropagation()
+ loadedShells.add(event.currentTarget)
+ shellLoaded(event.currentTarget)
}}
ref={attach}
referrerPolicy="no-referrer"
diff --git a/hermes_cli/webapp_previews.py b/hermes_cli/webapp_previews.py
index ab8b6d218fc..16ae3a97a24 100644
--- a/hermes_cli/webapp_previews.py
+++ b/hermes_cli/webapp_previews.py
@@ -33,6 +33,53 @@ PREVIEW_HTML = """<!doctype html><html><head><meta charset="utf-8">
const frame = document.createElement('iframe');
frame.referrerPolicy = 'no-referrer';
frame.title = 'Preview content';
+const transferableTypes = [
+ 'MessagePort', 'ReadableStream', 'WritableStream', 'TransformStream', 'ImageBitmap',
+ 'OffscreenCanvas', 'VideoFrame', 'AudioData', 'ArrayBuffer', 'MediaStreamTrack', 'RTCDataChannel'
+].map(name => globalThis[name]).filter(type => typeof type === 'function');
+// An explicit stack: a deeply nested payload that cloning accepts must not
+// overflow the call stack. Children are pushed in reverse to keep their order.
+function transfersFor(event) {
+ const transfers = new Set(event.ports);
+ const seen = new Set();
+ const pending = [event.data];
+ while (pending.length) {
+ const value = pending.pop();
+ if (!value || typeof value !== 'object' || seen.has(value)) continue;
+ seen.add(value);
+ let children = [];
+ if (transferableTypes.some(type => value instanceof type)) {
+ transfers.add(value);
+ } else if (value instanceof Map) {
+ value.forEach((item, key) => children.push(key, item));
+ } else if (value instanceof Set) {
+ children = [...value];
+ } else if (value instanceof Error) {
+ children = [value.cause, value.errors];
+ } else if (Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype ||
+ Object.getPrototypeOf(value) === null) {
+ children = Object.values(value);
+ }
+ for (let index = children.length - 1; index >= 0; index--) pending.push(children[index]);
+ }
+ return [...transfers];
+}
+// A missing target (no guest frame yet) fails both posts, so its ports are closed.
+function relay(target, event) {
+ let transfers = [...event.ports];
+ try {
+ transfers = transfersFor(event);
+ target.postMessage(event.data, '*', transfers);
+ } catch {
+ try {
+ target.postMessage(event.data, '*');
+ } catch {
+ for (const value of transfers) {
+ if (typeof globalThis.MessagePort === 'function' && value instanceof MessagePort) value.close();
+ }
+ }
+ }
+}
addEventListener('message', event => {
if (event.source === parent && parent !== window &&
event.origin === new URL(location.href).origin &&
@@ -44,9 +91,9 @@ addEventListener('message', event => {
frame.srcdoc = event.data.html;
document.body.append(frame);
} else if (event.source === parent && event.origin === new URL(location.href).origin) {
- frame.contentWindow?.postMessage(event.data, '*');
+ relay(frame.contentWindow, event);
} else if (event.source === frame.contentWindow) {
- parent.postMessage(event.data, '*');
+ relay(parent, event);
}
});
</script></body></html>"""
diff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.md
index 701ca99b1dc..dc10a7a250b 100644
--- a/website/docs/developer-guide/desktop-plugin-sdk.md
+++ b/website/docs/developer-guide/desktop-plugin-sdk.md
@@ -1084,7 +1084,8 @@ same window, so filter guest messages by type). Post
to `parent`, not `top`: the shell sits between them.
*Teardown:* it is a plain React element — unmounting your pane/page removes the
-frame and its realm; nothing is registered app-side.
+frame and its realm; nothing is registered app-side for it (the Webapp routes
+guest shells through one shared listener that holds frames only weakly).
Migration for **rss-reader** (#115972): replace the stubbed `/preview` → 501 →
`host.openWorkspace('rss-browser')` → empty `RssBrowserFrame` → `ctx.os.openExternal`