diff --git a/.agents/notes/implemented/architecture/2026-10-15-desktop-shared-texture-api.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-15-desktop-shared-texture-api.i18n.yaml new file mode 100644 index 0000000000..af203879f3 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-15-desktop-shared-texture-api.i18n.yaml @@ -0,0 +1,37 @@ +# Bilingual-pair consistency record for 2026-10-15-desktop-shared-texture-api.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-15-desktop-shared-texture-api.md +/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package: + en: de5e9439711001ae + zh: e5ac22aa5d51043d +/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/problem: + en: 4adf47d0d97b0e23 + zh: 12dedda00f579336 +/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/decision: + en: beeb92d43bbf3389 + zh: 39e77f9c22210ea3 +/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/decision/desktop-shared-textures: + en: 9cf55a65959c002c + zh: b29f1fc65936632e +/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/decision/trust-model: + en: d056763e283a5d30 + zh: fd7f1bba0ce5eba6 +/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/decision/the-frame-forwarding-package: + en: 59b3109d10f52831 + zh: f04c9bd2a730b30a +/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/decision/frame-path: + en: 7ba66e63258cc160 + zh: 87373d062c2dde60 +/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/alternatives-considered: + en: dfa341b1fe449288 + zh: 475e6ab42702ba36 +/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/verification: + en: a98f84f310538d8b + zh: bd345d71474eb862 +/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/consequences: + en: b823f7ee32d12180 + zh: f7338b942f03e81c +/agent-note-generic-desktop-shared-texture-api-with-a-shared-frame-forwarding-package/consequences/native-producer-sdk: + en: 9eabfbc1a83598d4 + zh: d43c9db0b40942c8 diff --git a/.agents/notes/implemented/architecture/2026-10-15-desktop-shared-texture-api.md b/.agents/notes/implemented/architecture/2026-10-15-desktop-shared-texture-api.md new file mode 100644 index 0000000000..3c1045cca9 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-15-desktop-shared-texture-api.md @@ -0,0 +1,105 @@ +# Agent Note: Generic Desktop shared-texture API with a shared frame-forwarding package + +Status: implemented + +English | [中文](2026-10-15-desktop-shared-texture-api.zh.md) + +## Problem + +The native Office preview needs textures rendered by a LibreOffice process to reach the Electron renderer without copying pixels, which requires an Electron main-process import and a renderer-side `sharedTexture` consumer. The first design of the Office Preview and Editing bundle let a bundle declare `dsh.bundle.desktop` with `main`, `preload`, and `verify` exports: Desktop imported the bundle's module into the main process, registered its preload for every frame of the default session, and verified the bundle's native payload with the bundle's own verifier. That selection could only be made at application startup, so enabling or disabling the bundle required a Desktop restart, and the startup selection had to be pinned through `loadProfileDirectory`, `ProfileRuntimeResolution`, `DSH_DESKTOP_STARTUP_BUNDLES`, the plugin manager (`restart-required`, `desktop-only`), the package manifest types, and the Web plugin list. Any installed package carrying the declaration could run code in the main process and in a session-wide preload, and Electron's `setSharedTextureReceiver` is a document singleton, so two such bundles would have overwritten each other. + +The correction that followed made frame forwarding a fixed Desktop capability: the Electron main process ran the native receiver (first loaded from the LibreOffice Kit's receiver SDK in the dsh runtime, then built from Kit sources copied into `apps/desktop`), validated producer metadata, and answered `frame-forwarding` control messages that carried viewports, generations, and credits. `apps/desktop` therefore carried protocol that only the Office preview used, its preload exposed frame forwarding rather than textures, a receiver inside Electron Main could not use libuv and needed Electron-compatible builds, and every protocol change required a Desktop release before a Kit release could use it. Copying the Kit's C++ into Desktop added a second claimed origin for one protocol; loading it from the Kit tied every Desktop receiver change to a Kit release. Frame forwarding is also not Office's: other Host plugins will render in native processes of their own, so the receiver, its transport, and its Host service cannot belong to the Office package either, and the Kit is one producer among several. + +Electron fixes what Desktop must own. `sharedTexture.importSharedTexture` runs only in the main process and accepts only a handle local to that process: an `IOSurfaceRef` on macOS, an NT `HANDLE` on Windows. `sharedTexture.subtle` exports an imported texture for a renderer to import, and each reference's release callback runs after the GPU work that used it completes. The managed `sendSharedTexture` waits at most 1000 ms for the renderer's acknowledgement; when Main then releases its reference, a renderer that was busy for longer imports a destroyed texture and shows an empty frame. Electron has no API that receives a GPU handle from a process outside Chromium, and Node cannot receive Mach messages or duplicate Win32 handles. On macOS, bringing a foreign IOSurface into Main needs native code in Main; on both platforms, carrying a Host-local handle toward Main needs native code in the Host. + +Whatever Desktop adds for that consumer is reachable by other code in the same process: a Host service by every Host plugin, a preload object by every script of the document. Two consumers of one texture interface would steal each other's frames, and a consumer that registers while frame forwarding is idle would take the interface over. The Office slideshow also entered window fullscreen through `dshDesktop.window.setFullscreen`, a Desktop-private API that Office read by duck typing and that Main restored by bookkeeping of its own; every plugin that needs fullscreen, for example a game, would have needed the same window control. + +## Decision + +Desktop owns an internal shared-texture API whose only consumer is frame forwarding, including the hop and ingress addons that open a native channel between the Host and Electron Main and carry Host-local handles across it; no plugin runs code in the Electron main process or a session-wide preload. The [`frame-forwarding`](../../../../packages/experimental/frame-forwarding/README.md) package owns frame forwarding for every Host plugin: the `frameForwarding` Host service, and the renderer-side views. + +### Desktop: shared textures + +Plugins see frame forwarding only. The shared-texture service definitions live in [`@deepseek-ai/dsh-shared-texture`](../../../../packages/shared-texture/shared-texture/README.md) with separate Host and Client compiler faces. Its root entry (`.`) defines the abstract Host `SharedTexture` Cordis service (`ctx.sharedTexture`), whose `claim()` grants `capabilities`, `nativeSink`, and `adapterLuid` to one holder until `release()` or the disposal of the scope that claimed; its `./types` entry defines the Cordis-free `SharedTextureClientExport`, `SharedTextureHostExport`, and `SharedTextureLease` shared by Desktop preload and the Client plugin; and its `./client` entry is the Client plugin that provides that bridge as the Client `ctx.sharedTexture`, typed `SharedTextureClientExport`. web-app mounts the package; its Host entry does nothing. Because Host and Client faces compile with separate `tsconfig.{host,client}.json` programs, the Host `Context` declaration never enters a Client program. Desktop Main takes the types of the `shared-texture` control messages (`capabilities` and `adapter-luid`) exchanged over the Host child-process channel from the Desktop Host's own `types` export ([`apps/desktop-host/src/types.ts`](../../../../apps/desktop-host/src/types.ts)), a private protocol between the two rather than a plugin API, and the hop addon's interfaces stay beside the service that loads it; each side validates every message it receives at runtime ([Main's channel](../../../../apps/desktop/src/shared-texture/channel.ts), [`apps/desktop-host/src/shared-texture.ts`](../../../../apps/desktop-host/src/shared-texture.ts)). The two apps share no package dependency; Main compiles against that export through a TypeScript project reference. Electron Main wires everything through one [entry](../../../../apps/desktop/src/shared-texture/main.ts) that attaches the [shared-texture channel](../../../../apps/desktop/src/shared-texture/channel.ts) to each Host process and supplies the window and Host cleanups; the channel validates every control request before Main's presenter sees it, and the Host-process lifecycle carries no shared-texture routing. + +- The Desktop Host's [`sharedTexture` service](../../../../apps/desktop-host/src/shared-texture.ts) takes Host-local handles and loads the hop addon ([`native/shared-texture/hop.cc`](../../../../apps/desktop/native/shared-texture/hop.cc), Node-API 8 only) that Main names in its capabilities on first use. On macOS and Windows the hop opens one native two-way connection to Main's ingress — a pair of Mach ports on macOS, and a duplex message named pipe on Windows where Main duplicates each frame's Host-local NT handle into its own process — and every frame's submission, delivery reply, and settlement travel on that connection while the Host IPC channel carries only `capabilities` and `adapter-luid`. Each connection admits at most 128 unsettled requests; losing the connection settles its unsettled requests as `invalidated`, and the next frame opens a new connection. `nativeSink(timeoutMs)` returns an opaque `napi_external` pointing to `dsh_shared_texture_sink_v2` ([`native/shared-texture/shared-texture-sink.h`](../../../../apps/desktop/native/shared-texture/shared-texture-sink.h)) for same-process native addons; a consumer built for another ABI version refuses it. A frame carries its handle, size, pixel format, metadata, and a delivery deadline that applies in the Host only, and no request identifier. The sink is bound to that connection: `present` returns `DSH_SHARED_TEXTURE_PRESENT_OK` when the request left the Host, `DSH_SHARED_TEXTURE_PRESENT_REJECTED` when it refused only that frame and the sink stays usable, and `DSH_SHARED_TEXTURE_PRESENT_DISCONNECTED` once the connection was closed or lost, for every later frame too, so the consumer obtains a new sink. Ending a claim that took `nativeSink` closes that connection and settles its unsettled frames as `invalidated`. `adapterLuid(timeoutMs)` returns `null` outside Windows without asking Main and never opens the native connection; on Windows Main exports one texture from Chromium's compositor, reads its adapter's LUID through the ingress addon, and releases the texture at once. Main keeps the answer until Chromium's GPU process exits or the Host stops, shares one reading among concurrent queries, and keeps no failed reading. The answer is `:` in lowercase hexadecimal, the text frame forwarding's receiver uses for adapters, or `null` when Chromium exports no Direct3D 11 compositor texture, DXGI cannot read its adapter, or a cleanup cancelled the reading. +- Main's ingress ([`native/shared-texture/ingress.cc`](../../../../apps/desktop/native/shared-texture/ingress.cc)) queues at most 32 frames waiting for Main's JavaScript thread and refuses any frame beyond them with no reference kept, so the Host can reuse that texture at once. For each admitted frame, Main's [presenter](../../../../apps/desktop/src/shared-texture/presenter.ts) imports the handle and sends the subtle transfer with the Host's metadata unchanged to the product main frame over Desktop's IPC. Main keeps its import until the document reports its own reference, then replies `delivered` on the native channel; a busy renderer delays that reply — keeping the Host's slot past a delivery timeout until settlement — instead of losing the texture. Main settles every admitted presentation once on the native channel: it replies `released` after its own release callback and the document's release, which the document sends from its release callback, have both arrived, and `invalidated` when the document, renderer, GPU process, or GPU release synchronization failed or went away first; a failure reply with no reference kept means Main retained nothing. Main validates the pixel dimensions Electron bounds and parses `metadata` JSON without interpreting its fields. +- Main's `capabilities` reports its process identity to the Desktop Host, which passes only support and a reason to its consumer; on macOS and Windows it also reports the hop addon path and opens one native ingress (Node-API 8 only) for the requesting Host. On macOS ([`native/shared-texture/ingress-darwin.cc`](../../../../apps/desktop/native/shared-texture/ingress-darwin.cc)) the ingress is a Mach receive port: it accepts a message only when its audit trailer names the Host process Main spawned, resolves the carried port with `IOSurfaceLookupFromMachPort`, delivers the Main-local `IOSurfaceRef`, and replies to the Host's reply port, dropping messages from other processes and oversized messages while the Host's messages keep arriving. On Windows ([`native/shared-texture/ingress-win32.cc`](../../../../apps/desktop/native/shared-texture/ingress-win32.cc)) the ingress is a single-instance duplex message named pipe: it checks `GetNamedPipeClientProcessId` against that Host process before reading, disconnects any other client, holds a `PROCESS_DUP_HANDLE | SYNCHRONIZE` handle to the connected Host, and duplicates each frame's NT `HANDLE` from the Host into Main; the same addon reads, through DXGI, the adapter LUID of a Main-local shared texture for `adapter-luid`. The ingress lives as long as that Host process: window-level cleanup keeps it, so the Host queries capabilities once per connection and presents every later frame over the native channel without another IPC round trip. An explicit capability query always reaches Main, which reports `gpu-compositing-disabled` while Chromium composites in software, for example after repeated GPU process crashes. A message from the Host with another protocol version or malformed contents stops the ingress with an error, ending the connection, and the next capability query reopens it. + +The application preload exposes `dshDesktop.textures` to the product main frame only: it imports each transfer, reports the result to Main at once, delivers `{ frame, metadata, release }` to the single document consumer, and releases textures that arrive without one. The shared-texture Client plugin provides `globalThis.dshDesktop?.textures` as the Client `ctx.sharedTexture`, so other Client plugins never read `globalThis.dshDesktop`. Desktop offers the document no window control: a plugin that shows a view fullscreen uses the document's Fullscreen API through frame forwarding, Electron makes the window fullscreen for the document's fullscreen element, and the existing state relay keeps window chrome in step. Main cancels a pending adapter reading, refuses frames arriving during cleanup, settles the textures sent to the document as `invalidated`, and starts a new document generation when the renderer or GPU process exits, a cross-document navigation commits, or the window closes; a GPU process exit also forgets the compositor adapter, and the ingress closes only when the Host process stops or fails. Main never reports an unobserved reference as released. Cancelled, intercepted, and same-document navigations keep the document's textures, and the document generation fails a capability query that spans a reset during ingress replacement. + +### Trust model + +Main trusts only the Host process it spawned. The macOS ingress drops every message whose audited sender PID differs from the Host's and keeps receiving the Host's; the Windows ingress checks `GetNamedPipeClientProcessId` before reading, disconnects any other client, and duplicates handles only from that Host process. Producers never communicate with Main, and only Desktop's hop touches the Host-to-Main channel. + +Security review has two process boundaries. The Host-to-Main boundary is Desktop's: any code in the Host process can send to Main without the `sharedTexture` service, so Main's request validation and the ingress PID check are audited as part of Desktop and do not change with frame forwarding. The producer-to-Host boundary is frame forwarding's, recorded in its [security semantics](../../../../packages/experimental/frame-forwarding/README.md#security-semantics). The plugin API is `frameForwarding` alone; reserving `sharedTexture` for the exclusive frame-forwarding consumer makes it unsupported for general plugins rather than unreachable, so it is not a security boundary. Both shared-texture surfaces admit one consumer at a time, and frame forwarding takes both while it is loaded: its Host plugin holds the Host `sharedTexture` claim from load to unload, and its Client consumes Client `ctx.sharedTexture` from start to disposal, also while no channel is open. Another consumer therefore fails at once instead of taking either interface over when frame forwarding is idle. A claim ends with the scope that took it, so a holder unloaded without releasing cannot keep it. + +### The frame-forwarding package + +`@deepseek-ai/dsh-frame-forwarding` owns frame forwarding for any Host plugin whose producer speaks its wire protocol. + +- The frame-forwarding workspace keeps the [receiver source](../../../../packages/experimental/frame-forwarding/native/receiver.cc) alongside the plugin that uses its protocol. Desktop builds it directly from the workspace for each macOS and Windows target and ships the binary and build record. The plugin’s npm package excludes the receiver sources and binary. Main resolves the addon's absolute path for the running Desktop and passes it to the Host as `--frame-receiver-path`. The Host publishes this path through its internal `desktopFrameReceiver` service. On first use the plugin checks the build record against its own protocol and handshake requirements, then loads the addon in the Host process. The listener and producer handshake for each channel run in the Host process. +- The Host [forwarder](../../../../packages/experimental/frame-forwarding/src/host/forwarder.ts) owns channels and their producer connections ([frame-forwarding channels](2026-10-18-frame-forwarding-channels.md)), the frame and byte budgets, and viewport acknowledgement and replay. When opening a channel, it asks `sharedTexture.capabilities()`, obtains `sharedTexture.nativeSink()`, and on Windows reads Chromium's adapter from `sharedTexture.adapterLuid()` before creating the receiver; every channel asks, because Desktop reads the adapter again after Chromium's GPU process restarts. It attaches the sink to the channel's receiver with `attachSink`, with a presentation deadline of at most 30000 ms, and updates the receiver's deliverable state via `setDeliverable` as connections, viewports, and visibility change. In the receiver addon, the C++ Desktop bridge validates producer metadata on the thread that produced the frame, filters frames against that deliverable state, and submits matching frames through `dsh_shared_texture_sink_v2` with `rx`, `connectionId`, `requestId`, `frameId`, `generation`, `revision`, `width`, and `height` as metadata, so steady-state frames never cross the Host's JavaScript event loop. On `on_settled`, the bridge returns the frame's credit directly when released; on `invalidated`, it stops the receiver before releasing the delivery and notifies the forwarder to close the channel as `lost`. Refused submissions and failed deliveries report `presentation-error` to the renderer; a submission refused with any result other than `DSH_SHARED_TEXTURE_PRESENT_REJECTED` detaches that sink, while a rejected frame leaves it attached; without an attached sink, frames arrive in JavaScript as `frame` events, where the forwarder returns the credit at once, requests a fresh `nativeSink`, and reattaches it to open channels. +- The Host plugin is a Typert Remote service: consumers use `capabilities`, `channel`, `isOpen`, and `close`; the renderer applies viewports through the `viewport` Remote and follows channel states from the `events` stream. The Client plugin provides the renderer-side `frameForwarding` service only when Client `ctx.sharedTexture` is available; `connect(rx)` returns a receive channel that consumes `ctx.sharedTexture`, routes textures by the `rx` in their metadata, lends each frame to a consumer callback, and releases it when the callback settles. Receive channels also hold the document's fullscreen element, one at a time, and report coverage to the others ([frame-forwarding channels](2026-10-18-frame-forwarding-channels.md)). A channel closes with the Cordis scope that opened it. +- Every consumer bundle inserts frame forwarding as the same row, `frame-forwarding`, without a config. The Loader keeps one row per id, so consumers enabled together share one instance and its one claim, and disabling one consumer leaves the instance and the other consumers' channels running; deployments tune its limits with a patch targeting that id. + +### Frame path + +``` +LibreOffice (Kit producer holding the channel's TX credential) + │ Packet protocol: hello / allocate / frame (+ handle) / release / message + ▼ +Host process — frame-forwarding receiver addon + C++ Desktop bridge (attachSink, setDeliverable) + │ credits, budget, handoff, metadata check, deliverable filter → dsh_shared_texture_sink_v2.present + ▼ +Host process — Desktop shared-texture hop addon (≤ 128 unsettled; Host IPC: capabilities / adapter-luid only) + │ macOS: Mach port pair (IOSurface port + reply port) ⇄ Main ingress + │ Windows: duplex message named pipe (Host NT HANDLE; Main DuplicateHandle from Host) ⇄ Main ingress + ▼ +Electron Main — shared-texture ingress addon (delivery queue ≤ 32) + presenter → renderer frame + │ document import result → delivered reply, Main drops its import; both GPU releases → released + ▼ +Native channel reply (released or invalidated) → hop reader → bridge on_settled returns credit (invalidated stops receiver first → channel lost) +``` + +## Alternatives considered + +**Keep the bundle-declared main, preload, and verify exports.** This hands every installed bundle main-process and session-wide preload execution for one consumer, duplicates a singleton Electron API across bundles, and forces startup-only activation with its restart plumbing through app-boot, plugin manager, manifest types, and the Web plugin list. Rejected in review. + +**Keep frame forwarding in Electron Main as a fixed Desktop capability.** This was the intermediate decision. It leaves protocol only one plugin uses and a receiver bound to the Electron main process in `apps/desktop`, couples protocol changes to Desktop releases, and makes the preload API a frame-forwarding API. Its own rejected variants remain rejected for the same reasons: loading the receiver SDK from the Kit installed in the dsh runtime ties every receiver change to a Kit release; libuv completion signalling (`uv_async_t`) lies outside Node-API's ABI guarantee and would force Electron-exact builds. + +**Give the Office package its own receiver addon with the hop inside it.** Frame forwarding serves every Host plugin that renders natively, not Office alone, and the hop is Desktop's shared-texture mechanism, not frame forwarding's. An Office-owned addon would have to be copied by the next consumer and would make a feature package the owner of Mach and Win32 handle transfer. + +**Electron's managed `sendSharedTexture` and `setSharedTextureReceiver`.** Its fixed 1000 ms acknowledgement deadline fails a view whenever the renderer's main thread is busy longer, and keeping Main's import past the deadline still returned the producer's texture before the renderer's GPU work completed. Rejected after real-device stall tests. + +**Load the plugin's addon into Electron Main through an extension slot.** Plugin native code would run in the main process. Loading it in the Host keeps Main's native code fixed to Desktop's ingress addon. + +**Publish the receiver as prebuilt npm platform packages now.** Desktop packaging already runs on each target operating system with a C++ toolchain; platform packages would add four packages, a release workflow, and Windows prebuild CI before the package has a second consumer. Deferred, not rejected. + +**No native code in Desktop, with pixels copied through the Host.** Each frame would copy tens of megabytes and lose the shared-texture path that motivates native preview. It remains a possible fallback for small viewports, not the design. + +**Let the producer send surfaces directly to Main's ingress.** This saves one Mach message per frame but requires Main to authenticate a process it did not spawn and requires the consumer to obtain Main's endpoint before starting the producer. The trust model excludes it; measured hop cost is the condition for revisiting. + +**Global IOSurface identifiers (`IOSurfaceLookup`).** Deprecated by Apple and readable by every process of the user. + +**Place the receiver in `apps/desktop-host`.** The Desktop Host would then carry one protocol's native build and service; Desktop Host provides shared textures and the preinstalled receiver’s location. The plugin owns the protocol checks and Node-API bindings. + +**Keep `dshDesktop.window.setFullscreen`.** It is a Desktop window control per plugin need, read by duck typing, with Main-side restore bookkeeping. Element fullscreen is document-scoped, ends on Escape without plugin code, and tells frame forwarding which channel covers the others. + +**Give each consumer bundle its own frame-forwarding row.** Two instances would compete for the one `sharedTexture` claim and the one renderer texture subscription; the second would report native rendering unavailable while the first serves only its own consumer. + +**Insert frame forwarding from the Desktop profile itself.** Every Desktop session would load the receiver and hold Desktop's interfaces even with no consumer enabled, and a profile without Desktop-specific rows could not stay shared with Web. + +**Making the Office Host plugin itself hide the bundle in Web.** The plugin needs no profile check: without `frameForwarding` support it reports unavailable, the Client registers no UI, and the existing PDF and spreadsheet preview remains. + +## Verification + +Desktop specs cover the [presenter](../../../../apps/desktop/tests/shared-texture-presenter.spec.ts) (one ingress per Host and replacement for another Host, software-compositing detection, the hop addon path and ingress endpoint, the 128-frame limit, Electron import failure without keeping a reference, renderer import results including a busy renderer, a failed import, and a missing GPU sync token, delivery-before-settlement reply ordering, `reset` invalidating frames sent to the document while keeping the ingress, `dispose` closing the ingress after abandoning sent frames, ingress failure and reopening, adapter LUID readings kept for their GPU process, shared by concurrent queries, not kept when they fail or a GPU process exit overtakes them, and null outside Windows, and the Main entry answering through its channel), the [preload bridge](../../../../apps/desktop/tests/preload-shared-texture.spec.ts) including import reports and the release report after its consumer and the GPU, [sent-texture settlement](../../../../apps/desktop/tests/shared-texture-transfer.spec.ts), the [shared-texture channel](../../../../apps/desktop/tests/shared-texture-channel.spec.ts) accepting only capability and bounded adapter requests and routing control with the Host identity, [generic Host-process channels](../../../../apps/desktop/tests/host-process.spec.ts), [declared native package builds](../../../../apps/desktop/tests/native-package-builds.spec.ts), and the [shared-texture addon verifier](../../../../apps/desktop/tests/shared-texture-runtime.spec.ts). The [Desktop native e2e](../../../../apps/desktop/tests/shared-texture-native.e2e.ts) exchanges real textures between separate Main and Host processes over the built hop and ingress addons from native `dsh_shared_texture_sink_v2` threads, covers every reply kind, refuses presentations that cannot leave the Host without sending them, reports sink ABI version 2 so a consumer built for another version refuses it, rejects frames beyond the 32-frame delivery queue at once while Main's JavaScript thread is blocked and resumes afterwards, ignores another process at the endpoint while continuing to serve the registered Host, ends the connection when a send finds Main gone or Main cannot deliver its replies, stops the ingress on another protocol version or malformed requests, enforces hop delivery deadlines while keeping the slot until Main settles, reconnects and settles once on close or Main exit, and reads the adapter LUID of a shared Direct3D 11 texture as the text Host addons derive while reading none from other handles. The [built-preload e2e](../../../../apps/desktop/tests/preload.e2e.ts) asserts `dshDesktop.textures` exposes only `onFrame` and `dshDesktop` exposes no window control. [Desktop Host specs](../../../../apps/desktop-host/tests/shared-texture.spec.ts) cover the single claim, its end with the claiming scope, including a claim taken inside an effect of that scope as frame forwarding takes it, a release before the scope's disposal that leaves the next holder's claim intact, hop connection reuse and reconnection after disconnect with unsettled frames invalidated, `nativeSink` closing its connection when the claim that took it ends while claims that never took it settle normally, `adapterLuid` returning Main's reading or null without opening the native connection, refusing a reading that is not a LUID, reporting Desktop's reason, and timing out while ignoring the late reply, unrelated channel traffic, and pending work rejected on disposal. Frame-forwarding specs cover the [forwarder](../../../../packages/experimental/frame-forwarding/tests/forwarder.host.spec.ts) (every Windows channel reading the adapter LUID from Desktop, every channel asking Desktop for its current `nativeSink` with concurrent requests shared, the sink deadline capped at 30000 ms, refresh when unattached frames reach JavaScript, deliverable-state updates pushed before each viewport is sent, presentation error and invalidation handling, producer connections and handoff, viewport replay, and teardown), the [Host service](../../../../packages/experimental/frame-forwarding/tests/service.host.spec.ts) with its claim, channel ownership by the opening scope, and Remote, the [receiver loader](../../../../packages/experimental/frame-forwarding/tests/native.host.spec.ts) and its build-record check, the [Client mount](../../../../packages/experimental/frame-forwarding/tests/mount.client.spec.ts), the [wire adapter](../../../../packages/experimental/frame-forwarding/tests/wire.client.spec.ts) with its lifelong texture subscription and fullscreen holder, and [receive channels](../../../../packages/experimental/frame-forwarding/tests/rx.client.spec.ts). The [Desktop bridge native e2e](../../../../packages/experimental/frame-forwarding/tests/desktop-bridge-native.e2e.ts) drives a real producer through the built receiver's C++ sink bridge, covering metadata projection, credit return on release and outside the deliverable state, delivery errors, an invalidated frame's notice followed by stopping its receiver and connection before its release, keeping the sink after a rejected frame and detaching a disconnected one so later frames reach JavaScript, synchronous callbacks inside `present`, ABI checks that refuse a sink of another magic or of version 1 or 3, settlements after receiver close and collection, and, when Desktop's addons are built, presentation through Desktop's hop sink into Desktop's ingress. The [Kit frames e2e](../../../../packages/experimental/frame-forwarding/tests/kit-frames-native.e2e.ts) drives the installed Kit's LibreOffice producer through the built receiver and the forwarder while an in-process native sink holds every presented frame. The [receiver native e2e](../../../../packages/experimental/frame-forwarding/tests/receiver-native.e2e.ts) compiles a fixture producer and drives it through the built receiver across producer processes, protocol and capability mismatches, and shared-budget trimming. The NodeNext declaration check rejects a published package whose public declarations import a private workspace package, which keeps Desktop's types out of frame forwarding's published API. No Session format or model-visible input changes. + +## Consequences + +Preinstalling the receiver lets users install or enable the plugin without a C++ toolchain. Native fixes and receiver protocol updates ship with Desktop. Each plugin version checks the preinstalled receiver and reports it as unavailable if incompatible. Steady-state frames bypass the Host's JavaScript event loop; between Host and Main each frame costs Mach messages on macOS or named-pipe messages and one `DuplicateHandle` by Main on Windows, never a pixel copy. Texture lifetime spans three processes: Main owns and closes the Windows handles it duplicated from the Host once Electron's GPU work finishes or Host teardown runs, and a Main exit ends the Host and the producer with it. On Windows, Main opens the Host it spawned with `PROCESS_DUP_HANDLE | SYNCHRONIZE` while the Host never opens Main; a failed open disconnects the pipe and a denied `DuplicateHandle` replies with a delivery error rather than presenting nothing silently. + +### Native producer SDK + +The native producer interface is still evolving with the Office integration. DSH defers publishing a third-party producer SDK because external plugins could come to depend on C calls that still change with the engine. Reconsider publication once the producer interface has settled. LibreOffice Kit connects through its own engine. diff --git a/.agents/notes/implemented/architecture/2026-10-15-desktop-shared-texture-api.zh.md b/.agents/notes/implemented/architecture/2026-10-15-desktop-shared-texture-api.zh.md new file mode 100644 index 0000000000..db000cde5f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-15-desktop-shared-texture-api.zh.md @@ -0,0 +1,105 @@ +# Agent Note: 通用 Desktop 共享纹理 API 与共享的帧转发包 + +Status: implemented + +[English](2026-10-15-desktop-shared-texture-api.md) | 中文 + +## Problem + +原生 Office 预览需要把 LibreOffice 进程渲染的纹理不经像素拷贝地送达 Electron renderer,这要求一个 Electron 主进程侧的导入和一个 renderer 侧的 `sharedTexture` 消费者。“Office 预览编辑”bundle 的第一版设计允许 bundle 通过 `dsh.bundle.desktop` 声明 `main`、`preload` 和 `verify` 导出:Desktop 把 bundle 的模块导入主进程,为默认 session 的每一个 frame 注册其 preload,并用 bundle 自带的校验器校验其原生载荷。这种选择只能在应用启动时做出,因此启用或关闭该 bundle 必须重启 Desktop,而启动时的选择又必须穿透 `loadProfileDirectory`、`ProfileRuntimeResolution`、`DSH_DESKTOP_STARTUP_BUNDLES`、插件管理器(`restart-required`、`desktop-only`)、包清单类型和 Web 插件列表加以钉死。任何带有该声明的已安装包都能在主进程和 session 级 preload 中运行代码;而 Electron 的 `setSharedTextureReceiver` 是 document 级单例,两个这样的 bundle 会互相覆盖。 + +随后的修正把帧转发变成 Desktop 的固定能力:Electron 主进程运行原生接收器(先是从 dsh runtime 内的 LibreOffice Kit 接收端 SDK 加载,后来用拷贝进 `apps/desktop` 的 Kit 源码构建),校验 producer 元数据,并应答携带 viewport、generation 和信用的 `frame-forwarding` 控制消息。于是 `apps/desktop` 带着只有 Office 预览使用的协议,其 preload 暴露的是帧转发而不是纹理,位于 Electron Main 内的接收器不能使用 libuv 且需要与 Electron 兼容的构建,而每次协议变更都要先发 Desktop 版本,Kit 版本才能使用。把 Kit 的 C++ 拷进 Desktop 让同一个协议多出第二个自称的来源;从 Kit 加载则把 Desktop 接收器的每次变更绑死在 Kit 发版上。帧转发也不属于 Office:其他 Host 插件将来也会在各自的原生进程中渲染,因此接收器、传输和 Host 服务也不能归 Office 包所有,Kit 只是多个 producer 中的一个。 + +Electron 决定了 Desktop 必须持有什么。`sharedTexture.importSharedTexture` 只在主进程运行,且只接受该进程本地的句柄:macOS 上是 `IOSurfaceRef`,Windows 上是 NT `HANDLE`。`sharedTexture.subtle` 导出已导入的纹理供 renderer 导入,每个引用的释放回调在使用它的 GPU 工作完成后运行。托管的 `sendSharedTexture` 最多等待 renderer 确认 1000 ms;此后 Main 释放自己的引用,忙碌更久的 renderer 会导入一个已销毁的纹理并显示空帧。Electron 没有任何 API 能从 Chromium 之外的进程接收 GPU 句柄,Node 也不能接收 Mach 消息或复制 Win32 句柄。在 macOS 上,把外部 IOSurface 带进 Main 需要 Main 里的原生代码;在两个平台上,把 Host 本地句柄送往 Main 都需要 Host 里的原生代码。 + +Desktop 为这个消费者新增的任何东西,同一进程中的其他代码也能触达:Host 服务能被每个 Host 插件调用,preload 对象能被文档中的每段脚本调用。同一纹理接口的两个消费者会互相抢走对方的帧,在帧转发空闲时注册的消费者会接管该接口。Office 放映还通过 `dshDesktop.window.setFullscreen` 进入窗口全屏,这是 Desktop 的私有 API,Office 以鸭子类型读取它,Main 则靠自己的记录来恢复窗口状态;每个需要全屏的插件(例如游戏)都得要同样的窗口控制。 + +## Decision + +Desktop 持有一个内部共享纹理 API,其唯一消费者是帧转发,包括在 Host 与 Electron Main 之间建立原生通道并跨通道传递 Host 本地句柄的跳转与 ingress addon;没有任何插件在 Electron 主进程或 session 级 preload 中运行代码。[`frame-forwarding`](../../../../packages/experimental/frame-forwarding/README.zh.md) 包为所有 Host 插件持有帧转发:`frameForwarding` Host 服务和 renderer 侧视图。 + +### Desktop:共享纹理 + +插件只看到帧转发。共享纹理服务定义位于 [`@deepseek-ai/dsh-shared-texture`](../../../../packages/shared-texture/shared-texture/README.zh.md),采用独立的 Host 与 Client 编译面。其根入口(`.`)定义抽象 Host Cordis 服务 `SharedTexture`(`ctx.sharedTexture`),其 `claim()` 把 `capabilities`、`nativeSink` 和 `adapterLuid` 交给唯一的持有者,直到 `release()` 或发起认领的作用域被销毁;`./types` 入口定义不含 Cordis 依赖的 `SharedTextureClientExport`、`SharedTextureHostExport` 与 `SharedTextureLease`,供 Desktop preload 与 Client 插件共用;`./client` 入口是 Client 插件,把该桥接提供为 Client 侧的 `ctx.sharedTexture`,类型为 `SharedTextureClientExport`。web-app 挂载本包,其 Host 入口不做任何事。由于 Host 与 Client 编译面使用各自独立的 `tsconfig.{host,client}.json` 程序,Host 的 `Context` 声明不会进入 Client 程序。Desktop Main 从 Desktop Host 自己的 `types` 导出([`apps/desktop-host/src/types.ts`](../../../../apps/desktop-host/src/types.ts))导入两者经 Host 子进程通道交换的 `shared-texture` 控制消息(`capabilities` 和 `adapter-luid`)的类型;这是两者之间的私有协议,不是插件 API,hop addon 的接口留在加载它的服务旁边。两侧各自在运行时校验收到的每条消息([Main 的通道](../../../../apps/desktop/src/shared-texture/channel.ts)、[Host 的服务](../../../../apps/desktop-host/src/shared-texture.ts))。两个应用之间没有包依赖:Main 通过 TypeScript 项目引用编译这组导出。Electron Main 通过一个[入口](../../../../apps/desktop/src/shared-texture/main.ts)接入全部内容:它把 [shared-texture 通道](../../../../apps/desktop/src/shared-texture/channel.ts)挂到每个 Host 进程上,并提供窗口级和 Host 级清理;通道在 Main 的 presenter 看到请求之前校验每个控制请求,Host 进程生命周期不携带任何 shared-texture 路由。 + +- Desktop Host 的 [`sharedTexture` 服务](../../../../apps/desktop-host/src/shared-texture.ts)接收 Host 本地句柄,并在首次使用时加载 Main 在其能力中给出的跳转 addon([`native/shared-texture/hop.cc`](../../../../apps/desktop/native/shared-texture/hop.cc),仅依赖 Node-API 8)。macOS 和 Windows 上都由跳转向 Main 的 ingress 打开一条原生双向连接——macOS 上是一对 Mach 端口,Windows 上是双工消息命名管道并由 Main 把每帧的 Host 本地 NT 句柄复制进自己的进程——每帧的提交、送达回执和结算都走这条连接,Host 的 IPC 通道只承载 `capabilities` 和 `adapter-luid`。每条连接最多接纳 128 个未结算请求;连接丢失时所有未结算请求按 `invalidated` 结算,下一帧打开新连接。`nativeSink(timeoutMs)` 返回一个指向 `dsh_shared_texture_sink_v2`([`native/shared-texture/shared-texture-sink.h`](../../../../apps/desktop/native/shared-texture/shared-texture-sink.h))的不透明 `napi_external` 供同进程原生 addon 使用;按其他 ABI 版本构建的消费者会拒绝它。每帧携带句柄、尺寸、像素格式、元数据和只在 Host 本地生效的送达期限,不带请求标识。sink 归属当前连接:请求已离开 Host 时 `present` 返回 `DSH_SHARED_TEXTURE_PRESENT_OK`,只拒绝这一帧且 sink 仍可用时返回 `DSH_SHARED_TEXTURE_PRESENT_REJECTED`,连接已关闭或丢失时返回 `DSH_SHARED_TEXTURE_PRESENT_DISCONNECTED`,之后每一帧也都如此,消费者随即取得新的 sink。取过 `nativeSink` 的认领结束时会关闭该连接并把未结算帧按 `invalidated` 结算。`adapterLuid(timeoutMs)` 在 Windows 以外直接返回 `null` 而不询问 Main,且从不打开原生连接;Windows 上 Main 从 Chromium 合成器导出一张纹理,经 ingress addon 读出其 adapter 的 LUID,并立即释放该纹理。Main 保留这个答案直到 Chromium 的 GPU 进程退出或 Host 停止,并发查询共用一次读取,失败的读取不保留。答案是小写十六进制的 `:`,与帧转发接收器表示 adapter 的文本一致;Chromium 没有导出 Direct3D 11 合成器纹理、DXGI 读不出其 adapter 或读取被清理取消时为 `null`。 +- Main 的 ingress([`native/shared-texture/ingress.cc`](../../../../apps/desktop/native/shared-texture/ingress.cc))最多排队 32 帧等待 Main 的 JavaScript 线程,超出的帧当场按未保留引用拒绝,Host 可立即复用该纹理。对每一帧获准进入的帧,Main 的 [presenter](../../../../apps/desktop/src/shared-texture/presenter.ts) 导入句柄,经 Desktop 的 IPC 把 subtle 传输连同 Host 原样的 metadata 送到产品主 frame。Main 一直持有自己的导入,直到文档报告它已持有自己的引用,再在原生通道上回复 `delivered`;忙碌的 renderer 只会推迟该回复——即使送达超时也继续保留 Host 的槽位直至结算——而不会丢失纹理。Main 在原生通道上对每次获准的呈现只结算一次:自己的释放回调和文档的释放(文档在其释放回调中发出)都到达后回复 `released`;文档、renderer、GPU 进程或 GPU 释放同步先行消失或失败时回复 `invalidated`;不保留引用的失败回复表示 Main 未保留任何引用。Main 校验 Electron 限定的像素尺寸,解析 `metadata` 的 JSON 而不解释其中的字段。 +- Main 的 `capabilities` 向 Desktop Host 报告其进程身份,Desktop Host 只把是否支持及原因交给其消费者;macOS 和 Windows 上还报告跳转 addon 路径,并为发出请求的 Host 打开一个仅依赖 Node-API 8 的原生 ingress。macOS 上([`native/shared-texture/ingress-darwin.cc`](../../../../apps/desktop/native/shared-texture/ingress-darwin.cc))ingress 是 Mach 接收端口:仅当消息的 audit trailer 指向 Main 所启动的 Host 进程时才接受,用 `IOSurfaceLookupFromMachPort` 解析携带的端口,交付 Main 本地的 `IOSurfaceRef` 并向 Host 的回复端口应答,同时丢弃其他进程的消息和超长消息而继续接收 Host 的消息。Windows 上([`native/shared-texture/ingress-win32.cc`](../../../../apps/desktop/native/shared-texture/ingress-win32.cc))ingress 是单实例双工消息命名管道:读取前先核对 `GetNamedPipeClientProcessId` 为该 Host 进程并断开任何其他客户端,连接期间持有该 Host 的 `PROCESS_DUP_HANDLE | SYNCHRONIZE` 句柄,把每帧的 NT `HANDLE` 从 Host 复制进 Main;同一 addon 还为 `adapter-luid` 经 DXGI 读取 Main 本地共享纹理的 adapter LUID。ingress 与该 Host 进程同寿命:窗口级清理保留它,因此 Host 每条连接只查询一次能力,之后每一帧都直接经原生通道呈现,无需额外的 IPC 往返。显式的能力查询总会到达 Main;Chromium 改用软件合成时(例如 GPU 进程多次崩溃后),Main 报告 `gpu-compositing-disabled`。Host 发来的协议版本不符或内容畸形的消息会以错误停止 ingress 并结束连接,下一次能力查询会重新打开它。 + +应用 preload 仅向产品主 frame 暴露 `dshDesktop.textures`:它导入每个传输,立即向 Main 报告结果,把 `{ frame, metadata, release }` 交付给唯一的文档消费者,没有消费者时立即释放到达的纹理。共享纹理 Client 插件把 `globalThis.dshDesktop?.textures` 提供为 Client 侧的 `ctx.sharedTexture`,因此其他 Client 插件从不读取 `globalThis.dshDesktop`。Desktop 不向文档提供窗口控制:要全屏显示视图的插件经帧转发使用文档的 Fullscreen API,Electron 为文档的全屏元素让窗口全屏,现有的状态同步让窗口外观随之调整。当 renderer 或 GPU 进程退出、跨文档导航提交或窗口关闭时,Main 取消待完成的 adapter 读取、拒绝清理期间到达的帧、把已发往文档的纹理结算为 `invalidated`,并开始新的文档代次;GPU 进程退出还会让 Main 忘掉合成器 adapter,只有在 Host 进程停止或失败时才关闭 ingress。Main 从不把未观察到的引用报告为已释放。被取消、被拦截和同文档导航保留文档的纹理,文档代次让跨越 ingress 替换期间发生的 reset 的能力查询失败。 + +### 信任模型 + +Main 只信任自己启动的 Host 进程。macOS ingress 丢弃经 audit 的发送方 PID 与 Host 不同的每条消息,并继续接收 Host 的消息;Windows ingress 在读取前核对 `GetNamedPipeClientProcessId`,断开任何其他客户端,并只从该 Host 进程复制句柄。producer 永远不与 Main 通信,Host 中只有 Desktop 的跳转接触 Host 到 Main 的通道。 + +安全审查面对两条进程边界。Host 到 Main 的边界属于 Desktop:Host 进程中的任何代码都能绕过 `sharedTexture` 服务直接向 Main 发送消息,因此 Main 的请求校验和 ingress 的 PID 检查作为 Desktop 的一部分审计,不随帧转发变化。producer 到 Host 的边界属于帧转发,记录在其[安全语义](../../../../packages/experimental/frame-forwarding/README.zh.md#security-semantics)中。插件 API 只有 `frameForwarding`;将 `sharedTexture` 保留给独占的帧转发消费者,只让它对普通插件不受支持,而不是不可达,因此它不是安全边界。两侧共享纹理接口同一时间都只接纳一个消费者,帧转发在加载期间占用二者:其 Host 插件从加载到卸载持有 Host 的 `sharedTexture` 认领,其 Client 从启动到销毁消费 Client 的 `ctx.sharedTexture`(没有打开的通道时也是如此)。因此其他消费者会立即失败,而不会在帧转发空闲时接管任一接口。认领随发起它的作用域结束,因此未释放就被卸载的持有者无法继续占用它。 + +### 帧转发包 + +`@deepseek-ai/dsh-frame-forwarding` 为任何 producer 使用其线上协议的 Host 插件持有帧转发。 + +- frame-forwarding 工作区将[接收器源码](../../../../packages/experimental/frame-forwarding/native/receiver.cc)与使用其协议的插件放在一起。Desktop 打包时直接从工作区为 macOS 和 Windows 的目标架构编译接收器,并预装二进制文件和构建清单。插件 npm 包不含接收器源码和二进制文件。Desktop 主进程根据当前安装位置或开发目录确定接收器的绝对路径,通过启动参数 `--frame-receiver-path` 传给 Host。Host 通过内部服务 `desktopFrameReceiver` 提供这个路径。插件首次使用时按自身要求校验构建清单中的协议版本和握手能力,再在 Host 进程中加载模块。每个通道的监听和与 producer 的握手都在 Host 进程中完成。 +- Host 的 [forwarder](../../../../packages/experimental/frame-forwarding/src/host/forwarder.ts) 持有通道及其 producer 连接([帧转发通道](2026-10-18-frame-forwarding-channels.zh.md))、帧数与字节预算,以及 viewport 确认与重放。打开通道时,它询问 `sharedTexture.capabilities()`,取得 `sharedTexture.nativeSink()`,Windows 上还在创建接收器前通过 `sharedTexture.adapterLuid()` 读取 Chromium 的 adapter;每个通道都会询问,因为 Chromium 的 GPU 进程重启后 Desktop 会重新读取 adapter。它以 `attachSink` 把 sink 挂到该通道的接收器上,呈现期限最多 30000 ms,随后随连接、viewport 和可见性变化通过 `setDeliverable` 更新可交付状态。接收器 addon 内的 C++ Desktop 桥在产生帧的线程上校验 producer 元数据、按该可交付状态过滤帧,并以 `rx`、`connectionId`、`requestId`、`frameId`、`generation`、`revision`、`width` 和 `height` 作为元数据经 `dsh_shared_texture_sink_v2` 提交匹配的帧,稳态帧不经过 Host 的 JavaScript 事件循环。`on_settled` 回调在正常释放时直接归还帧信用;`invalidated` 时先停止接收器再释放交付,并通知 forwarder 以 `lost` 关闭通道。被拒绝的提交和失败的送达向 renderer 报告 `presentation-error`;以 `DSH_SHARED_TEXTURE_PRESENT_REJECTED` 之外的结果被拒的提交会解挂该 sink,被拒绝的单帧则保留 sink;未挂载 sink 时帧以 `frame` 事件到达 JavaScript,forwarder 立即归还信用,重新获取 `nativeSink` 并挂回各打开的通道。 +- Host 插件是一个 Typert Remote 服务:消费者使用 `capabilities`、`channel`、`isOpen` 和 `close`;renderer 通过 `viewport` Remote 应用 viewport,并从 `events` 流跟随通道状态。Client 插件仅在 Client `ctx.sharedTexture` 可用时提供 renderer 侧的 `frameForwarding` 服务;`connect(rx)` 返回一个接收通道,它消费 `ctx.sharedTexture`,按元数据中的 `rx` 路由纹理,把每一帧借给消费者回调,并在回调结束后释放该帧。接收通道还持有文档的全屏元素(同一时间只有一个),并向其他通道报告遮挡([帧转发通道](2026-10-18-frame-forwarding-channels.zh.md))。通道随打开它的 Cordis 作用域一起关闭。 +- 每个消费者 bundle 都以同一行 `frame-forwarding` 插入帧转发,且不带 config。Loader 对每个 id 只保留一行,因此同时启用的消费者共享同一个实例及其唯一的认领,关闭其中一个消费者时,该实例和其他消费者的通道继续运行;部署方用针对该 id 的 patch 调整其上限。 + +### 帧路径 + +``` +LibreOffice (Kit producer holding the channel's TX credential) + │ Packet protocol: hello / allocate / frame (+ handle) / release / message + ▼ +Host process — frame-forwarding receiver addon + C++ Desktop bridge (attachSink, setDeliverable) + │ credits, budget, handoff, metadata check, deliverable filter → dsh_shared_texture_sink_v2.present + ▼ +Host process — Desktop shared-texture hop addon (≤ 128 unsettled; Host IPC: capabilities / adapter-luid only) + │ macOS: Mach port pair (IOSurface port + reply port) ⇄ Main ingress + │ Windows: duplex message named pipe (Host NT HANDLE; Main DuplicateHandle from Host) ⇄ Main ingress + ▼ +Electron Main — shared-texture ingress addon (delivery queue ≤ 32) + presenter → renderer frame + │ document import result → delivered reply, Main drops its import; both GPU releases → released + ▼ +Native channel reply (released or invalidated) → hop reader → bridge on_settled returns credit (invalidated stops receiver first → channel lost) +``` + +## Alternatives considered + +**保留 bundle 声明的 main、preload 和 verify 导出。** 这为一个消费者把主进程和 session 级 preload 的执行权交给每个已安装的 bundle,在多个 bundle 间重复一个单例 Electron API,并强制只能在启动时激活,连带穿透 app-boot、插件管理器、清单类型和 Web 插件列表的重启管线。评审中否决。 + +**把帧转发作为 Desktop 的固定能力留在 Electron Main。** 这是中间阶段的决定。它把只有一个插件使用的协议和绑定在 Electron 主进程的接收器留在 `apps/desktop`,把协议变更与 Desktop 发版耦合,并让 preload API 成为帧转发 API。它自身否决过的变体出于同样理由仍被否决:从 dsh runtime 内安装的 Kit 加载接收端 SDK 把每次接收器变更绑在 Kit 发版上;libuv 完成信号(`uv_async_t`)在 Node-API 的 ABI 保证之外,会迫使按 Electron 精确头文件构建。 + +**让 Office 包自带一个内含跳转的接收器 addon。** 帧转发服务于每个原生渲染的 Host 插件,而不只是 Office;跳转是 Desktop 共享纹理的机制,不是帧转发的。Office 自有的 addon 会被下一个消费者再拷一份,并让一个功能包成为 Mach 和 Win32 句柄传递的所有者。 + +**Electron 托管的 `sendSharedTexture` 和 `setSharedTextureReceiver`。** 它固定的 1000 ms 确认期限会在 renderer 主线程忙碌更久时让视图失败;即使在期限后继续持有 Main 的导入,也仍会在 renderer 的 GPU 工作完成前把 producer 的纹理归还。经真机卡顿测试后否决。 + +**通过扩展槽把插件的 addon 加载进 Electron Main。** 插件原生代码会在主进程中运行。在 Host 中加载它,让 Main 的原生代码固定为 Desktop 的 ingress addon。 + +**现在就把接收器作为预构建的 npm 平台包发布。** Desktop 打包已经在每个目标操作系统上带 C++ 工具链运行;在该包有第二个消费者之前,平台包会增加四个包、一条发布流程和 Windows 预构建 CI。推迟,而非否决。 + +**Desktop 不含原生代码,像素经 Host 拷贝。** 每帧要拷贝几十 MB,并失去原生预览赖以成立的共享纹理路径。它仍可作为小视口的兜底,不是本设计。 + +**让 producer 直接把 surface 发到 Main 的 ingress。** 这每帧省一条 Mach 消息,但要求 Main 鉴别一个不是它启动的进程,并要求消费者在启动 producer 之前拿到 Main 的端点。信任模型排除了它;重新考虑的条件是实测的跳转开销。 + +**全局 IOSurface 标识符(`IOSurfaceLookup`)。** 已被 Apple 弃用,且用户的任何进程都可读取。 + +**把接收器放在 `apps/desktop-host`。** Desktop Host 将因此背上一个协议的原生构建和服务;Desktop Host 提供共享纹理和预装接收器的位置,协议校验和 Node-API 绑定由插件维护。 + +**保留 `dshDesktop.window.setFullscreen`。** 它是按插件需求增设的 Desktop 窗口控制,以鸭子类型读取,并需要 Main 一侧的恢复记录。元素全屏以文档为范围,按 Escape 即可结束而无需插件代码,并让帧转发知道是哪个通道遮挡了其他通道。 + +**让每个消费者 bundle 各自插入一行帧转发。** 两个实例会争夺唯一的 `sharedTexture` 认领和唯一的 renderer 纹理订阅;第二个实例会报告原生渲染不可用,而第一个只服务自己的消费者。 + +**由 Desktop profile 自身插入帧转发。** 即使没有启用任何消费者,每个 Desktop 会话也会加载接收器并占用 Desktop 的接口,而不带 Desktop 专属行的 profile 也无法继续与 Web 共用。 + +**让 Office Host 插件自己在 Web 中隐藏 bundle。** 插件不需要 profile 检查:`frameForwarding` 不受支持时它报告不可用,Client 不注册 UI,现有的 PDF 和表格预览保持不变。 + +## Verification + +Desktop 规格测试覆盖 [presenter](../../../../apps/desktop/tests/shared-texture-presenter.spec.ts)(每个 Host 一个 ingress 并在换 Host 时替换、软件合成检测、跳转 addon 路径与 ingress 端点、128 帧上限、不保留引用的 Electron 导入失败、renderer 导入结果(包括忙碌的 renderer、失败的导入和缺失的 GPU 同步 token)、先送达回复再结算回复的顺序、`reset` 在保留 ingress 的同时把已发往文档的帧结算为 `invalidated`、`dispose` 先放弃已发送的帧再关闭 ingress、ingress 失败与重开、adapter LUID 读取按 GPU 进程保留、并发查询共用、失败或被 GPU 进程退出抢先时不保留、Windows 以外返回 null,以及经通道应答的 Main 入口)、[preload 桥接](../../../../apps/desktop/tests/preload-shared-texture.spec.ts)(含导入结果报告,以及消费者和 GPU 用完之后的释放报告)、[已发送纹理的结算](../../../../apps/desktop/tests/shared-texture-transfer.spec.ts)、[shared-texture 通道](../../../../apps/desktop/tests/shared-texture-channel.spec.ts)只接受能力查询与有界 adapter 请求并携带 Host 身份路由控制、[通用 Host 进程通道](../../../../apps/desktop/tests/host-process.spec.ts)、[声明式原生包构建](../../../../apps/desktop/tests/native-package-builds.spec.ts),以及 [shared-texture addon 校验器](../../../../apps/desktop/tests/shared-texture-runtime.spec.ts)。[Desktop 原生 e2e](../../../../apps/desktop/tests/shared-texture-native.e2e.ts) 在独立的 Main 与 Host 进程间经已构建的跳转与 ingress addon 从原生 `dsh_shared_texture_sink_v2` 线程交换真实纹理,覆盖每种回复类型、无法离开 Host 的呈现不发送即被拒、报告 sink ABI 版本 2 使按其他版本构建的消费者拒绝它、Main 的 JavaScript 线程阻塞时超出 32 帧投递队列的帧当场被拒并在恢复后继续处理、忽略端点上的其他进程并继续服务已注册的 Host、发送时发现 Main 已退出或 Main 无法投递其回复时结束连接、协议版本不符或请求畸形时停止 ingress、执行跳转送达期限的同时保留槽位直至 Main 结算、关闭或 Main 退出后的重连与单次结算,以及把共享 Direct3D 11 纹理的 adapter LUID 读成 Host addon 推导出的文本、其他句柄读不出 adapter。[构建产物 preload 的 e2e](../../../../apps/desktop/tests/preload.e2e.ts) 断言 `dshDesktop.textures` 只暴露 `onFrame`,且 `dshDesktop` 不暴露窗口控制。[Desktop Host 规格测试](../../../../apps/desktop-host/tests/shared-texture.spec.ts)覆盖唯一的认领、认领随发起它的作用域结束(包括像帧转发那样在该作用域的 effect 中发起的认领)、作用域销毁前的释放不影响下一个持有者的认领、跳转连接复用以及断连时把未结算帧置为 `invalidated` 并重连、取过 `nativeSink` 的认领结束时关闭该连接而未取过的认领正常结算、`adapterLuid` 不打开原生连接即返回 Main 的读取结果或 null、拒绝不是 LUID 的读取结果、报告 Desktop 给出的原因、超时并忽略迟到的回复、无关的通道流量,以及销毁时拒绝待完成的工作。帧转发规格测试覆盖 [forwarder](../../../../packages/experimental/frame-forwarding/tests/forwarder.host.spec.ts)(每个 Windows 通道都向 Desktop 读取 adapter LUID、每个通道都向 Desktop 取当前的 `nativeSink` 且并发请求合并、sink 期限上限 30000 ms、未挂载帧到达 JavaScript 时的刷新、在发出每个 viewport 之前更新可交付状态、呈现错误与失效处理、producer 连接与交接、viewport 重放、拆除)、[Host 服务](../../../../packages/experimental/frame-forwarding/tests/service.host.spec.ts)及其认领、由打开方作用域持有的通道和 Remote、[接收器加载器](../../../../packages/experimental/frame-forwarding/tests/native.host.spec.ts)及其构建记录检查、[Client 挂载](../../../../packages/experimental/frame-forwarding/tests/mount.client.spec.ts)、[wire 适配](../../../../packages/experimental/frame-forwarding/tests/wire.client.spec.ts)(含常驻的纹理订阅与全屏持有者)和[接收通道](../../../../packages/experimental/frame-forwarding/tests/rx.client.spec.ts)。[Desktop 桥原生 e2e](../../../../packages/experimental/frame-forwarding/tests/desktop-bridge-native.e2e.ts) 驱动真实 producer 穿过已构建接收器的 C++ sink 桥,覆盖元数据投射、正常释放和处于可交付状态之外时的信用归还、送达错误、被置为失效的帧先发出通知、再停止接收器及其连接后才释放、单帧被拒时保留 sink 而连接断开时解挂 sink 让后续帧到达 JavaScript、`present` 内同步触发的回调、拒绝其他 magic 或版本 1、3 的 sink 的 ABI 检查、接收器关闭并被垃圾回收后到达的结算,以及在 Desktop 的 addon 已构建时经 Desktop 的跳转 sink 送进 Desktop 的 ingress。[Kit 帧 e2e](../../../../packages/experimental/frame-forwarding/tests/kit-frames-native.e2e.ts) 在进程内原生 sink 扣住每一帧已呈现帧时,驱动已安装 Kit 的 LibreOffice producer 穿过已构建的接收器和 forwarder。[接收器原生 e2e](../../../../packages/experimental/frame-forwarding/tests/receiver-native.e2e.ts) 编译测试用 producer,跨 producer 进程、协议与能力不匹配以及共享预算收缩驱动它穿过已构建的接收器。NodeNext 声明检查拒绝公开声明 import 私有 workspace 包的发布包,从而让 Desktop 的类型不进入帧转发的发布 API。无 Session 格式或模型可见输入的变化。 + +## Consequences + +插件可以在运行时安装或启用。由 Desktop 预装接收器,可以在没有 C++ 工具链的机器上启用 Office 预览;接收器的协议和原生修复随 Desktop 发版。各版本插件自行校验预装接收器,不兼容时报告不可用。稳态帧绕过 Host 的 JavaScript 事件循环;在 Host 与 Main 之间,每帧在 macOS 上开销为 Mach 消息,在 Windows 上开销为命名管道消息加 Main 执行的一次 `DuplicateHandle`,没有像素拷贝。纹理生命周期跨越三个进程:Main 自己持有并在 Electron 的 GPU 工作完成或 Host 拆除时关闭它从 Host 复制来的 Windows 句柄,Main 退出会连带结束 Host 和 producer。Windows 上由 Main 以 `PROCESS_DUP_HANDLE | SYNCHRONIZE` 打开自己启动的 Host,Host 从不打开 Main;打开失败会断开管道,`DuplicateHandle` 被拒绝会返回送达错误,而不是静默地什么都不呈现。 + +### Native producer SDK + +原生 producer 接口仍在随 Office 集成调整。DSH 暂不向第三方发布 producer SDK:现在公开 C 头文件和静态库会让外部插件依赖仍可能变化的调用方式。待接口定型后再决定是否开放。LibreOffice Kit 通过自己的引擎接入。 diff --git a/.agents/notes/implemented/architecture/2026-10-18-frame-forwarding-channels.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-18-frame-forwarding-channels.i18n.yaml new file mode 100644 index 0000000000..d61e6aeca6 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-18-frame-forwarding-channels.i18n.yaml @@ -0,0 +1,46 @@ +# Bilingual-pair consistency record for 2026-10-18-frame-forwarding-channels.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-18-frame-forwarding-channels.md +/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget: + en: 6ffcd2e12496f609 + zh: 3aac5b5b6fcaf426 +/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/problem: + en: 41f0d6fa7045c3a2 + zh: 15ee3e573127d43c +/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/decision: + en: a15c7c13f167e5ac + zh: a15c7c13f167e5ac +/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/decision/channels-and-credentials: + en: ccf914afe119ab1e + zh: 12fbff4a5e879ca4 +/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/decision/connections-and-handoff: + en: 4fdd0bed5e2a8bf9 + zh: 361d50bee163c4d9 +/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/decision/producers-name-only-their-own-handles: + en: 1c00e9088f93e12f + zh: 060e06ef9ebc164b +/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/decision/compatibility: + en: 0f0266faf90bd2b2 + zh: 565841a9155bbfed +/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/decision/host-and-renderer: + en: 135ab5329118eadb + zh: dd5f84ac1358764b +/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/decision/hidden-and-covered-views-return-their-surfaces: + en: 216abcac1e6cd25d + zh: d19600a531086ccb +/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/decision/the-window-budget-follows-physical-memory: + en: 070fdad928fd862d + zh: 85f39b3adccc19c5 +/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/decision/fullscreen-belongs-to-frame-forwarding: + en: 01ca9d01aacc84d6 + zh: 82b7c5cdeedb33e1 +/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/alternatives-considered: + en: 43089e5b5935fe17 + zh: 9534aa449fbdd343 +/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/verification: + en: f9130f0bda61a5d7 + zh: c1bf0f49f6c51908 +/agent-note-frame-forwarding-channels-with-transferable-credentials-producer-local-handles-covered-views-and-a-memory-sized-budget/consequences: + en: d73bd477975a1249 + zh: db4e9d5732c05513 diff --git a/.agents/notes/implemented/architecture/2026-10-18-frame-forwarding-channels.md b/.agents/notes/implemented/architecture/2026-10-18-frame-forwarding-channels.md new file mode 100644 index 0000000000..b278496617 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-18-frame-forwarding-channels.md @@ -0,0 +1,101 @@ +# Agent Note: Frame-forwarding channels with transferable credentials, producer-local handles, covered views, and a memory-sized budget + +Status: implemented + +English | [中文](2026-10-18-frame-forwarding-channels.zh.md) + +## Problem + +A frame-forwarding view authorized one producer process. The Host plugin started the producer, passed it a private endpoint, and called `bind(viewId, pid)`; the receiver accepted only that PID, could not be rebound, and failed the view when the producer disconnected. Replacing a producer therefore meant a new receiver, a new view identifier, and a new renderer consumer: the Office preview's CPU restart rebuilt the whole path, a crashed engine took its view with it, and the parent had to know the child's PID before the child connected. A PID is also a poor authorization identity: the operating system reuses it, it names a process rather than a holder of authority, and a successor process of the same feature cannot inherit it. + +Once any process holding a channel's credential may connect a producer, what such a producer can do to the Host matters. On Windows a producer duplicated each frame's NT handle into the receiver's process and sent the resulting value, and the receiver treated whatever value arrived as a handle of its own. A packet with a forged value therefore made the Host open that handle as a texture or, on an error path, close it, whichever Host object it named. The same scheme also required the producer to hold `PROCESS_DUP_HANDLE` on the Host, which an engine running in a sandbox below the Host's integrity level cannot obtain. + +All channels of the window share one byte budget, granted first come, first served. A producer whose view was hidden stopped rendering but kept its idle pooled surfaces and its pending requests, so a visible view could wait behind a hidden one for budget nobody was using. While one view occupied the screen in a slideshow, the views it covered kept rendering frames nobody could see, and nothing told frame forwarding which channel covered the others. + +The budget was also a fixed 256 MiB, at most 1 GiB, whatever the machine. A channel streaming 4K frames holds up to three 3840×2160 surfaces of 31.64 MiB each, so two such channels filled it, and on the Windows relay path, which also reserves three target textures and two staging textures per channel, a 4096-pixel-wide slideshow frame exceeded the share one allocation may take. + +## Decision + +### Channels and credentials + +A receiver is a logical channel with two halves. The Host plugin calls `frameForwarding.channel()` and receives `{ tx, rx }`: `tx` is an opaque, serializable credential that any process holding a copy may present, and `rx` is the receive identity the renderer passes to `frameForwarding.connect(rx)`. `close(rx)` closes the channel permanently and withdraws the credential, and a channel also closes when the Cordis scope that read the service is disposed. `bind`, `bindProducer`, and the receiver's permanent expected PID no longer exist; the OS-reported peer process is checked per physical connection only for packet origin and handle duplication. The credential never reaches a renderer, a log, or a diagnostic. + +### Connections and handoff + +A channel serves one connection at a time and moves Idle → Active(N) → Draining(N) → Idle → Active(N+1); Closed and Failed are reachable from every state. Connection IDs increase and are never reused; ready carries N, and every later packet is checked against it. While N is connected, other candidates are refused as `channel-busy`, and N is never preempted, even when it stops responding. After N disconnects by goodbye, error, or process exit, N keeps its frames, allocations, budget, relay state, and submitted GPU work until each is released. During that drain one authenticated successor waits for ready within its own deadline and cancellation, and others are refused. Frames and allocations are keyed by connection, delivery IDs stay unique within the channel, credit returns only to the frame's own connection, and a late release of N returns nothing to N+1. GPU work whose completion is unknown keeps its resources and reports `drain-blocked`; no timeout ends a drain. On macOS each connection has its own Mach ports, delivered in ready; on Windows each connection uses its own pipe instance; a failed handshake closes only its candidate. A producer's `close()` completes once its own sender is closed, and the successor's ready completes the handoff. + +### Producers name only their own handles + +The hello capability `producer-local-handles` declares that every handle a producer names belongs to it. On Windows a frame carries a handle value in the producer's process. When a pipe client connects, the receiver opens that process with `PROCESS_DUP_HANDLE | SYNCHRONIZE` from `GetNamedPipeClientProcessId`, and it duplicates each frame's value from there. A value that names no handle of a live producer ends that connection as "sent a handle it does not own" without touching any Host handle; a producer that already exited took its handles with it, and its connection ends as lost. A hello that carries a handle is dropped, and the producer side never interprets a received value. macOS keeps Mach port transfer, where the kernel names the right in the receiver. + +### Compatibility + +Channels change no wire protocol version, constant, packet layout, or endpoint prefix; they add hello capability bits that both sides check. The current wire protocol, version 2, sends each packet as a fixed header followed by only the bytes of its text and requires the same capabilities. The hello declares `transferable-tx` and `producer-local-handles`. Ready carries the connection ID in its token field and, in `ready.stride`, unused before, echoes the capabilities the receiver accepted. A receiver refuses a producer without `transferable-tx` as `transferable-tx-required`, one without `producer-local-handles` as `producer-local-handles-required`, and a producer of another version as `protocol-mismatch`, naming both versions. A producer refuses a ready without a connection ID or without the `producer-local-handles` echo, so neither side of a mixed build sends or reads a handle value under the other rule. Build records (the Kit's `sdk.json`, `receipt.json`, and prebuild manifests, and DSH's `frame-forwarding.json`) list `capabilities: ["transferable-tx", "producer-local-handles"]`, and their loaders and verifiers reject artifacts without both, so a matching version number alone never passes a compatibility check. Desktop [preinstalls the receiver](2026-10-15-desktop-shared-texture-api.md). The Kit 0.2.3 engine is a protocol 1 producer, which the protocol 2 receiver refuses as `protocol-mismatch`. + +### Host and renderer + +The Host keeps the renderer's latest viewport per channel, sends it to each new connection, and presents frames only from the current connection, up to the latest viewport's version. The gate opens before the viewport is sent, because the receiver judges a frame in native code, possibly before the Host's JavaScript handles the acknowledgement that preceded it. A viewport request belongs to the connection that received it and reports `producer-changed` when that connection ends; a timeout fails the request and keeps the channel. Each event-stream subscription starts with a snapshot of every channel's state, then carries states with increasing sequence numbers and producer errors. Frame metadata carries `connectionId` beside `generation`, which remains the viewport version. A `FrameRx` streams the latest frame across producer switches. Frames whose connection state has yet to arrive wait within the channel's frame limit, and the renderer releases frames from earlier connections. Native producers can still use `dsh_frame_forwarding_submit` for ordered delivery or `dsh_frame_forwarding_submit_latest` for replaceable frames. `ready()` resolves once a producer acknowledged the latest viewport. + +On `invalidated`, which [Desktop's settlement](2026-10-15-desktop-shared-texture-api.md) reports when the document, renderer, or GPU process went away first, the bridge queues the notice, then stops the receiver and the frame's connection before releasing the delivery, so its producer never writes that texture again; the forwarder closes the channel as `lost` when it handles the notice. A producer disconnect, by contrast, drains and hands over. + +### Hidden and covered views return their surfaces + +A consumer sends its next viewport version with `visible: false` whenever its view is hidden or covered. The producer SDK's `dsh_frame_forwarding_trim` deallocates every surface that is neither acquired nor submitted: available surfaces, the queued latest frame, granted allocations not yet created, and pending requests; on Windows it then flushes the producer's D3D11 context, because D3D11 destroys a released texture only at the next flush. The Kit engine trims after acknowledging an invisible viewport, so its allocations return to the shared budget, and its next visible frame requests them again. + +### The window budget follows physical memory + +`maxBytes: auto`, the default, resolves to half of physical memory and at least 256 MiB when the first channel opens; no budget exceeds physical memory, and a larger byte count is reduced to it with a Host warning. Sizing waits for the first channel because a Host that never loads the receiver, such as the browser worker deployment, cannot read physical memory. The budget is a ceiling, not a reservation: each channel still holds at most `maxFrames` surfaces, so a larger budget lets more channels hold surfaces at once without enlarging any of them. A producer whose allocation does not fit waits until other channels return surfaces; its channel stays open, and its consumer keeps what it shows and draws a placeholder where content has not arrived. + +### Fullscreen belongs to frame forwarding + +A receive channel shows its consumer's element fullscreen through the document's Fullscreen API with `FrameRx.requestFullscreen(element)`, which the consumer calls before its click handler awaits anything. One channel holds fullscreen at a time. Every other channel learns `{ active: true, holder: false }` and treats its view as covered; the holder learns `active: false` when the fullscreen ends, including on Escape; closing the holding channel or disposing the Client leaves its fullscreen. Desktop exposes no window control of its own ([shared-texture API](2026-10-15-desktop-shared-texture-api.md)). + +Each document view runs its Host operations in arrival order, and different views run concurrently, so a view that waits for frame surfaces delays only its own later operations. A frame that misses `frameTimeoutMs`, or the Kit engine's own report that no frame surface became free, does not fail the view: tiles and page previews request their frame again once the late request settles, a slideshow keeps its stream, and the view keeps its retained tiles, page previews, or last slideshow frame, draws a checkerboard where nothing has arrived, and says that it waits for graphics memory until a frame draws. + +## Alternatives considered + +**Rebind the receiver to a successor's PID.** This keeps the PID as authority, still requires the parent to learn the child's PID before it connects, and needs a new bind call for crash takeover. + +**Preempt a connected producer after a timeout.** A stalled producer may still own GPU work on the channel's textures, so preemption would hand those textures to a successor while they are in use. Only the operating system's disconnect or the producer's own close starts a drain. + +**Connect the successor at once and keep the old connection's frames separately.** Two producers would share one channel's budget and frame limit, and the renderer would interleave their frames. Draining first keeps one producer's resources and credit in flight at a time. + +**Open a new channel per producer, as before.** Every producer switch would replace the renderer's consumer and lose its viewport and stream subscription. + +**Mark channels with a new wire protocol version.** Channels change no packet layout; capability bits that both sides check refuse mixed builds as well, and the frame-forwarding README promises that within a version the wire changes only by such capabilities. + +**Return invalidated textures through a drain.** Desktop cannot observe their remaining references, so a successor could write a texture a stale document still reads; a closed channel is the only state in which releasing them is safe. + +**Validate the received value before use.** The receiver could check that a value names a shared D3D11 texture. That checks the object's type, not its owner: a forged value naming another channel's texture or any other shared object of the Host passes, and error paths still release the value. + +**Keep producer-side duplication and verify it in the receiver.** The receiver cannot tell a value the producer duplicated in from a value it guessed without the producer's handle table, and the producer would still need `PROCESS_DUP_HANDLE` on the Host, which a sandboxed engine lacks. + +**A new wire message that pauses covered producers.** Viewport visibility already tells a producer to stop rendering, carries a version the Host orders, and reaches each new connection through the viewport replay, so a separate pause message would duplicate it. + +**Per-channel byte caps or a channel count limit.** Trimming covered views and closing channels with the scope that opened them handle the observed contention; on the Windows relay path the budget formula would make a low cap block a 4K slideshow. Deferred until a measurement shows the need. + +**Fullscreen the document element and keep the slideshow overlay on `document.body`.** The application chrome would then share the fullscreen screen, including the Windows menu and caption controls that need their own fullscreen handling, and frame forwarding could not name the covering view. + +**Keyboard Lock.** Letting a holder keep Escape suits games, not slideshows, and is deferred until a consumer needs it. + +**Keep a fixed default budget.** 256 MiB held two 4K streams on the shared-texture paths and refused a 4096-pixel-wide frame on the relay path, however much memory the machine had. + +**A quarter of physical memory**, the ceiling Chromium sets for a renderer's tile memory. Half lets more views render at once, which suits using whatever the machine has, and still stays below the working set Metal recommends, about two thirds to four fifths of unified memory. + +**95% or 100% of physical memory.** The operating systems' graphics limits are lower: WDDM lets graphics use `min(80%, max(RAM − 16 GB, 50%))` of system memory, and Metal's recommended working set is the fraction above. The same memory also holds the engines, Chromium, and other applications. Frame forwarding would never refuse first: exhaustion would surface wherever the operating system fails an allocation, for example in Chromium's GPU process, whose exit closes every channel, and nothing would bound the frame memory producers make the Host and the GPU process hold. + +**Fail a view whose frame misses its deadline.** A missing allocation is usually temporary: hiding, covering, or closing another view frees it, while a failed view waits for the user to retry. + +**Run every Office operation in one Host queue.** A view waiting for frame surfaces would hold every other document's operations for the engine's whole wait, and opening one document would stall the others. + +**Tell a budget wait from a stalled engine.** The receiver does not report a pending grant to the Host, and distinguishing that state would require a new producer-to-Host diagnostic; an engine that stops answering still ends at `operationTimeoutMs`. + +**Size the budget from the operating system's GPU budget** (DXGI `QueryVideoMemoryInfo`, Metal `recommendedMaxWorkingSetSize`). It would follow dedicated video memory, which physical memory does not show, but requires platform-specific native queries in the receiver. + +## Verification + +The Kit's transport tests and DSH's [receiver native e2e](../../../../packages/experimental/frame-forwarding/tests/receiver-native.e2e.ts) connect a separate producer process with a copied credential and cover busy refusal, a waiting successor, deadline expiry, crash takeover, IDs reused across connections with late releases, mixed-build refusals in both directions including a producer built without `producer-local-handles` and a ready without the echo, budget return after repeated handoffs, and a trimmed producer's allocation passing to another channel sharing its budget. On Windows the Kit's tests close the connection of a producer that sends a receiver handle's value while that sentinel handle stays valid, and show the trimmed textures' video memory freed through the shared-texture and relay paths; the serialized native suite passes on macOS arm64, two Windows x64 hardware hosts, and Windows ARM64. The [Kit frames e2e](../../../../packages/experimental/frame-forwarding/tests/kit-frames-native.e2e.ts) hands a real Office engine's channel to a replacement and, after a crash, to a successor, renders two engines on two channels at once, and trims an invisible engine's surfaces. Unit specs cover the Host's viewport replay and connection-bound requests, the renderer's snapshot and sequence handling and early-frame ordering, the [wire adapter](../../../../packages/experimental/frame-forwarding/tests/wire.client.spec.ts) and [receive channel](../../../../packages/experimental/frame-forwarding/tests/rx.client.spec.ts) with the single fullscreen holder, coverage events, exits during a pending entry or after Escape, and exits on close and disposal. The [service specs](../../../../packages/experimental/frame-forwarding/tests/service.host.spec.ts) cover `auto` at half of physical memory, its 256 MiB floor, and the refused load of a budget above physical memory. + +## Consequences + +Producer replacement and crash takeover keep the channel, the renderer's consumer, and the viewport, and need no PID: a parent hands over a string. In exchange, every protocol 1 receiver, producer, engine, and build record must be upgraded together, and older builds are refused explicitly: Kit 0.2.2 and earlier producers and receivers cannot interoperate with these sources in either direction, so the Kit, its engines, and Desktop, which compiles the receiver when it packages, upgrade together. A stalled producer that stays connected blocks its channel until it exits or the channel closes, and a successor waits for Desktop and its consumers to release the previous producer's frames. A GPU-process exit closes the channels that had frames on screen, and its consumer must open a new channel instead of continuing on the old one. A producer must keep a sent handle open until the receiver reads the frame, and a producer that exits right after submitting loses that frame with its connection. An engine sandboxed below the Host's integrity level keeps working, since only the Host opens the other process; conversely a producer elevated above the Host, which the Host cannot open, cannot connect, and the receiver closes it during the handshake without a Host diagnostic. A view that becomes visible again waits for an allocation grant before its first frame, and trimming returns frame surfaces only, not an engine's own renderer caches. Escape always leaves fullscreen, and coverage is per document: a fullscreen element of the document covers every receive channel except the holder's. On Windows machines with 32 GB or less, half of physical memory equals the system memory WDDM lets graphics use, so the operating system's limit can be reached there before the budget; a discrete GPU keeps frames in its dedicated memory, which the budget does not see, and WDDM pages rather than fails when that memory runs out. diff --git a/.agents/notes/implemented/architecture/2026-10-18-frame-forwarding-channels.zh.md b/.agents/notes/implemented/architecture/2026-10-18-frame-forwarding-channels.zh.md new file mode 100644 index 0000000000..3891328a77 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-18-frame-forwarding-channels.zh.md @@ -0,0 +1,101 @@ +# Agent Note: 带可转交凭据、生产者自有句柄、被遮挡视图和按内存定额预算的帧转发通道 + +Status: implemented + +[English](2026-10-18-frame-forwarding-channels.md) | 中文 + +## Problem + +帧转发视图只授权一个生产者进程。Host 插件启动生产者,向其传递私有端点,再调用 `bind(viewId, pid)`;接收端只接受该 PID,不能重新绑定,生产者断开时视图随之失败。因此替换生产者意味着新的接收端、新的视图标识和新的渲染端消费者:Office 预览的 CPU 重启要重建整条路径,引擎崩溃会带走其视图,父进程还必须在子进程连接前得知其 PID。PID 也不适合作为授权身份:操作系统会复用 PID,它指代进程而非权限持有者,同一功能的后继进程也无法继承它。 + +一旦任何持有通道凭据的进程都能连接生产者,这样的生产者能对 Host 做什么就变得重要。在 Windows 上,生产者把每帧的 NT 句柄复制进接收端进程并发送复制后的值,接收端则把收到的任何值都当作自身的句柄。因此,带有伪造值的包会让 Host 把该句柄当作纹理打开,或在出错路径上关闭它,无论它指向 Host 中的哪个对象。这一方案还要求生产者持有 Host 的 `PROCESS_DUP_HANDLE` 权限,而在低于 Host 完整性级别的沙箱中运行的引擎拿不到该权限。 + +窗口内所有通道共享一个按先来先得授予的字节预算。视图被隐藏的生产者虽停止渲染,却仍保留其空闲池中的 surface 和尚在申请中的分配,于是可见视图可能排在隐藏视图之后,等待一份无人使用的预算。放映时一个视图占满屏幕,被它遮挡的视图仍在渲染无人可见的帧,帧转发也无从知道是哪个通道遮挡了其他通道。 + +预算还固定为 256 MiB,最多 1 GiB,与机器无关。传输 4K 帧的通道最多持有三个 3840×2160、每个 31.64 MiB 的 surface,两个这样的通道就能占满预算;在 Windows 中继路径上,每个通道还要预留三个目标纹理和两个暂存纹理,一个 4096 像素宽的放映帧超出了单次分配可占的份额。 + +## Decision + +### 通道与凭据 + +接收端是一个由两半组成的逻辑通道。Host 插件调用 `frameForwarding.channel()` 得到 `{ tx, rx }`:`tx` 是不透明、可序列化的凭据,任何持有副本的进程都可出示;`rx` 是接收身份,渲染端将其传给 `frameForwarding.connect(rx)`。`close(rx)` 永久关闭通道并撤回凭据;读取该服务的 Cordis 作用域销毁时,通道也随之关闭。`bind`、`bindProducer` 和接收端永久的预期 PID 已不存在;操作系统报告的对端进程仅按物理连接用于检查数据包来源和句柄复制。凭据从不进入渲染端、日志或诊断信息。 + +### 连接与交接 + +通道同一时间只服务一个连接,状态依次为 Idle → Active(N) → Draining(N) → Idle → Active(N+1);任何状态都可进入 Closed 或 Failed。连接 ID 递增且永不复用;ready 携带 N,之后每个数据包都按其校验。N 在线时,其他候选连接以 `channel-busy` 被拒绝,N 即使停止响应也不会被抢占。N 因 goodbye、错误或进程退出而断开后,其帧、分配、预算、中继状态和已提交的 GPU 工作一直保留到各自释放。排空期间,一个通过认证的后继在自身截止时间和取消条件内等待 ready,其余候选被拒绝。帧和分配按连接区分,交付 ID 在通道内保持唯一,信用只返还给帧所属的连接,N 迟到的释放不会给 N+1 返还任何东西。完成情况未知的 GPU 工作保留其资源并报告 `drain-blocked`;不存在结束排空的超时。macOS 上每个连接拥有自己的 Mach 端口,随 ready 交付;Windows 上每个连接使用独立的管道实例;握手失败只关闭该候选连接。生产者的 `close()` 在本地发送端关闭后完成,后继的 ready 标志交接完成。 + +### 生产者只指名自己的句柄 + +握手能力 `producer-local-handles` 声明生产者指名的每个句柄都归它所有。在 Windows 上,帧携带的是生产者进程中的句柄值。管道客户端连接时,接收端根据 `GetNamedPipeClientProcessId` 以 `PROCESS_DUP_HANDLE | SYNCHRONIZE` 打开该进程,并从那里复制每一帧的值。若值不对应仍在运行的生产者的任何句柄,该连接以“sent a handle it does not own”结束,且不触碰任何 Host 句柄;已退出的生产者带走了自己的句柄,其连接以丢失结束。携带句柄的 hello 会被丢弃,生产者一侧从不解读收到的值。macOS 保留 Mach 端口传递,由内核在接收端中为端口权限命名。 + +### 兼容性 + +通道不改变通信协议的版本、常量、数据包布局或端点前缀,只增加双方都检查的 hello 能力位。当前的通信协议为版本 2,每个数据包由固定的包头加上仅含其文本字节的部分组成,并要求同样的能力。hello 声明 `transferable-tx` 和 `producer-local-handles`。ready 在 token 字段中携带连接 ID,并在此前未使用的 `ready.stride` 中回显接收端接受的能力。接收端以 `transferable-tx-required` 拒绝不带 `transferable-tx` 的生产者,以 `producer-local-handles-required` 拒绝不带 `producer-local-handles` 的生产者,并以写明双方版本的 `protocol-mismatch` 拒绝其他版本的生产者。生产者拒绝不含连接 ID 或未回显 `producer-local-handles` 的 ready,因此混合构建的任一方都不会按另一套规则发送或读取句柄值。构建记录(Kit 的 `sdk.json`、`receipt.json` 和预构建清单,以及 DSH 的 `frame-forwarding.json`)列出 `capabilities: ["transferable-tx", "producer-local-handles"]`,其加载器和校验器拒绝缺少其中任一能力的产物,因此仅版本号相同永远无法通过兼容性检查。Desktop [预装接收器](2026-10-15-desktop-shared-texture-api.zh.md)。Kit 0.2.3 引擎是协议 1 的生产者,协议 2 的接收器以 `protocol-mismatch` 拒绝它。 + +### Host 与渲染端 + +Host 按通道保存渲染端最新的视口,发送给每个新连接,并且只呈现当前连接 generation 不超过最新视口版本的帧。门控在视口发出之前就已打开,因为接收器在原生代码里判定帧,可能早于 Host 的 JavaScript 处理排在该帧之前的确认。视口请求属于接收它的连接,该连接结束时报告 `producer-changed`;超时只让该请求失败,通道保留。每个事件流订阅先收到所有通道状态的快照,随后收到带递增序号的状态和生产者错误。帧元数据在 `generation`(仍为视口版本)旁携带 `connectionId`。`FrameRx` 在生产者切换后继续交付最新帧。连接状态尚未到达的帧在通道帧上限内等待,渲染端释放更早连接的帧。原生生产者仍可通过 `dsh_frame_forwarding_submit` 按序提交帧,或通过 `dsh_frame_forwarding_submit_latest` 提交可替换的帧。`ready()` 在生产者确认最新视口后完成。 + +[Desktop 的结算](2026-10-15-desktop-shared-texture-api.zh.md)在文档、渲染进程或 GPU 进程先行消失时报告 `invalidated`;收到它时,桥先把通知排入队列,再停止接收器和该帧所属的连接,然后释放交付,因此其生产者不会再写入该纹理;forwarder 处理该通知后以 `lost` 关闭通道。相比之下,生产者断开则排空后交接。 + +### 隐藏和被遮挡的视图归还 surface + +视图被隐藏或遮挡时,消费者以下一个视口版本发送 `visible: false`。生产者 SDK 的 `dsh_frame_forwarding_trim` 释放所有既未被获取也未被提交的 surface:可用的 surface、排队中的最新帧、已获批但尚未创建的分配,以及尚在申请中的分配;在 Windows 上它随后刷新生产者的 D3D11 上下文,因为 D3D11 只在下一次刷新时销毁已释放的纹理。Kit 引擎在确认不可见视口后执行收缩,使其分配回到共享预算,下一个可见帧再重新申请。 + +### 窗口预算随物理内存确定 + +默认值 `maxBytes: auto` 在第一个通道打开时解析为物理内存的一半,且不低于 256 MiB;任何预算都不超过物理内存,更大的字节数降为物理内存并在 Host 日志中警告。预算等到第一个通道才确定,因为从不加载接收器的 Host(例如浏览器 worker 部署)读不到物理内存。预算是上限而非预留:每个通道仍最多持有 `maxFrames` 个 surface,因此更大的预算让更多通道能同时持有 surface,而不会让任何一个通道变大。分配放不进预算的 producer 会等待其他通道归还 surface;其通道保持打开,它的消费方保留已显示的内容,并在内容尚未到达处绘制占位。 + +### 全屏归帧转发所有 + +接收通道通过文档的 Fullscreen API,以 `FrameRx.requestFullscreen(element)` 全屏显示其消费者的元素;消费者须在点击处理函数 await 任何东西之前调用它。同一时间只有一个通道持有全屏。其他每个通道收到 `{ active: true, holder: false }`,并将其视图视为被遮挡;全屏结束时(包括按 Escape),持有者收到 `active: false`;关闭持有全屏的通道或销毁 Client 都会退出其全屏。Desktop 自身不暴露任何窗口控制([共享纹理 API](2026-10-15-desktop-shared-texture-api.zh.md))。 + +每个文档视图的 Host 操作按到达顺序执行,不同视图并发执行,因此等待帧 surface 的视图只会推迟它自己后续的操作。错过 `frameTimeoutMs` 的帧,或 Kit 引擎自身报告没有空闲的帧 surface,都不会让视图失败:图块和分页预览在迟到的请求结束后重新请求其帧,放映保留其流;视图保留已保存的图块、分页预览或放映的最后一帧,在尚无内容处绘制棋盘格,并提示正在等待图形内存,直到有帧绘制出来。 + +## Alternatives considered + +**把接收端重新绑定到后继的 PID。** 这仍以 PID 作为权限,父进程仍须在子进程连接前得知其 PID,崩溃接管也需要新的绑定调用。 + +**超时后抢占在线的生产者。** 停滞的生产者可能仍持有作用于通道纹理的 GPU 工作,抢占会在纹理仍被使用时把它们交给后继。只有操作系统的断开或生产者自身的关闭才开始排空。 + +**立即连接后继,并单独保留旧连接的帧。** 两个生产者会共用一个通道的预算和帧上限,渲染端会交错收到双方的帧。先排空保证同一时间只有一个生产者的资源和信用在途。 + +**像以前一样为每个生产者打开新通道。** 每次切换生产者都会替换渲染端的消费者,并丢失其视口和流式订阅。 + +**为通道启用新的通信协议版本。** 通道不改变数据包布局;双方都检查的能力位同样能拒绝混合构建,帧转发 README 也承诺同一版本内的线上协议只通过这类能力演进。 + +**通过排空归还已失效的纹理。** Desktop 无法观察这些纹理剩余的引用,后继可能写入过期文档仍在读取的纹理;只有通道关闭后释放它们才安全。 + +**使用前校验收到的值。** 接收端可以检查该值是否指向共享的 D3D11 纹理。但这只检查对象的类型而非归属:指向另一通道纹理或 Host 中其他共享对象的伪造值仍能通过,出错路径也仍会释放该值。 + +**保留生产者一侧的复制,由接收端验证。** 没有生产者的句柄表,接收端无法区分生产者复制进来的值与猜测的值;生产者也仍需持有 Host 的 `PROCESS_DUP_HANDLE` 权限,而沙箱中的引擎没有该权限。 + +**新增一条暂停被遮挡生产者的线上消息。** 视口的可见性已经告诉生产者停止渲染,携带由 Host 排序的版本,并通过视口重放到达每个新连接,因此单独的暂停消息与之重复。 + +**每通道字节上限或通道数上限。** 收缩被遮挡的视图、通道随打开它的作用域一起关闭,已能处理观察到的争用;在 Windows 中继路径上,预算公式会让较低的上限卡住 4K 放映。等测量证明需要时再做。 + +**让文档根元素全屏,并把放映浮层保留在 `document.body`。** 这样应用界面会一起占用全屏屏幕,其中包括需要另行处理全屏的 Windows 菜单和标题栏按钮,帧转发也无法指明是哪个视图在遮挡。 + +**Keyboard Lock。** 让持有者保留 Escape 适合游戏而不适合放映,等有消费者需要时再做。 + +**保留固定的默认预算。** 无论机器有多少内存,256 MiB 在共享纹理路径上只能容纳两路 4K 流,在中继路径上会拒绝 4096 像素宽的帧。 + +**物理内存的四分之一**,即 Chromium 为渲染进程 tile 内存设的上限。一半能让更多视图同时渲染,契合尽量使用机器已有资源的目标,并且仍低于 Metal 建议的工作集,约为统一内存的三分之二到五分之四。 + +**物理内存的 95% 或 100%。** 操作系统的图形上限更低:WDDM 允许图形使用 `min(80%, max(RAM − 16 GB, 50%))` 的系统内存,Metal 建议的工作集即上述比例。同一份内存还要容纳引擎、Chromium 和其他应用。帧转发将永远不会先拒绝:耗尽会出现在操作系统让分配失败的地方,例如 Chromium 的 GPU 进程,其退出会关闭所有通道;producer 让 Host 和 GPU 进程持有的帧内存也将不受任何约束。 + +**帧错过期限时让视图失败。** 分配不足通常是暂时的:隐藏、遮挡或关闭另一个视图就能释放它,而失败的视图要等用户重试。 + +**让所有 Office 操作走同一个 Host 队列。** 等待帧 surface 的视图会在引擎整个等待期间挡住其他所有文档的操作,打开一个文档也会让其他文档停顿。 + +**区分预算等待与停滞的引擎。** 接收器不会向 Host 报告尚未批准的分配,区分这种状态需要新增一项从生产者到 Host 的诊断;停止响应的引擎仍会在 `operationTimeoutMs` 到期时结束。 + +**按操作系统的 GPU 预算确定预算**(DXGI `QueryVideoMemoryInfo`、Metal `recommendedMaxWorkingSetSize`)。它能跟随物理内存反映不出的独立显存,但需要接收器调用各平台的原生 API 查询 GPU 预算。 + +## Verification + +Kit 的传输测试和 DSH 的[接收器原生 e2e](../../../../packages/experimental/frame-forwarding/tests/receiver-native.e2e.ts) 用复制的凭据连接独立的生产者进程,覆盖忙碌拒绝、等待中的后继、截止时间到期、崩溃接管、跨连接复用 ID 及迟到释放、双向的混合构建拒绝(包括不具备 `producer-local-handles` 的生产者和未回显能力的 ready)、多次交接后的预算归还,以及被收缩的生产者的分配交给共享其预算的另一个通道。在 Windows 上,Kit 的测试会在生产者发送接收端句柄的值时关闭其连接,而该哨兵句柄保持有效,并显示经共享纹理和中继两条路径收缩的纹理释放其显存;串行的原生测试套件在 macOS arm64、两台 Windows x64 硬件主机和 Windows ARM64 上通过。[Kit 帧 e2e](../../../../packages/experimental/frame-forwarding/tests/kit-frames-native.e2e.ts) 把真实 Office 引擎的通道交给替代引擎,并在崩溃后交给后继;它还在两个通道上同时渲染两个引擎,并收缩不可见引擎的 surface。单元测试覆盖 Host 的视口重放和绑定连接的请求、渲染端的快照与序号处理及提前到达帧的排序,以及 [wire 适配](../../../../packages/experimental/frame-forwarding/tests/wire.client.spec.ts)与[接收通道](../../../../packages/experimental/frame-forwarding/tests/rx.client.spec.ts)的唯一全屏持有者、遮挡事件、在进入全屏尚未完成或已按 Escape 后的退出,以及关闭和销毁时的退出。[服务规格测试](../../../../packages/experimental/frame-forwarding/tests/service.host.spec.ts)覆盖 `auto` 取物理内存的一半、其 256 MiB 下限,以及超过物理内存的预算被拒绝加载。 + +## Consequences + +生产者替换和崩溃接管保留通道、渲染端消费者和视口,且无需 PID:父进程只需交出一个字符串。代价是:协议 1 的所有接收端、生产者、引擎和构建记录必须一起升级,旧构建会被明确拒绝:Kit 0.2.2 及更早的生产者和接收端在两个方向上都无法与这些源码互通,因此 Kit、其引擎以及在打包时编译接收器的 Desktop 必须一起升级。保持连接但停滞的生产者会阻塞其通道,直到它退出或通道关闭;后继要等待 Desktop 及其消费者释放前一个生产者的帧。GPU 进程退出会关闭画面上有帧的通道,消费者须打开新通道,而不能继续使用旧通道。生产者必须让已发送的句柄保持打开,直到接收端读取该帧;提交后立即退出的生产者会连同其连接一起丢失这一帧。在低于 Host 完整性级别的沙箱中运行的引擎依然可用,因为只有 Host 打开另一进程;反过来,权限高于 Host 的 producer 无法被 Host 打开,因而无法连接,接收器会在握手时关闭它,且 Host 不记录诊断。重新可见的视图要等到分配获批后才能出第一帧,收缩只归还帧 surface,不归还引擎自身的渲染缓存。Escape 总会退出全屏;遮挡以文档为范围:文档中的全屏元素会遮挡除持有者以外的所有接收通道。在 32 GB 及以下的 Windows 机器上,物理内存的一半等于 WDDM 允许图形使用的系统内存,因此那里可能先达到操作系统的上限而非预算;独立 GPU 把帧放在其独立显存中,预算看不到这部分内存,显存用尽时 WDDM 会换页而不是失败。 diff --git a/apps/desktop-host/src/index.ts b/apps/desktop-host/src/index.ts index dabf5faea8..5e6fea219f 100644 --- a/apps/desktop-host/src/index.ts +++ b/apps/desktop-host/src/index.ts @@ -1,6 +1,7 @@ /** Launch the Desktop profile through the Web application and report its URL to Electron. */ -import { delimiter, join } from 'node:path' +import { delimiter, isAbsolute, join } from 'node:path' +import { parseArgs } from 'node:util' import { randomUUID } from 'node:crypto' import type { PluginOperationRunId } from '@deepseek-ai/dsh-plugin-manager/diagnostic' import { formatFatalDiagnostic } from './fatal-diagnostic.ts' @@ -41,6 +42,13 @@ async function main(): Promise { } const runtimeDir = process.argv[2] as string const projectDir = process.argv[3] as string + const { values, positionals: [pnpm, nodeBin] } = parseArgs({ + args: process.argv.slice(5), + allowPositionals: true, + options: { 'frame-receiver-path': { type: 'string' } }, + }) + const receiverPath = values['frame-receiver-path'] + if (receiverPath !== undefined && !isAbsolute(receiverPath)) throw new Error('--frame-receiver-path must be absolute') // Set before the launch-environment snapshot and profile evaluation; empty means the payload sits beside the runtime directory. process.env.DSH_PRIMARY_RUNTIME = process.argv[4] || join(runtimeDir, '..', 'runtime', 'primary-runtime') const installAnchor = join(runtimeDir, 'node_modules', '@deepseek-ai', 'dsh', 'package.json') @@ -52,14 +60,14 @@ async function main(): Promise { resolvedProfile: { profile, installAnchor }, patchFiles: [], args: ['--no-open', '--host', '127.0.0.1', '--port', '0'], - ...(process.argv[5] === undefined ? {} : { + ...(pnpm === undefined ? {} : { packageManager: { command: process.execPath, - args: ['--expose-internals', process.argv[5]], + args: ['--expose-internals', pnpm], env: { ELECTRON_RUN_AS_NODE: '1', DSH_DESKTOP_NODE_EXECUTABLE: process.execPath, - PATH: `${process.argv[6] ?? ''}${delimiter}${process.env.PATH ?? ''}`, + PATH: `${nodeBin ?? ''}${delimiter}${process.env.PATH ?? ''}`, }, }, }), @@ -154,6 +162,7 @@ async function main(): Promise { installOperationDiagnostics(ctx, record => send({ type: 'plugin-operation', record }), 32, runId) control.updateTasks = installDesktopUpdateTaskControl(ctx) control.quitInspection = installDesktopQuitInspection(ctx) + if (receiverPath !== undefined) ctx.provide('desktopFrameReceiver', { path: receiverPath }) await ctx.plugin(sharedTexture) installPlatformSessionPublisher(ctx, (session) => { if (process.connected) process.send?.({ type: 'platform-session', session }) diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index dacd0de9ae..c385ef13c6 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -27,14 +27,14 @@ en: 19642526da04f108 zh: 506ea427d46bb38f /deepseek-harness-desktop/key-technical-decisions/bundled-workspace-dependencies: - en: c4e360238ae471ec - zh: 747eea646ef0203f + en: 618c74a38432c06c + zh: 5d2514b907e28835 /deepseek-harness-desktop/bundled-command-runtime: en: 372297005b57a08b zh: 074a635ac17e4362 /deepseek-harness-desktop/installation-ownership: - en: 3d3b0e92079a4ef7 - zh: 4ab572bf57f4c55c + en: b9eff63ca25bb96d + zh: 50feb6af9cb8c54d /deepseek-harness-desktop/installation-ownership/runtime-and-plugin-activation: en: 4951cd3ee659eb33 zh: 96bdd6358dad587a diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 75d2d18e83..803ef3945b 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -103,7 +103,7 @@ The macOS PNG uses an inset rounded background for legacy ICNS packaging, with r electron-builder copies only the manifest's `dependencies` into `app.asar/node_modules`, so the Electron main bundle `lib/main.js` inlines its workspace devDependencies and leaves `electron`, Node builtins, and those `dependencies` as its only bare imports; a sandboxed preload may leave only `electron`, `events`, `timers`, and `url`, the modules its `require` polyfill resolves. The main bundle resolves the inlined packages from their `lib/` output, so the root `build:lib:host` bundles `apps/desktop` after the concurrent workspace tsdown pass, and [`desktop-bundle-imports`](scripts/desktop-bundle-imports.mjs) fails any Desktop bundle whose static, dynamic, or `require()` import the packaged application cannot resolve. Without that check an import rolldown could not resolve ships as an external specifier and fails at launch with `ERR_MODULE_NOT_FOUND`. The [archived bundle-order decision](../../.agents/notes/archived/process/2026-09-22-desktop-main-bundle-after-workspace-tsdown.md) records the alternatives. -Desktop's [shared-texture service](../../packages/shared-texture/shared-texture/src/index.ts) accepts an exclusive Host claim and transfers GPU-backed frames to the product main document. On macOS and Windows, a pair of [Node-API addons](native/shared-texture/) opens a native two-way channel between the Host and Main; the Host's IPC channel carries only capability and adapter queries. On macOS the channel carries IOSurfaces; on Windows Main duplicates the Host's NT handle into its own process. A native addon in the Host submits frames through the entry that `nativeSink` returns; each frame's submission, delivery reply, and settlement travel on that channel without passing through the Host's JavaScript event loop, and a refused submission tells whether only that frame was refused or the channel is gone. At most 32 frames wait for Main's JavaScript thread; Main refuses a frame beyond them, and the Host can reuse that frame at once. The Host admits up to 128 unsettled frames; a delivery timeout keeps its slot until settlement. Electron imports each texture and forwards it with the Host's metadata text to the document via `dshDesktop.textures`, whose preload parses the metadata; a frame whose metadata is not JSON, or that arrives while the document has no consumer, is refused before the renderer imports it, and the Host can reuse it once Main releases its own reference. The Host can reuse a frame after the renderer and Main release their references and GPU work completes. Loss of the document, GPU process, or channel invalidates unsettled frames, and the next frame opens a new channel; a `nativeSink` object belongs to one channel. If Electron cannot synchronize a frame's GPU release, that frame is also invalidated. On Windows, Main identifies the adapter of Chromium's compositor itself: it reads the adapter LUID of one compositor texture it exports and releases at once, and reuses that answer until Chromium's GPU process exits, so no probe texture enters the Host. +Desktop's [shared-texture service](../../packages/shared-texture/shared-texture/src/index.ts) accepts an exclusive Host claim from [frame forwarding](../../packages/experimental/frame-forwarding/README.md#security-semantics) and transfers GPU-backed frames to the product main document. On macOS and Windows, a pair of [Node-API addons](native/shared-texture/) opens a native two-way channel between the Host and Main; the Host's IPC channel carries only capability and adapter queries. On macOS the channel carries IOSurfaces; on Windows Main duplicates the Host's NT handle into its own process. A native addon in the Host submits frames through the entry that `nativeSink` returns; each frame's submission, delivery reply, and settlement travel on that channel without passing through the Host's JavaScript event loop, and a refused submission tells whether only that frame was refused or the channel is gone. At most 32 frames wait for Main's JavaScript thread; Main refuses a frame beyond them, and the Host can reuse that frame at once. The Host admits up to 128 unsettled frames; a delivery timeout keeps its slot until settlement. Electron imports each texture and forwards it with the Host's metadata text to the document via `dshDesktop.textures`, whose preload parses the metadata; a frame whose metadata is not JSON, or that arrives while the document has no consumer, is refused before the renderer imports it, and the Host can reuse it once Main releases its own reference. The Host can reuse a frame after the renderer and Main release their references and GPU work completes. Loss of the document, GPU process, or channel invalidates unsettled frames, and the next frame opens a new channel; a `nativeSink` object belongs to one channel. If Electron cannot synchronize a frame's GPU release, that frame is also invalidated. On Windows, Main identifies the adapter of Chromium's compositor itself: it reads the adapter LUID of one compositor texture it exports and releases at once, and reuses that answer until Chromium's GPU process exits, so no probe texture enters the Host. Main passes the absolute path of the preinstalled receiver to Desktop Host with `--frame-receiver-path`. Host plugins read it from `desktopFrameReceiver.path`. The Electron main process declares `@deepseek-ai/dsh-error` as a production dependency to supply the required peer of `@deepseek-ai/dsh-typert-protocol`. The standalone command-management worker at `resources/runtime/cli/command-manager.js` has no adjacent `node_modules`, so its bundle inlines `@deepseek-ai/dsh-atomic-write` and `@deepseek-ai/dsh-error`. @@ -165,7 +165,7 @@ Update copy preserves the complete version, including prerelease suffixes, witho Electron chooses typed shell copy in the eight [shipped Client languages](../../packages/client/locale/README.md) from its application locale and falls back to English. The macOS application bundle declares all eight languages in `CFBundleLocalizations`, allowing macOS to match the initial application language to the user’s preferred languages. Saved Client UI language preferences still take precedence for the main interface. Windows NSIS installer resources live in one JSON file per language under `installer/locales/`; packaging generates NSIS strings and discovers the installer language list from these files. All shipped language resources must have matching keys, format placeholders, and command examples; `pnpm run check:i18n` validates them. The native installer test builds and exercises each configured language. Platform account pages and onboarding artwork use English for languages other than Chinese. On Windows, the main document's language updates desktop menus, recovery and update prompts. The repository Client UI i18n gate checks desktop sources. -Windows and macOS relay native fullscreen transitions and the state after each page load to the renderer, so overlays can adapt their caption clearance. +Windows and macOS relay native fullscreen transitions and the state after each page load to the renderer, so overlays can adapt their caption clearance. The Windows Application and Edit entries stay hidden during fullscreen and return when fullscreen ends. The document enters fullscreen only through the Fullscreen API, which frame forwarding offers to plugins; Electron then makes the window fullscreen, and the same relay applies. Windows uses a 40-DIP caption with native window controls and colors synchronized from the application palette. Localized Application and Edit entries beside the sidebar toggle open native popup menus. They mount only after the application frame publishes its shell overlay seat, and remain absent during startup loading. Application provides About, Settings, Check for Updates, Manage dsh Command, Developer tools, and Exit; Edit provides undo, redo, cut, copy, paste, delete, and select all by sending the corresponding keys to the focused editor, independently of custom shortcut bindings. Plugin management uses the main application's Plugins page. No separate native menu row appears on Alt. Other platforms retain their native menus. Editable fields retain keyboard commands and a context menu without shortcut labels; Chromium supplies command availability, and selected read-only text offers Copy. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index 3f6627c1b9..790643ed8a 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -103,7 +103,7 @@ macOS PNG 使用带留白的圆角底板,供传统 ICNS 打包使用,包含 electron-builder 只把清单中的 `dependencies` 复制进 `app.asar/node_modules`,因此 Electron 主进程 bundle `lib/main.js` 内联其工作区 devDependencies,裸导入只剩 `electron`、Node 内置模块与这些 `dependencies`;沙箱 preload 只能留下 `electron`、`events`、`timers` 与 `url`,即其 `require` polyfill 能解析的模块。主进程 bundle 从被内联包的 `lib/` 产物解析它们,所以根 `build:lib:host` 在并发的工作区 tsdown 阶段之后才为 `apps/desktop` 打 bundle,并由 [`desktop-bundle-imports`](scripts/desktop-bundle-imports.mjs) 让任何静态、动态或 `require()` 导入无法在打包应用内解析的 Desktop bundle 直接失败。没有这项检查时,rolldown 无法解析的导入会作为外部说明符进入产物,并在启动时以 `ERR_MODULE_NOT_FOUND` 失败。[已归档的bundle 顺序决策](../../.agents/notes/archived/process/2026-09-22-desktop-main-bundle-after-workspace-tsdown.md)记录了备选方案。 -Desktop 的[共享纹理服务](../../packages/shared-texture/shared-texture/src/index.ts)供 Host 独占认领,向产品主文档传递 GPU 帧。macOS 与 Windows 都由一对 [Node-API addon](native/shared-texture/) 在 Host 与 Main 之间建立原生双向通道;Host 的 IPC 通道只承载能力查询与适配器查询。macOS 上通道传递 IOSurface;Windows 上由 Main 把 Host 的 NT 句柄复制进自己的进程。Host 中的原生 addon 经 `nativeSink` 返回的入口提交帧;每一帧的提交、交付回执与结算都经这条通道传递,不经过 Host 的 JavaScript 事件循环;提交被拒时,结果会区分只是该帧被拒还是通道已断开。最多 32 帧等待 Main 的 JavaScript 线程处理;超出的帧由 Main 拒绝,Host 可以立即复用该帧。Host 最多接受 128 个尚未结算的帧;交付超时的帧会继续占用名额,直到结算。Electron 导入纹理后将其连同 Host 的元数据文本经 `dshDesktop.textures` 交给文档,由 preload 解析元数据;元数据不是 JSON 的帧,或在文档没有消费者时到达的帧,会在渲染进程导入前被拒绝,Main 释放自己的引用后 Host 即可复用该帧。渲染进程与 Main 均释放引用且 GPU 工作完成后,Host 才能复用该帧。文档、GPU 进程或通道丢失会使尚未结算的帧失效,下一帧会建立新通道;`nativeSink` 对象只属于一条通道。若 Electron 无法同步某帧的 GPU 释放操作,该帧也会失效。Windows 上,Main 自行识别 Chromium 合成器所用的适配器:它导出一张合成器纹理,读取其适配器 LUID 后立即释放,并在 Chromium 的 GPU 进程退出前复用这一结果,因此探测纹理不会进入 Host。 +Desktop 的[共享纹理服务](../../packages/shared-texture/shared-texture/src/index.ts)由 Host 上的[帧转发](../../packages/experimental/frame-forwarding/README.zh.md#security-semantics)独占认领,向产品主文档传递 GPU 帧。macOS 与 Windows 都由一对 [Node-API addon](native/shared-texture/) 在 Host 与 Main 之间建立原生双向通道;Host 的 IPC 通道只承载能力查询与适配器查询。macOS 上通道传递 IOSurface;Windows 上由 Main 把 Host 的 NT 句柄复制进自己的进程。Host 中的原生 addon 经 `nativeSink` 返回的入口提交帧;每一帧的提交、交付回执与结算都经这条通道传递,不经过 Host 的 JavaScript 事件循环;提交被拒时,结果会区分只是该帧被拒还是通道已断开。最多 32 帧等待 Main 的 JavaScript 线程处理;超出的帧由 Main 拒绝,Host 可以立即复用该帧。Host 最多接受 128 个尚未结算的帧;交付超时的帧会继续占用名额,直到结算。Electron 导入纹理后将其连同 Host 的元数据文本经 `dshDesktop.textures` 交给文档,由 preload 解析元数据;元数据不是 JSON 的帧,或在文档没有消费者时到达的帧,会在渲染进程导入前被拒绝,Main 释放自己的引用后 Host 即可复用该帧。渲染进程与 Main 均释放引用且 GPU 工作完成后,Host 才能复用该帧。文档、GPU 进程或通道丢失会使尚未结算的帧失效,下一帧会建立新通道;`nativeSink` 对象只属于一条通道。若 Electron 无法同步某帧的 GPU 释放操作,该帧也会失效。Windows 上,Main 自行识别 Chromium 合成器所用的适配器:它导出一张合成器纹理,读取其适配器 LUID 后立即释放,并在 Chromium 的 GPU 进程退出前复用这一结果,因此探测纹理不会进入 Host。主进程通过 `--frame-receiver-path` 将预装接收器的绝对路径传给 Desktop Host,Host 插件从 `desktopFrameReceiver.path` 读取。 Electron 主进程将 `@deepseek-ai/dsh-error` 声明为生产依赖,满足 `@deepseek-ai/dsh-typert-protocol` 必需的对等依赖(peer dependency)。独立命令管理 worker 位于 `resources/runtime/cli/command-manager.js`,其相邻位置没有 `node_modules`,因此 bundle 内联 `@deepseek-ai/dsh-atomic-write` 和 `@deepseek-ai/dsh-error`。 @@ -165,7 +165,7 @@ Electron 拥有 `$DSH_HOME/profiles/desktop`。其 `dependencies` 包含 pnpm Electron 根据应用语言选择类型化的八种[内置 Client 语言](../../packages/client/locale/README.zh.md)的 shell 文案,并回退到英文。macOS 应用包通过 `CFBundleLocalizations` 声明支持全部八种语言,让 macOS 根据用户的首选语言匹配初始应用语言。主界面仍优先使用已保存的 Client UI 语言偏好。Windows NSIS 安装器在 `installer/locales/` 下按语言保存独立 JSON 资源;打包从这些文件生成 NSIS 文案和安装器语言清单。全部内置语言资源的键、格式占位符和命令示例必须一致,`pnpm run check:i18n` 负责检查。原生安装器测试逐个构建并验证配置中的语言。账户平台页面和引导插图对中文以外的语言使用英文。在 Windows 上,主文档的语言会更新桌面菜单、恢复与更新提示。仓库 Client UI i18n 检查覆盖桌面端源码。 -Windows 和 macOS 会在原生全屏切换及每次页面加载后向渲染器同步全屏状态,让浮层调整顶栏避让距离。 +Windows 和 macOS 会在原生全屏切换及每次页面加载后向渲染器同步全屏状态,让浮层调整顶栏避让距离。Windows 的“应用”和“编辑”入口在全屏期间隐藏,退出全屏后恢复。文档只通过 Fullscreen API 进入全屏,帧转发把它提供给插件;Electron 随后让窗口全屏,同样的状态同步随之生效。 Windows 使用 40 DIP 顶栏,保留原生窗口按钮,颜色随应用调色板同步。侧栏开关旁的本地化“应用”和“编辑”入口打开原生弹出菜单。仅当应用框架发布 shell overlay 席位后才挂载菜单,启动加载期间不显示。“应用”提供关于、设置、检查更新、管理 dsh 命令、开发者工具和退出;“编辑”向当前编辑器发送对应按键,提供撤销、重做、剪切、复制、粘贴、删除和全选,不受自定义快捷键绑定影响。插件管理使用主应用的“插件”页面。按 Alt 不会出现额外的原生菜单行。其他平台保留原生菜单。可编辑区域保留快捷键和不带快捷键标注的右键菜单;命令可用状态由 Chromium 提供,选中的只读文本提供“复制”命令。 diff --git a/apps/desktop/native/shared-texture/scripts/build.ts b/apps/desktop/native/shared-texture/scripts/build.ts index a9d9e2c6c5..370a0b66c8 100644 --- a/apps/desktop/native/shared-texture/scripts/build.ts +++ b/apps/desktop/native/shared-texture/scripts/build.ts @@ -1,12 +1,12 @@ /** * Build Desktop's Node-API 8 shared-texture addons with the target C++ toolchain: clang on macOS, MSVC on Windows. - * `shared-texture-hop.node` (loaded by the Desktop Host) and `shared-texture-ingress.node` (loaded by Electron Main) - * are written with their build records to `apps/desktop/lib/native/-/`. + * The Desktop Host loads frame-forwarding.node and shared-texture-hop.node. Main loads shared-texture-ingress.node. + * All three are written with their build records to `apps/desktop/lib/native/-/`. * Usage: `tsx scripts/build.ts [--arch x64|arm64]`. Headers come from `DSH_NODE_INCLUDE` or Desktop's `node-api-headers`. */ import { spawnSync } from 'node:child_process' import { createHash } from 'node:crypto' -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' @@ -42,8 +42,9 @@ if (include === undefined) throw new Error(`shared-texture: Node-API headers mis type Libraries = Record<'darwin' | 'win32', readonly string[]> /** Compile one addon from its sources and write its build record beside it. */ -function buildAddon(name: string, moduleName: string, sources: readonly string[], libraries: Libraries): void { +function buildAddon(name: string, moduleName: string, sources: readonly string[], libraries: Libraries, record: object = {}): void { const addon = resolve(output, `${name}.node`) + rmSync(resolve(output, `${name}.json`), { force: true }) const defines = ['NAPI_VERSION=8', `NODE_GYP_MODULE_NAME=${moduleName}`] if (process.platform === 'win32') { // Objects, the Node-API import library, and the addon's own import library stay out of the packaged directory. @@ -51,7 +52,7 @@ function buildAddon(name: string, moduleName: string, sources: readonly string[] try { const library = join(scratch, 'node.lib') run('lib.exe', ['/nologo', `/def:${join(headers, 'def', 'node_api.def')}`, '/name:node.exe', `/machine:${arch}`, `/out:${library}`]) - run('cl.exe', ['/nologo', '/LD', '/O2', '/EHsc', '/MD', '/std:c++17', '/W4', `/I${include}`, + run('cl.exe', ['/nologo', '/LD', '/O2', '/EHsc', '/MD', '/std:c++17', '/W4', '/D_WIN32_WINNT=0x0602', `/I${include}`, ...defines.map(define => `/D${define}`), `/Fo${scratch}\\`, ...sources, 'win-delay-load.cc', '/link', '/DELAYLOAD:node.exe', 'delayimp.lib', library, ...libraries.win32, `/IMPLIB:${join(scratch, `${name}.lib`)}`, `/OUT:${addon}`]) } finally { @@ -67,7 +68,7 @@ function buildAddon(name: string, moduleName: string, sources: readonly string[] run('codesign', ['--force', '--sign', '-', addon]) } writeFileSync(resolve(output, `${name}.json`), `${JSON.stringify({ - platform, + platform, ...record, sha256: createHash('sha256').update(readFileSync(addon)).digest('hex'), }, null, 2)}\n`) console.log(`shared-texture: built ${addon}`) @@ -76,3 +77,12 @@ function buildAddon(name: string, moduleName: string, sources: readonly string[] buildAddon('shared-texture-hop', 'dsh_shared_texture_hop', ['hop.cc', `hop-${process.platform}.cc`], { darwin: [], win32: [] }) buildAddon('shared-texture-ingress', 'dsh_shared_texture_ingress', ['ingress.cc', `ingress-${process.platform}.cc`], { darwin: ['-lbsm'], win32: ['bcrypt.lib', 'dxgi.lib'] }) + +const receiver = resolve(root, '../../../../packages/experimental/frame-forwarding/native') +const header = readFileSync(join(receiver, 'transport.h'), 'utf8') +const protocolVersion = Number(/DSH_FRAME_FORWARDING_PROTOCOL_VERSION (\d+)/u.exec(header)?.[1]) +if (!Number.isInteger(protocolVersion)) throw new Error('Missing frame-forwarding protocol version in transport.h') +buildAddon('frame-forwarding', 'dsh_frame_forwarding', ['receiver.cc', 'transport.cc', 'desktop-bridge.cc'].map(file => join(receiver, file)), + { darwin: ['-lbsm'], win32: ['d3d11.lib', 'dxgi.lib', 'advapi32.lib', 'bcrypt.lib'] }, + { protocolVersion, capabilities: ['transferable-tx', 'producer-local-handles'] }) +copyFileSync(join(receiver, 'LICENSE'), join(output, 'frame-forwarding.LICENSE')) diff --git a/apps/desktop/packaging/README.i18n.yaml b/apps/desktop/packaging/README.i18n.yaml index 66df36c48b..2ece5d3869 100644 --- a/apps/desktop/packaging/README.i18n.yaml +++ b/apps/desktop/packaging/README.i18n.yaml @@ -45,8 +45,8 @@ en: b42f103358d0dfd7 zh: a534164ad9eb00da /desktop-packaging/runtime-file-selection-and-installation-checks: - en: 267624bd7a5c4568 - zh: 62908be9e4b9487a + en: 268cb7868641cf6e + zh: ff9a2abcd0370628 /desktop-packaging/desktop-runtime-preparation: en: 84be38ab3136fff7 zh: bb4ed12ee0e1dfa0 diff --git a/apps/desktop/packaging/README.md b/apps/desktop/packaging/README.md index 744941bcca..4730620625 100644 --- a/apps/desktop/packaging/README.md +++ b/apps/desktop/packaging/README.md @@ -254,6 +254,8 @@ The [Electron shell file list](../scripts/electron-builder-config.mjs) excludes The [Office conversion provider](../../../packages/document/office-kit/README.md) is a Host service mounted by web-app, so every application that loads web-app, including `dsh web` and Desktop, provides it together with the [Office tools](../../../packages/document/tool-document/README.md). The provider [resolves the Kit's engine itself](../../../packages/document/office-kit/README.md#understand-the-implementation), including the mapping of native engine manifests to unpacked physical directories. Desktop packaging only carries and unpacks the engine: it carries the target’s declared native engine, and preparation rejects an undeclared or missing target engine before packaging. The complete Office dependencies, including the JavaScript libraries and the selected engine’s executables, data, licenses, and notices, are unpacked under `resources/app.asar.unpacked/dsh/node_modules/`. The Desktop shell passes the primary runtime location to the Host in [main.ts](../src/main.ts), and the Host sets it as `DSH_PRIMARY_RUNTIME`; neither passes a Kit location. Office skills are available in every application that loads web-app, and Desktop reads them from the skill package inside `resources/app.asar`; only Desktop mounts the bundled Python environment (`workspace-dependencies`). On macOS, the native helper receives the JIT entitlement required by [LibreOffice’s UNO bridge](https://github.com/LibreOffice/core/blob/master/sysui/desktop/macosx/hardened_runtime.xcent.in). The Computer Use helper applications under `@deepseek-ai/dsh-cua-macos/native/bin` are also unpacked whole under `resources/app.asar.unpacked/dsh/node_modules/`, and the provider opens that copy. +On macOS and Windows, Desktop packages `frame-forwarding.node` and its build record alongside the shared-texture addons. Frame forwarding loads the preinstalled receiver on demand, including when installed through Plugin Manager. + The packaged application runs compiled JavaScript and pre-generated Typert metadata; it does not compile TypeScript plugins. Source-level debugger navigation and editor declarations remain available in development packages. [Copy-policy tests](../tests/runtime-file-policy.spec.ts) cover exclusions and retained assets; The [payload smoke](../tests/fixtures/runtime-payload-smoke.mjs) runs under Electron RunAsNode before the Host smoke and final inventory verification. The payload smoke resolves the search tool’s ripgrep executable and verifies text search and file enumeration. Signed Windows builds run these checks after dependency signing; other builds run them during `prepare:dsh`. The [Host smoke](../scripts/smoke-runtime.ts) creates DOCX, XLSX, and PPTX inputs with bundled Python and runs each through the real Office provider: PDF conversion, PNG rendering, conversion to the matching OpenDocument format, and, for XLSX, recalculation, checking each output's signature. Every assembled application, including directory and unsigned builds, repeats the payload and Host checks against ASAR. Archive integrity checks compare the complete archived descriptor with preparation, file bytes and membership in both archive and unpacked trees, recorded executable flags for archived files, and physical permissions for unpacked files. Conversion failures stop packaging before a release record is written; macOS DMG/ZIP builds run these checks before notarization. Windows release qualification also runs [directory and replacement checks](../scripts/smoke-windows.ps1) manually after the Desktop build. Set `$Makensis`, `$SevenZip`, and `$PluginDir` to the pinned builder’s NSIS compiler, 7-Zip executable, and x86-unicode NSIS plugin directory; pass the prepared `window-frame.dll` as `-FrameLibrary` to exercise the native extraction path and its failure report as well. From the repository root, run the command below. It verifies directory replacement and rollback, and both locked-file replacement modes; it is not part of the unit-test lane. diff --git a/apps/desktop/packaging/README.zh.md b/apps/desktop/packaging/README.zh.md index e52be505fb..2b552e22d1 100644 --- a/apps/desktop/packaging/README.zh.md +++ b/apps/desktop/packaging/README.zh.md @@ -254,6 +254,8 @@ Desktop 在本地打包工作区包,并通过目标捆绑的 Node 和 pnpm 安 [Office 转换提供方](../../../packages/document/office-kit/README.zh.md)是 web-app 挂载的 Host 服务,因此所有加载 web-app 的应用(包括 `dsh web` 和 Desktop)都提供它以及 [Office 工具](../../../packages/document/tool-document/README.zh.md)。该提供方[自行解析 Kit 的引擎](../../../packages/document/office-kit/README.zh.md#understand-the-implementation),包括把原生引擎清单映射到解包后的实体目录。Desktop 打包只负责携带和解包引擎:携带目标声明的原生引擎;目标引擎未声明或缺失时,准备阶段在打包前拒绝。完整的 Office 依赖(包括 JavaScript 库以及所选引擎的可执行文件、数据、许可证和声明)解包到 `resources/app.asar.unpacked/dsh/node_modules/` 下。Desktop 壳在 [main.ts](../src/main.ts) 中把主运行时位置传给 Host,由 Host 设为 `DSH_PRIMARY_RUNTIME`;两者都不传 Kit 位置。所有加载 web-app 的应用都提供 Office 技能,Desktop 从 `resources/app.asar` 内的技能包读取它们;只有 Desktop 挂载内置 Python 环境(`workspace-dependencies`)。在 macOS 上,原生 helper 获得 [LibreOffice UNO 桥](https://github.com/LibreOffice/core/blob/master/sysui/desktop/macosx/hardened_runtime.xcent.in)所需的 JIT 权限。`@deepseek-ai/dsh-cua-macos/native/bin` 下的 Computer Use helper 应用也整体解包到 `resources/app.asar.unpacked/dsh/node_modules/` 下,提供方打开该副本。 +Desktop 在 macOS 和 Windows 上将 `frame-forwarding.node` 及其构建记录随共享纹理模块一同打包。帧转发插件按需加载预装接收器,通过 Plugin Manager 安装时也无需原生构建。 + 打包应用运行编译后的 JavaScript 和预生成的 Typert 元数据,不编译 TypeScript 插件。源码级调试导航和编辑器声明仍可从开发包中获取。[复制规则测试](../tests/runtime-file-policy.spec.ts)覆盖排除项和保留资源;[产物 smoke](../tests/fixtures/runtime-payload-smoke.mjs) 在 Host smoke 和最终清单验证之前,使用 Electron RunAsNode 执行。产物 smoke 解析搜索工具使用的 ripgrep 可执行文件,并验证文本搜索和文件枚举。Windows 签名构建在依赖签名后运行这些检查;其他构建在 `prepare:dsh` 中运行。[Host smoke](../scripts/smoke-runtime.ts) 使用捆绑的 Python 创建 DOCX、XLSX 和 PPTX 输入,并通过真实 Office 提供方逐一执行:PDF 转换、PNG 渲染、转换为对应的 OpenDocument 格式,以及针对 XLSX 的重算,检查每个输出的签名。每个组装后的应用(包括目录包和未签名构建)都会针对 ASAR 重复产物和 Host 检查。归档完整性检查将归档内完整描述符与准备结果比对,并核对归档和解包目录中的文件内容与清单、归档内文件记录的执行标志,以及解包文件的物理权限。转换失败会在写入发布记录前终止打包;macOS DMG/ZIP 构建在公证前执行这些检查。 Windows 发布验收还需在 Desktop 构建后手动运行[目录和替换检查](../scripts/smoke-windows.ps1)。将 `$Makensis`、`$SevenZip` 和 `$PluginDir` 分别设为锁定版本构建器的 NSIS 编译器、7-Zip 可执行文件和 x86-unicode NSIS 插件目录;通过 `-FrameLibrary` 传入已准备好的 `window-frame.dll`,即可同时覆盖原生解压路径及其失败报告。从仓库根目录运行以下命令。它验证 目录替换与回滚和两种文件占用替换方式;不属于单元测试通道。 diff --git a/apps/desktop/scripts/dev.ts b/apps/desktop/scripts/dev.ts index 5923607304..78af29372d 100644 --- a/apps/desktop/scripts/dev.ts +++ b/apps/desktop/scripts/dev.ts @@ -1,7 +1,7 @@ /** Build and launch the unpackaged Electron shell against the current workspace. */ import { spawn, execFileSync } from 'node:child_process' -import { existsSync, readFileSync } from 'node:fs' +import { existsSync, readdirSync, readFileSync } from 'node:fs' import { createRequire } from 'node:module' import { join, resolve } from 'node:path' import { parseArgs } from 'node:util' @@ -11,6 +11,7 @@ import { developmentRuntimeDirectory, resolveDesktopBuildTarget } from './deskto import { prepareDevelopmentProject } from './development-project.ts' import { prepareDevelopmentApp } from './development-app.ts' import { prepareDevelopmentState } from './development-state.ts' +import { buildNativePackage, nativeBuildEnvironment, nativePackageBuildAt, type NativePackageBuild } from './native-package-builds.mjs' import { preparePrimaryRuntime } from './prepare-primary-runtime.ts' const APP_ROOT = resolve(import.meta.dirname, '..') @@ -49,6 +50,15 @@ async function run(command: string, args: readonly string[], cwd: string, enviro }) } +/** Workspace packages declaring `dsh.native`; development loads them in place, so they build in their own directories. */ +function workspaceNativePackages(): NativePackageBuild[] { + const packages = join(REPOSITORY_ROOT, 'packages') + return readdirSync(packages, { withFileTypes: true }).filter(group => group.isDirectory()) + .flatMap(group => readdirSync(join(packages, group.name), { withFileTypes: true }).filter(entry => entry.isDirectory()) + .map(entry => nativePackageBuildAt(join(packages, group.name, entry.name)))) + .filter(declaration => declaration !== undefined) +} + async function runPackageScript(script: string, cwd: string): Promise { const packageManager = process.env.npm_execpath if (packageManager === undefined || packageManager === '') { @@ -99,6 +109,12 @@ async function main(): Promise { if (process.platform === 'darwin' || process.platform === 'win32') await runPackageScript('build:native', APP_ROOT).catch((error: unknown) => { console.warn(`desktop development: shared-texture addons not built: ${error instanceof Error ? error.message : String(error)}`) }) + // Packaging's build environment: on Windows, the MSVC developer environment for this architecture. + for (const declaration of workspaceNativePackages()) { + try { buildNativePackage(declaration, process.arch, nativeBuildEnvironment(process.arch)) } catch (error) { + console.warn(`desktop development: ${declaration.name} native addon not built: ${error instanceof Error ? error.message : String(error)}`) + } + } } for (const path of [ join(APP_ROOT, 'lib', 'main.js'), diff --git a/apps/desktop/scripts/electron-builder-config.mjs b/apps/desktop/scripts/electron-builder-config.mjs index 1e9f021389..3478a30167 100644 --- a/apps/desktop/scripts/electron-builder-config.mjs +++ b/apps/desktop/scripts/electron-builder-config.mjs @@ -77,7 +77,8 @@ export function createElectronBuilderConfig( let primaryRuntimeDestination let dshDestination let windowsCode = [] - const unpack = ['**/*.{node,dylib,dll,so,exe}', '**/*.so.*', '**/spawn-helper', '**/@vscode/ripgrep-*/bin/rg', + const receiverBase = `lib/native/${resolvedPlatform}-${resolvedArch}/frame-forwarding` + const unpack = [`${receiverBase}.json`, '**/*.{node,dylib,dll,so,exe}', '**/*.so.*', '**/spawn-helper', '**/@vscode/ripgrep-*/bin/rg', `**/node_modules/@deepseek-ai/libreoffice-kit-${resolvedPlatform}-${resolvedArch}/**/*`, // LaunchServices opens the Computer Use helper as an application, so every file of its bundles stays on disk. // Both architectures ship: they form one notarized payload whose manifest staging verifies as a whole. @@ -151,6 +152,8 @@ export function createElectronBuilderConfig( 'lib/preload-update-dialog.cjs', 'lib/preload-welcome.cjs', ...sharedTextureAddonNames(resolvedPlatform).map(name => `lib/native/${resolvedPlatform}-${resolvedArch}/${name}.node`), + ...(sharedTextureAddonNames(resolvedPlatform).includes('frame-forwarding') ? [`${receiverBase}.json`, `${receiverBase}.LICENSE`] : []), + 'native/shared-texture/win-delay-load.LICENSE', 'renderer/**/*', 'package.json', '!node_modules/**/*.{js,cjs,mjs,ts,cts,mts,css}.map', diff --git a/apps/desktop/scripts/native-package-builds.d.mts b/apps/desktop/scripts/native-package-builds.d.mts index 810622c3e5..f734f612e3 100644 --- a/apps/desktop/scripts/native-package-builds.d.mts +++ b/apps/desktop/scripts/native-package-builds.d.mts @@ -1,9 +1,21 @@ -/** Native addon build support for Desktop packaging: target build environment and object-file architecture checks. */ +/** Build and verify native addons that runtime packages compile from shipped sources under `package.json` `dsh.native`, with the target build environment and object-file architecture checks. */ +/** One package's validated `dsh.native` declaration. */ +export interface NativePackageBuild { name: string; root: string; build: string; addons: string[] } /** Check the object header against the requested platform and CPU. */ export function matchingArchitecture(bytes: Buffer, target: { platform: string; arch: string }): boolean +/** The validated `dsh.native` declaration of one package directory, or undefined when it declares none or is not a DeepSeek Harness package. */ +export function nativePackageBuildAt(root: string): NativePackageBuild | undefined +/** Every installed package under a runtime root that declares `dsh.native`, including nested `node_modules`. */ +export function nativePackageBuilds(runtimeRoot: string): NativePackageBuild[] /** The `vcvarsall.bat` argument that targets `arch` from a `host` build machine. */ export function vcvarsallTarget(host: string, arch: string): string /** Read the environment `set` printed after the build environment marker; throws when the marker is missing. */ export function parseDeveloperEnvironment(output: string): Record /** The build environment for a target: on Windows the MSVC developer environment; always with `DSH_NODE_API_HEADERS`. */ export function nativeBuildEnvironment(arch: string, environment?: NodeJS.ProcessEnv): NodeJS.ProcessEnv +/** Run one package's declared build for a target architecture; throws when it fails. */ +export function buildNativePackage(declaration: Pick, arch: string, environment?: NodeJS.ProcessEnv): void +/** Build every declared addon in the runtime for a target architecture and return the built package names. */ +export function buildNativePackages(runtimeRoot: string, arch: string): string[] +/** Require every declared addon of the target, its build record, its hash, and its architecture. */ +export function verifyNativePackages(runtimeRoot: string, target: { platform: string; arch: string }): void diff --git a/apps/desktop/scripts/native-package-builds.mjs b/apps/desktop/scripts/native-package-builds.mjs index 6c091b36d8..c6b225eaed 100644 --- a/apps/desktop/scripts/native-package-builds.mjs +++ b/apps/desktop/scripts/native-package-builds.mjs @@ -1,14 +1,25 @@ /** - * Native addon build support for Desktop packaging: the build environment for a target (on Windows, the MSVC - * developer environment `vcvarsall.bat` sets up, with `DSH_NODE_API_HEADERS` naming Desktop's `node-api-headers` - * package: `include/` headers and `def/` Windows symbol lists) and object-file architecture checks. + * Build and verify native addons that runtime packages compile from shipped sources. A DeepSeek Harness package + * (`@deepseek-ai/dsh-*`) opts in with `package.json` `dsh.native`; packaging ignores the declaration in any other + * package, so no third-party build script runs. `build` names a Node script, relative to the package root, that the + * packager runs on the target operating system as `node --arch `, on Windows inside the MSVC developer + * environment `vcvarsall.bat` sets up for the target, with `DSH_NODE_API_HEADERS` naming the root of Desktop's + * `node-api-headers` package (`include/` headers, `def/` Windows symbol lists); `addons` lists the produced files relative to the package root, + * with `{platform}` and `{arch}` expanded to the target. The build writes a record beside each addon, the addon path + * with `.node` replaced by `.json`, holding at least `{ platform, sha256 }`. Packaging owns presence, record, hash, and + * architecture checks; each package owns any further compatibility check its loader performs. */ import { spawnSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import { existsSync, readdirSync, readFileSync } from 'node:fs' import { createRequire } from 'node:module' import { dirname, join } from 'node:path' +/** Only packages with this name prefix may declare `dsh.native`. */ +const NATIVE_PACKAGE_PREFIX = '@deepseek-ai/dsh-' /** Separates `vcvarsall.bat` output from the environment it leaves. */ const ENVIRONMENT_MARKER = '--- dsh native build environment ---' + /** * Whether an addon's object header matches the packaged operating system and CPU. * @param {Buffer} bytes - Addon file contents. @@ -28,6 +39,64 @@ export function matchingArchitecture(bytes, target) { return false } +/** + * Validate one package's `dsh.native` declaration. + * @param {string} name - Package name for diagnostics. + * @param {unknown} value - Raw `dsh.native` value. + * @returns {{ build: string, addons: string[] }} The declaration. + */ +function nativeDeclaration(name, value) { + const declaration = /** @type {{ build?: unknown, addons?: unknown }} */ (value) + const relativePath = path => typeof path === 'string' && path !== '' && !path.startsWith('/') && !path.split('/').includes('..') + if (typeof value !== 'object' || value === null || !relativePath(declaration.build) + || !Array.isArray(declaration.addons) || declaration.addons.length === 0 + || !declaration.addons.every(addon => relativePath(addon) && addon.endsWith('.node'))) { + throw new Error(`desktop runtime: ${name} declares an invalid dsh.native; expected { build, addons: [".node", ...] }`) + } + return { build: /** @type {string} */ (declaration.build), addons: /** @type {string[]} */ (declaration.addons) } +} + +/** + * Read the `dsh.native` declaration of one package directory. + * @param {string} root - Package directory containing `package.json`. + * @returns {{ name: string, root: string, build: string, addons: string[] } | undefined} The declaration, or undefined when + * the package declares none or is not a DeepSeek Harness package. + */ +export function nativePackageBuildAt(root) { + const manifestPath = join(root, 'package.json') + if (!existsSync(manifestPath)) return undefined + const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) + if (manifest.dsh?.native === undefined || typeof manifest.name !== 'string' || !manifest.name.startsWith(NATIVE_PACKAGE_PREFIX)) return undefined + return { name: manifest.name, root, ...nativeDeclaration(manifest.name, manifest.dsh.native) } +} + +/** + * Installed packages under a runtime root that declare `dsh.native`, including nested `node_modules`. + * @param {string} runtimeRoot - Desktop runtime root containing `node_modules`. + * @returns {{ name: string, root: string, build: string, addons: string[] }[]} Declarations in directory order. + */ +export function nativePackageBuilds(runtimeRoot) { + const found = [] + /** @param {string} modules */ + const visit = (modules) => { + if (!existsSync(modules)) return + for (const entry of readdirSync(modules, { withFileTypes: true })) { + if (!entry.isDirectory() || entry.name.startsWith('.')) continue + const directories = entry.name.startsWith('@') + ? readdirSync(join(modules, entry.name), { withFileTypes: true }).filter(child => child.isDirectory()) + .map(child => join(modules, entry.name, child.name)) + : [join(modules, entry.name)] + for (const root of directories) { + const declaration = nativePackageBuildAt(root) + if (declaration !== undefined) found.push(declaration) + visit(join(root, 'node_modules')) + } + } + } + visit(join(runtimeRoot, 'node_modules')) + return found +} + /** * The `vcvarsall.bat` argument that targets `arch` from this build host. * @param {string} host - Build host architecture. @@ -93,3 +162,63 @@ function toolchainEnvironment(arch, environment) { if (result.status !== 0) throw new Error(`desktop native build: vcvarsall.bat ${target} failed (${String(result.status)}): ${result.stdout}`) return parseDeveloperEnvironment(result.stdout) } + +/** + * Run one package's declared build for a target architecture on the host toolchain. + * @param {{ name: string, root: string, build: string }} declaration - Package declaration. + * @param {string} arch - Target architecture. + * @param {NodeJS.ProcessEnv} environment - Build environment from {@link nativeBuildEnvironment}. + * @returns {void} + */ +export function buildNativePackage(declaration, arch, environment = process.env) { + const result = spawnSync(process.execPath, [join(declaration.root, declaration.build), '--arch', arch], { cwd: declaration.root, env: environment, stdio: 'inherit' }) + if (result.error) throw result.error + if (result.status !== 0) throw new Error(`desktop runtime: ${declaration.name} native build failed (${String(result.status)})`) +} + +/** + * Expand one declared addon path for a target. + * @param {string} addon - Declared path with `{platform}` and `{arch}` placeholders. + * @param {{ platform: string, arch: string }} target - Electron execution target. + * @returns {string} Target-specific relative path. + */ +function targetPath(addon, target) { + return addon.replaceAll('{platform}', target.platform).replaceAll('{arch}', target.arch) +} + +/** + * Compile every declared native addon in the runtime for the packaged target with the host toolchain. + * @param {string} runtimeRoot - Desktop runtime root containing `node_modules`. + * @param {string} arch - Target architecture. + * @returns {string[]} Names of the packages whose builds ran. + */ +export function buildNativePackages(runtimeRoot, arch) { + const declarations = nativePackageBuilds(runtimeRoot) + if (declarations.length === 0) return [] + const environment = nativeBuildEnvironment(arch) + for (const declaration of declarations) buildNativePackage(declaration, arch, environment) + return declarations.map(declaration => declaration.name) +} + +/** + * Require every declared addon of the target, its build record, its hash, and its architecture. + * @param {string} runtimeRoot - Desktop runtime root containing `node_modules`. + * @param {{ platform: string, arch: string }} target - Electron execution target. + * @returns {void} + */ +export function verifyNativePackages(runtimeRoot, target) { + const name = `${target.platform}-${target.arch}` + for (const declaration of nativePackageBuilds(runtimeRoot)) { + for (const declared of declaration.addons) { + const addon = join(declaration.root, targetPath(declared, target)) + if (!existsSync(addon)) throw new Error(`desktop runtime: ${addon} is missing; prepare:dsh builds ${declaration.name} for the target`) + const bytes = readFileSync(addon) + const recordPath = addon.replace(/\.node$/u, '.json') + const record = existsSync(recordPath) ? JSON.parse(readFileSync(recordPath, 'utf8')) : undefined + if (record?.platform !== name || record.sha256 !== createHash('sha256').update(bytes).digest('hex')) { + throw new Error(`desktop runtime: ${addon} differs from its build record`) + } + if (!['x64', 'arm64'].includes(target.arch) || !matchingArchitecture(bytes, target)) throw new Error(`desktop runtime: ${addon} is not ${name}`) + } + } +} diff --git a/apps/desktop/scripts/prepare-dsh.ts b/apps/desktop/scripts/prepare-dsh.ts index a069888036..be3c10816d 100644 --- a/apps/desktop/scripts/prepare-dsh.ts +++ b/apps/desktop/scripts/prepare-dsh.ts @@ -33,6 +33,7 @@ import { signMacOSRuntime, } from './macos-runtime.ts' import { desktopTargetPlatform, resolveDesktopBuildTarget, resolveDesktopTargetBuildPaths } from './desktop-build-paths.mjs' +import { buildNativePackages, verifyNativePackages } from './native-package-builds.mjs' import { desktopRuntimeFileExclusion } from './runtime-file-policy.ts' import { selectOfficeEngine } from '../../../scripts/libreoffice-packages.mjs' @@ -163,6 +164,12 @@ async function main(): Promise { if (!existsSync(join(DSH_OUTPUT_ROOT, 'node_modules', '@deepseek-ai', `libreoffice-kit-${officeEngine}`, 'prebuilds.json'))) { throw new Error(`desktop runtime: missing required LibreOffice engine ${officeEngine}`) } + // Declared native addons are compiled and checked against their build records before macOS signing rewrites them; + // the runtime descriptor seals the signed files. + await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:native-packages', async () => { + buildNativePackages(DSH_OUTPUT_ROOT, target.arch) + verifyNativePackages(DSH_OUTPUT_ROOT, target) + }) if (process.platform === 'darwin' && process.env.DSH_DESKTOP_UNSIGNED !== '1') { const cacheDirectory = resolveMacOSSignatureCacheDirectory(process.env, BUILD_PATHS.root) await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'sign:dsh-native', () => signMacOSRuntime(DSH_OUTPUT_ROOT, resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env), target.arch, cacheDirectory)) diff --git a/apps/desktop/scripts/verify-shared-texture.mjs b/apps/desktop/scripts/verify-shared-texture.mjs index c3005bb5e4..fce7ec6b73 100644 --- a/apps/desktop/scripts/verify-shared-texture.mjs +++ b/apps/desktop/scripts/verify-shared-texture.mjs @@ -1,4 +1,4 @@ -/** Verify Desktop's shared-texture hop and ingress addons on macOS and Windows. */ +/** Verify Desktop's frame receiver and shared-texture addons on macOS and Windows. */ import { createHash } from 'node:crypto' import { existsSync } from 'node:fs' import { readFile } from 'node:fs/promises' @@ -11,7 +11,7 @@ import { matchingArchitecture } from './native-package-builds.mjs' * @returns {readonly string[]} Addon basenames without `.node`; empty on unsupported platforms. */ export function sharedTextureAddonNames(platform) { - return platform === 'darwin' || platform === 'win32' ? ['shared-texture-hop', 'shared-texture-ingress'] : [] + return platform === 'darwin' || platform === 'win32' ? ['shared-texture-hop', 'shared-texture-ingress', 'frame-forwarding'] : [] } async function verifyAddon(directory, name, target) { diff --git a/apps/desktop/src/host-process.ts b/apps/desktop/src/host-process.ts index d464eb946f..3c48e55548 100644 --- a/apps/desktop/src/host-process.ts +++ b/apps/desktop/src/host-process.ts @@ -242,9 +242,10 @@ export class DesktopHostProcess { /** * Start this child once and await its Web application URL. + * @param frameReceiverPath - Absolute path of the Desktop-preinstalled receiver, when available. * @returns Ready facts supplied by the child after application startup. */ - async start(): Promise { + async start(frameReceiverPath?: string): Promise { if (this.child !== undefined) return this.readyPromise const entry = join(this.runtimeDir, 'node_modules', '@deepseek-ai', 'dsh-desktop-host', 'lib', 'index.js') const child = spawn(this.node, [ @@ -256,6 +257,7 @@ export class DesktopHostProcess { // Empty asks the Host for the payload beside its runtime directory, so that layout has one owner. this.primaryRuntime ?? '', ...this.packageManager === undefined ? [] : [this.packageManager.pnpm, this.packageManager.nodeBin], + ...(frameReceiverPath === undefined ? [] : ['--frame-receiver-path', frameReceiverPath]), ], { cwd: this.projectDir, env: desktopNodeEnvironment(this.node, undefined, this.environment), diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index f2e2cfefd6..ea96645c64 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -539,6 +539,8 @@ async function main(): Promise { const platformView = new DesktopPlatformView(join(app.getAppPath(), 'lib', 'preload-platform-account.cjs'), () => locale.id === 'zh-CN' ? 'zh_CN' : 'en_US', process.platform === 'win32' ? 'win32' : 'darwin', owner => isMandatory() || updateOverlays.input(owner).blocked) + const nativeRoot = development ? app.getAppPath() : join(process.resourcesPath, 'app.asar.unpacked') + const frameReceiverPath = join(nativeRoot, 'lib', 'native', `${process.platform}-${process.arch}`, 'frame-forwarding.node') const backend = new DesktopBackendController((onFailure) => { const hostInspectPort = developmentHostInspectPort(development) const host = new DesktopHostProcess(resources.node, resources.dsh, activeProject, @@ -555,7 +557,7 @@ async function main(): Promise { }, [textures.channel]) return { start: async () => { - const ready = await host.start() + const ready = await host.start(frameReceiverPath) const cookie = ready.authenticationCookie hostCookie = cookie hostUrl = ready.url diff --git a/apps/desktop/src/preload-menu.ts b/apps/desktop/src/preload-menu.ts index f7b881278a..f0d68d4586 100644 --- a/apps/desktop/src/preload-menu.ts +++ b/apps/desktop/src/preload-menu.ts @@ -16,6 +16,7 @@ export function installWindowsMenu(): { update(): void; dispose(): void } { :host { position: fixed; top: 0; left: var(--dsh-windows-menu-start, 48px); z-index: 1100; height: var(--dsh-windows-titlebar-height); display: flex; align-items: center; font-family: var(--dsw-font-family); -webkit-app-region: no-drag; } + :host-context(html[data-fullscreen]) { display: none; } [role=menubar] { display: flex; gap: 2px; } button { height: 28px; padding: 0 10px; border: 0; border-radius: 6px; background: transparent; color: var(--dsw-alias-label-secondary); diff --git a/apps/desktop/tests/dev.spec.ts b/apps/desktop/tests/dev.spec.ts index 1d27c6bb91..f922165e14 100644 --- a/apps/desktop/tests/dev.spec.ts +++ b/apps/desktop/tests/dev.spec.ts @@ -19,12 +19,16 @@ vi.mock('node:child_process', async (importOriginal) => { vi.mock('node:fs', async importOriginal => ({ ...await importOriginal(), existsSync: vi.fn(() => true), + readdirSync: vi.fn(() => []), readFileSync: vi.fn(() => JSON.stringify({ version: '1.0.0' })), })) vi.mock('node:module', () => ({ createRequire: () => () => 'fixture-electron' })) vi.mock('../scripts/development-app.ts', () => ({ prepareDevelopmentApp: vi.fn(() => 'fixture-macos-launcher') })) vi.mock('../scripts/development-project.ts', () => ({ prepareDevelopmentProject: vi.fn() })) vi.mock('../scripts/prepare-primary-runtime.ts', () => ({ preparePrimaryRuntime: vi.fn(async () => {}) })) +vi.mock('../scripts/native-package-builds.mjs', () => ({ + buildNativePackage: vi.fn(), nativeBuildEnvironment: vi.fn(), nativePackageBuildAt: vi.fn(), +})) afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); vi.clearAllMocks(); state.nativeStatus = 0 }) @@ -55,7 +59,7 @@ async function develop(platform: 'darwin' | 'win32', skipBuild = false) { it.each(['darwin', 'win32'] as const)('builds the native addons before launching the %s development runtime', async (platform) => { const { calls } = await develop(platform) - expect(calls.slice(0, 3).map(call => call[1])).toEqual([ + expect(calls.slice(0, -1).map(call => call[1])).toEqual([ ['fixture-pnpm.cjs', 'run', 'build:artifacts'], ['fixture-pnpm.cjs', 'run', 'build'], ['fixture-pnpm.cjs', 'run', 'build:native'], diff --git a/apps/desktop/tests/fixtures/workspace-update-adapters.mjs b/apps/desktop/tests/fixtures/workspace-update-adapters.mjs index 995eb6e753..e9928872e3 100644 --- a/apps/desktop/tests/fixtures/workspace-update-adapters.mjs +++ b/apps/desktop/tests/fixtures/workspace-update-adapters.mjs @@ -22,9 +22,9 @@ export class DesktopHostProcess extends Host { super(node, runtime, project, 0, environment, onFailure, primaryRuntime, packageManager) fixture.host = this } - async start() { + async start(frameReceiverPath) { try { - const result = await super.start() + const result = await super.start(frameReceiverPath) fixture.readyHosts.add(this) fixture.ready.resolve(result.url) return result diff --git a/apps/desktop/tests/frame-forwarding/fixtures/backlog-producer.cc b/apps/desktop/tests/frame-forwarding/fixtures/backlog-producer.cc new file mode 100644 index 0000000000..8cc808c7b2 --- /dev/null +++ b/apps/desktop/tests/frame-forwarding/fixtures/backlog-producer.cc @@ -0,0 +1,163 @@ +// Producer for the receiver's pending-event tests: floods control messages, submits frames, or presents a wrong +// credential repeatedly. +// +// backlog-producer produce [key=value ...] +// messages=N control messages {"seq":i,"pad":"x..."} of about length=L bytes (defaults 0 and 64) +// wait-go=1 poll until the receiver sends "go" before sending +// frames=N then submit N 64x64 frames, each once credit and an allocation are available; gives up after 5 s +// frames-first=1 submit the frames right after connecting, before waiting for "go" +// after=A "hold" polls up to hold-ms=MS (default 10000) and reports whether the receiver ended the +// connection, answers "ping" and leaves on "exit"; "goodbye" closes at once; "crash" terminates +// retry-busy=1 retry a connection refused as channel-busy every 10 ms for up to 20 s +// backlog-producer refuse [count=N] [max-ms=MS] +// Connect with the caller-corrupted credential until N attempts were refused for it (0: no limit) or MS elapsed. +// +// Every observation is one stdout line, `
`. With signal=PREFIX, each word also +// creates the empty file PREFIX., so a test whose JavaScript thread is blocked can still observe progress. +#include "fixture-client.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(_WIN32) +#include +#include +#endif + +static const auto started = std::chrono::steady_clock::now(); +static std::map options; +static long long elapsed() { + return std::chrono::duration_cast(std::chrono::steady_clock::now() - started).count(); +} +static long option(const char* key, long fallback) { + const auto found = options.find(key); + return found == options.end() ? fallback : std::atol(found->second.c_str()); +} +static void say(const char* word, const std::string& details = {}) { + std::printf("%lld %s %s\n", elapsed(), word, details.c_str()); + std::fflush(stdout); + const auto signal = options.find("signal"); + if (signal != options.end()) std::ofstream(signal->second + "." + word, std::ios::binary); +} +[[noreturn]] static void crash() { +#if defined(_WIN32) + TerminateProcess(GetCurrentProcess(), 9); +#endif + std::abort(); +} + +static int refuse(const std::string& tx, dsh_frame_forwarding_connect_options& connect) { + const long target = option("count", 1), max_ms = option("max-ms", 20000); +#if defined(_WIN32) + // One device for every attempt, so each attempt costs only the pipe handshake. + ID3D11Device* device = nullptr; + if (FAILED(D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, D3D11_CREATE_DEVICE_BGRA_SUPPORT, nullptr, 0, + D3D11_SDK_VERSION, &device, nullptr, nullptr))) { say("device-failed"); return 6; } + connect.device = device; +#endif + char error[512] = {}; + long credential = 0, other = 0, accepted = 0; + std::string other_text; + while ((target == 0 || credential < target) && elapsed() < max_ms) { + auto client = dsh_frame_forwarding_connect_with_options(tx.c_str(), &connect, error, sizeof(error)); + if (client) { ++accepted; dsh_frame_forwarding_close(client); } + else if (std::strstr(error, "credential was rejected")) { if (++credential == 1) say("refusing"); } + else { ++other; other_text = error; } + } + say("refused", "credential=" + std::to_string(credential) + " other=" + std::to_string(other) + " accepted=" + + std::to_string(accepted) + " other_text=" + other_text); + return 0; +} + +static int produce(const std::string& tx, dsh_frame_forwarding_connect_options& connect) { + const long messages = option("messages", 0), length = option("length", 64), hold_ms = option("hold-ms", 10000); + const long frames = option("frames", 0); + const bool wait_go = option("wait-go", 0) != 0, retry_busy = option("retry-busy", 0) != 0; + const bool frames_first = option("frames-first", 0) != 0; + const std::string after = options.count("after") ? options["after"] : "goodbye"; + char error[512] = {}; + dsh_frame_forwarding_client* client = nullptr; + long busy = 0; + for (;;) { + client = dsh_frame_forwarding_connect_with_options(tx.c_str(), &connect, error, sizeof(error)); + if (client || !retry_busy || std::strncmp(error, "channel-busy", 12) != 0 || elapsed() > 20000) break; + ++busy; + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + if (!client) { say("connect-failed", error); return 3; } + say("connected", "busy=" + std::to_string(busy)); + auto event = std::make_unique(); + const auto submit_frames = [&] { + std::vector pixels(64 * 64, 0xff3366cc); + long submitted = 0; + std::string failure; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (submitted < frames && failure.empty() && std::chrono::steady_clock::now() < deadline) { + if (auto surface = dsh_frame_forwarding_acquire(client, 64, 64)) { + if (!dsh_frame_forwarding_write_bgra(surface, pixels.data(), 64 * 4) || + !dsh_frame_forwarding_submit(client, surface, static_cast(submitted + 1), "{}")) failure = "submit"; + else ++submitted; + continue; + } + const int kind = dsh_frame_forwarding_poll(client, 20, event.get()); + if (kind < 0) failure = std::string("closed:") + event->text; + } + say("frames", "submitted=" + std::to_string(submitted) + " failure=" + failure); + }; + if (frames > 0 && frames_first) submit_frames(); + if (wait_go) { + bool go = false; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(20); + while (!go && std::chrono::steady_clock::now() < deadline) { + const int kind = dsh_frame_forwarding_poll(client, 100, event.get()); + if (kind < 0) { say("closed-before-go", event->text); dsh_frame_forwarding_close(client); return 4; } + if (kind == 1 && std::strcmp(event->text, "go") == 0) go = true; + } + if (!go) { say("go-timeout"); dsh_frame_forwarding_close(client); return 5; } + say("go"); + } + long sent = 0, failed = 0; + for (long index = 0; index < messages; ++index) { + std::string json = "{\"seq\":" + std::to_string(index) + ",\"pad\":\""; + const long pad = length - static_cast(json.size()) - 2; + if (pad > 0) json.append(static_cast(pad), 'x'); + json += "\"}"; + if (dsh_frame_forwarding_send(client, json.c_str())) ++sent; else ++failed; + } + say("sent", "ok=" + std::to_string(sent) + " failed=" + std::to_string(failed)); + if (frames > 0 && !frames_first) submit_frames(); + if (after == "crash") { say("crashing"); crash(); } + if (after == "goodbye") { dsh_frame_forwarding_close(client); say("goodbye"); return 0; } + const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(hold_ms); + while (std::chrono::steady_clock::now() < deadline) { + const int kind = dsh_frame_forwarding_poll(client, 100, event.get()); + if (kind < 0) { say("closed", event->text); dsh_frame_forwarding_close(client); return 0; } + if (kind == 1 && std::strcmp(event->text, "exit") == 0) { say("exit-request"); dsh_frame_forwarding_close(client); say("goodbye"); return 0; } + if (kind == 1 && std::strcmp(event->text, "ping") == 0) dsh_frame_forwarding_send(client, "{\"pong\":1}"); + } + say("hold-timeout"); + dsh_frame_forwarding_close(client); + return 0; +} + +int main(int argc, char** argv) { + if (argc < 3) return 2; + for (int index = 3; index < argc; ++index) { + const std::string argument = argv[index]; + const auto equals = argument.find('='); + if (equals == std::string::npos) return 2; + options[argument.substr(0, equals)] = argument.substr(equals + 1); + } + const std::string tx = argv[1], mode = argv[2]; + dsh_frame_forwarding_connect_options connect{}; + connect.timeout_ms = 10000; + if (mode == "refuse") return refuse(tx, connect); + if (mode == "produce") return produce(tx, connect); + return 2; +} diff --git a/apps/desktop/tests/frame-forwarding/fixtures/fake-sink.cc b/apps/desktop/tests/frame-forwarding/fixtures/fake-sink.cc new file mode 100644 index 0000000000..30fa07d920 --- /dev/null +++ b/apps/desktop/tests/frame-forwarding/fixtures/fake-sink.cc @@ -0,0 +1,264 @@ +/** + * Test-only Node-API addon standing in for Desktop's `shared-texture-hop.node` sink: it implements the + * `dsh_shared_texture_sink_v2` ABI of Desktop's `shared-texture-sink.h`, records each presentation under an identifier + * of its own (its position among accepted presentations, from "1"), and lets the test answer each one with a delivery + * and a settlement from a native thread, refuse the next presentation with a chosen result, answer presentations inside + * `present`, and read the sink's reference counts. On Windows it also names the default hardware adapter the way the + * receiver does. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "shared-texture-sink.h" +#if defined(_WIN32) +#define NOMINMAX +#include +#include +#endif + +namespace { + +struct Presented { + std::string id, metadata; + uintptr_t handle = 0; + uint32_t width = 0, height = 0, timeout_ms = 0; + uint8_t pixel_format = 0; + dsh_shared_texture_callbacks_v2 callbacks{}; +}; + +struct FakeSink { + dsh_shared_texture_sink_v2 sink{}; + std::atomic refs{1}, retains{0}, releases{0}; + std::mutex mutex; + std::vector presented; + /** Requests that have not settled, by identifier. */ + std::map pending; + std::string refuse; + /** Result of the refused presentation: 1 rejects only that frame, 2 reports a lost connection. */ + int refuse_code = 1; + bool inline_answer = false; +}; + +napi_value fail(napi_env env, const char* text) { napi_throw_error(env, nullptr, text); return nullptr; } +napi_value undefined(napi_env env) { napi_value value; napi_get_undefined(env, &value); return value; } +napi_value number(napi_env env, double value) { napi_value result; napi_create_double(env, value, &result); return result; } +napi_value text(napi_env env, const std::string& value) { napi_value result; napi_create_string_utf8(env, value.data(), value.size(), &result); return result; } +void property(napi_env env, napi_value object, const char* name, napi_value value) { napi_set_named_property(env, object, name, value); } +std::string string_of(napi_env env, napi_value value) { + size_t length = 0; + napi_get_value_string_utf8(env, value, nullptr, 0, &length); + std::string result(length, '\0'); + napi_get_value_string_utf8(env, value, &result[0], length + 1, &length); + return result; +} +FakeSink* fake_of(napi_env env, napi_value value) { + void* data = nullptr; + napi_get_value_external(env, value, &data); + return static_cast(data); +} + +void retain(void* ctx) { + auto fake = static_cast(ctx); + fake->retains++; fake->refs++; +} +void release(void* ctx) { + auto fake = static_cast(ctx); + fake->releases++; fake->refs--; +} +int present(void* ctx, const dsh_shared_texture_frame_v2* frame, const dsh_shared_texture_callbacks_v2* callbacks, char* err_buf, size_t err_cap) { + auto fake = static_cast(ctx); + Presented entry; + if (frame->metadata_len) entry.metadata.assign(frame->metadata_json, frame->metadata_len); + entry.handle = frame->handle; entry.width = frame->width; entry.height = frame->height; + entry.timeout_ms = frame->timeout_ms; entry.pixel_format = frame->pixel_format; entry.callbacks = *callbacks; + bool inline_answer; + { + std::lock_guard lock(fake->mutex); + if (!fake->refuse.empty()) { + std::snprintf(err_buf, err_cap, "%s", fake->refuse.c_str()); + fake->refuse.clear(); + return fake->refuse_code; + } + entry.id = std::to_string(fake->presented.size() + 1); + fake->presented.push_back(entry); + inline_answer = fake->inline_answer; + if (!inline_answer) fake->pending.emplace(entry.id, *callbacks); + } + // Desktop's hop may answer on the presenting thread before `present` returns. + if (inline_answer) { + callbacks->on_delivered(callbacks->user_data, nullptr); + callbacks->on_settled(callbacks->user_data, 0); + } + return 0; +} + +/** `create({ magic?, version? })`: `{ sink, native }`; `sink` owns one reference, as Desktop's external does. */ +napi_value create(napi_env env, napi_callback_info info) { + napi_value arg; size_t count = 1; + napi_get_cb_info(env, info, &count, &arg, nullptr, nullptr); + auto fake = new FakeSink; + fake->sink = {DSH_SHARED_TEXTURE_SINK_MAGIC, DSH_SHARED_TEXTURE_SINK_VERSION, fake, retain, release, present}; + if (count == 1) { + napi_valuetype type; napi_typeof(env, arg, &type); + if (type == napi_object) { + bool has = false; napi_value value; uint32_t field = 0; + if (napi_has_named_property(env, arg, "magic", &has) == napi_ok && has) { + napi_get_named_property(env, arg, "magic", &value); napi_get_value_uint32(env, value, &field); fake->sink.magic = field; + } + if (napi_has_named_property(env, arg, "version", &has) == napi_ok && has) { + napi_get_named_property(env, arg, "version", &value); napi_get_value_uint32(env, value, &field); fake->sink.version = field; + } + } + } + napi_value result, sink, native; + // The test process ends before the fake would be freed; its callbacks stay valid for late settlements. + napi_create_external(env, &fake->sink, [](napi_env, void* data, void*) { + auto sink = static_cast(data); + sink->release(sink->ctx); + }, nullptr, &sink); + napi_create_external(env, fake, nullptr, nullptr, &native); + napi_create_object(env, &result); + property(env, result, "sink", sink); + property(env, result, "native", native); + return result; +} + +/** `presented(native)`: every accepted presentation in order, each with the identifier the fake assigned it. */ +napi_value presented(napi_env env, napi_callback_info info) { + napi_value arg; size_t count = 1; + napi_get_cb_info(env, info, &count, &arg, nullptr, nullptr); + auto fake = fake_of(env, arg); + std::lock_guard lock(fake->mutex); + napi_value result; + napi_create_array_with_length(env, fake->presented.size(), &result); + for (size_t index = 0; index < fake->presented.size(); ++index) { + const auto& entry = fake->presented[index]; + napi_value object, handle; + napi_create_object(env, &object); + property(env, object, "id", text(env, entry.id)); + property(env, object, "metadata", text(env, entry.metadata)); + uint64_t raw = entry.handle; + napi_create_buffer_copy(env, sizeof(raw), &raw, nullptr, &handle); + property(env, object, "handle", handle); + property(env, object, "width", number(env, entry.width)); + property(env, object, "height", number(env, entry.height)); + property(env, object, "timeoutMs", number(env, entry.timeout_ms)); + property(env, object, "pixelFormat", number(env, entry.pixel_format)); + napi_set_element(env, result, static_cast(index), object); + } + return result; +} + +/** `answer(native, id, kind, value)`: `delivered` with an error string or null, or `settled` with `invalidated`. */ +napi_value answer(napi_env env, napi_callback_info info) { + napi_value args[4]; size_t count = 4; + napi_get_cb_info(env, info, &count, args, nullptr, nullptr); + auto fake = fake_of(env, args[0]); + const auto id = string_of(env, args[1]), kind = string_of(env, args[2]); + dsh_shared_texture_callbacks_v2 callbacks; + { + std::lock_guard lock(fake->mutex); + const auto found = fake->pending.find(id); + if (found == fake->pending.end()) return fail(env, "No unsettled presentation has this identifier"); + callbacks = found->second; + if (kind == "settled") fake->pending.erase(found); + } + napi_valuetype type; napi_typeof(env, args[3], &type); + std::string error; + bool flag = false; + if (kind == "delivered" && type == napi_string) error = string_of(env, args[3]); + if (kind == "settled") napi_get_value_bool(env, args[3], &flag); + const bool failed = kind == "delivered" && type == napi_string; + // The hop's reader thread runs every callback. + std::thread([&] { + if (kind == "delivered") callbacks.on_delivered(callbacks.user_data, failed ? error.c_str() : nullptr); + else callbacks.on_settled(callbacks.user_data, flag ? 1 : 0); + }).join(); + return undefined(env); +} + +/** `refuseNext(native, reason, code = 1)`: the next presentation returns `code` with `reason`. */ +napi_value refuse_next(napi_env env, napi_callback_info info) { + napi_value args[3]; size_t count = 3; + napi_get_cb_info(env, info, &count, args, nullptr, nullptr); + auto fake = fake_of(env, args[0]); + int32_t code = 1; + if (count == 3) napi_get_value_int32(env, args[2], &code); + std::lock_guard lock(fake->mutex); + fake->refuse = string_of(env, args[1]); + fake->refuse_code = code; + return undefined(env); +} + +/** `answerInline(native, enabled)`: answer later presentations with a delivery and a release inside `present`. */ +napi_value answer_inline(napi_env env, napi_callback_info info) { + napi_value args[2]; size_t count = 2; + napi_get_cb_info(env, info, &count, args, nullptr, nullptr); + auto fake = fake_of(env, args[0]); + bool enabled = false; + napi_get_value_bool(env, args[1], &enabled); + std::lock_guard lock(fake->mutex); + fake->inline_answer = enabled; + return undefined(env); +} + +/** `references(native)`: `{ refs, retains, releases }`. */ +napi_value references(napi_env env, napi_callback_info info) { + napi_value arg; size_t count = 1; + napi_get_cb_info(env, info, &count, &arg, nullptr, nullptr); + auto fake = fake_of(env, arg); + napi_value result; + napi_create_object(env, &result); + property(env, result, "refs", number(env, fake->refs)); + property(env, result, "retains", number(env, fake->retains)); + property(env, result, "releases", number(env, fake->releases)); + return result; +} + +/** `defaultAdapter()`: the adapter of a default hardware D3D11 device as the receiver names it; null outside Windows or without one. */ +napi_value default_adapter(napi_env env, napi_callback_info) { + napi_value result; + napi_get_null(env, &result); +#if defined(_WIN32) + ID3D11Device* device = nullptr; + if (FAILED(D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, D3D11_CREATE_DEVICE_BGRA_SUPPORT, nullptr, 0, + D3D11_SDK_VERSION, &device, nullptr, nullptr))) return result; + IDXGIDevice* dxgi = nullptr; IDXGIAdapter* adapter = nullptr; DXGI_ADAPTER_DESC desc{}; + if (SUCCEEDED(device->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast(&dxgi))) && SUCCEEDED(dxgi->GetAdapter(&adapter)) + && SUCCEEDED(adapter->GetDesc(&desc))) { + std::ostringstream id; + id << std::hex << static_cast(desc.AdapterLuid.HighPart) << ':' << desc.AdapterLuid.LowPart; + result = text(env, id.str()); + } + if (adapter) adapter->Release(); + if (dxgi) dxgi->Release(); + device->Release(); +#endif + return result; +} + +napi_value initialize(napi_env env, napi_value exports) { + const napi_property_descriptor methods[] = { + {"create", nullptr, create, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"presented", nullptr, presented, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"answer", nullptr, answer, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"refuseNext", nullptr, refuse_next, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"answerInline", nullptr, answer_inline, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"references", nullptr, references, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"defaultAdapter", nullptr, default_adapter, nullptr, nullptr, nullptr, napi_default, nullptr}, + }; + napi_define_properties(env, exports, sizeof(methods) / sizeof(methods[0]), methods); + return exports; +} + +} // namespace +NAPI_MODULE(NODE_GYP_MODULE_NAME, initialize) diff --git a/apps/desktop/tests/frame-forwarding/fixtures/fixture-client.cc b/apps/desktop/tests/frame-forwarding/fixtures/fixture-client.cc new file mode 100644 index 0000000000..16a659b779 --- /dev/null +++ b/apps/desktop/tests/frame-forwarding/fixtures/fixture-client.cc @@ -0,0 +1,309 @@ +#include "transport.h" +#include "fixture-client.h" +#include +#include +#include +#include +#include +#if defined(__APPLE__) +#include +#include +#include +#else +#define NOMINMAX +#include +#include +#include +#include +using Microsoft::WRL::ComPtr; +#endif +using namespace dsh_frame_forwarding; +struct dsh_frame_forwarding_surface { + uint32_t width = 0, height = 0, stride = 0; + uint64_t bytes = 0, frame_id = 0, allocation_id = 0; + enum { pending, granted, available, acquired, submitted } state = pending; + dsh_frame_forwarding_client* owner = nullptr; +#if defined(__APPLE__) + IOSurfaceRef surface = nullptr; + ~dsh_frame_forwarding_surface() { if (surface) CFRelease(surface); } +#else + ComPtr texture; + ComPtr keyed_mutex; + HANDLE handle = nullptr; + ~dsh_frame_forwarding_surface() { if (handle) CloseHandle(handle); } +#endif +}; +struct dsh_frame_forwarding_client { + std::unique_ptr channel; + std::mutex pool_mutex; + std::vector> surfaces; + uint32_t max_frames = 0; + uint64_t max_bytes = 0, next_allocation = 1; + std::string error; + std::atomic stopped{false}; +#if defined(_WIN32) + ComPtr device; + ComPtr context; +#endif +}; +namespace { +/** Send a complete surface, while the caller holds pool_mutex. */ +bool send_frame(dsh_frame_forwarding_client* client, dsh_frame_forwarding_surface* surface, uint64_t frame_id, const char* metadata_json) { + Packet packet; packet.kind = frame; + if (!metadata_json || std::strlen(metadata_json) >= sizeof(packet.text)) return false; + std::strcpy(packet.text, metadata_json); + packet.width = surface->width; packet.height = surface->height; packet.stride = surface->stride; + packet.frame_id = frame_id; packet.allocation_id = surface->allocation_id; +#if defined(__APPLE__) + auto resource = reinterpret_cast(surface->surface); +#else + auto resource = reinterpret_cast(surface->handle); +#endif + if (!client->channel->send(packet, resource)) return false; + surface->frame_id = frame_id; surface->state = dsh_frame_forwarding_surface::submitted; return true; +} +void copy_error(char* output, size_t size, const char* message) { + if (output && size) { std::strncpy(output, message, size - 1); output[size - 1] = 0; } +} +/** + * Return every surface that is neither acquired nor submitted to the receiver; the caller holds pool_mutex. + * @returns Whether every deallocation was sent. + */ +bool release_idle(dsh_frame_forwarding_client* client) { + bool sent = true; + client->surfaces.erase(std::remove_if(client->surfaces.begin(), client->surfaces.end(), [&](auto& surface) { + if (surface->state == dsh_frame_forwarding_surface::acquired || surface->state == dsh_frame_forwarding_surface::submitted) return false; + Packet packet; packet.kind = deallocate; packet.allocation_id = surface->allocation_id; + sent = client->channel->send(packet) && sent; return true; + }), client->surfaces.end()); + return sent; +} +bool set_text(Packet& packet, const char* text) { + if (!text || std::strlen(text) >= sizeof(packet.text)) return false; + std::strcpy(packet.text, text); return true; +} +/** Diagnostic for a receiver's refusal; "channel-busy" names a channel whose producer is still connected or draining. */ +std::string refusal(const Packet& packet) { + const std::string reason(packet.text, strnlen(packet.text, sizeof(packet.text))); + if (reason == reject_busy) return "channel-busy: the frame-forwarding channel already has a producer or a waiting successor"; + if (reason == reject_capability) return "Frame-forwarding receiver requires a transferable TX producer"; + if (reason == reject_local_handles) return "Frame-forwarding receiver requires a producer that names only its own handles"; + if (reason == reject_credential) return "Frame-forwarding TX credential was rejected"; + if (reason == reject_closed) return "Frame-forwarding channel is closed"; + if (reason.rfind(reject_protocol, 0) == 0) return "Frame-forwarding " + reason; + return "Frame-forwarding receiver rejected handshake"; +} +#if defined(__APPLE__) +void set_number(CFMutableDictionaryRef dictionary, CFStringRef key, int64_t value) { + auto number = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &value); + CFDictionarySetValue(dictionary, key, number); CFRelease(number); +} +#endif +} +static dsh_frame_forwarding_client* connect_impl(const char* endpoint_text, void* device, + const dsh_frame_forwarding_connect_options* options, char* error, size_t error_size) { + try { + if (!endpoint_text) throw std::runtime_error("Missing frame-forwarding TX credential"); + auto endpoint = parse_endpoint(endpoint_text); + auto client = std::make_unique(); + const auto started = std::chrono::steady_clock::now(); + const auto cancelled = [&] { + return options && ((options->cancelled && options->cancelled(options->cancellation_context)) || + std::chrono::steady_clock::now() - started >= std::chrono::milliseconds(options->timeout_ms)); + }; + client->channel = connect_channel(endpoint, options ? std::function(cancelled) : std::function{}); + Packet packet; packet.kind = hello; std::strcpy(packet.token, endpoint.token.c_str()); +#if defined(_WIN32) + if (device) { + client->device = static_cast(device); + client->device->GetImmediateContext(&client->context); + } else if (FAILED(D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, D3D11_CREATE_DEVICE_BGRA_SUPPORT, + nullptr, 0, D3D11_SDK_VERSION, &client->device, nullptr, &client->context))) + throw std::runtime_error("D3D11 hardware device unavailable"); + set_text(packet, device_adapter(client->device.Get()).c_str()); + packet.max_frames = hello_keyed_mutex | hello_transferable | hello_producer_local_handles; +#else + if (device) throw std::runtime_error("IOSurface producer does not accept a graphics device"); + packet.max_frames = hello_transferable | hello_producer_local_handles; +#endif + if (!client->channel->send(packet)) throw std::runtime_error("Cannot send frame-forwarding handshake"); + Received received; + int result; + do { + if (cancelled()) throw std::runtime_error("Frame-forwarding connection cancelled or timed out"); + result = client->channel->receive(received, 100); + } while (result == 0); + const auto& reply = received.packet; + if (result < 0 || reply.marker != magic || reply.version != DSH_FRAME_FORWARDING_PROTOCOL_VERSION) + throw std::runtime_error("Frame-forwarding receiver rejected handshake"); + if (reply.kind == goodbye) throw std::runtime_error(refusal(reply)); + const auto connection = parse_connection(reply.token); + if (reply.kind != ready || !reply.max_frames || !reply.max_bytes) throw std::runtime_error("Frame-forwarding receiver rejected handshake"); + // A receiver that predates transferable channels answers without a connection identifier. + if (!connection) throw std::runtime_error("Frame-forwarding receiver does not support transferable TX credentials"); + // A receiver that does not echo the capability would read this producer's handle values as handles of its own. + if (!(reply.stride & hello_producer_local_handles)) throw std::runtime_error("Frame-forwarding receiver does not accept producer-local handles"); + client->channel->bind_connection(connection); + client->max_frames = reply.max_frames; client->max_bytes = reply.max_bytes; + return client.release(); + } catch (const std::exception& exception) { copy_error(error, error_size, exception.what()); return nullptr; } +} +dsh_frame_forwarding_client* dsh_frame_forwarding_connect(const char* endpoint, char* error, size_t error_size) { + return connect_impl(endpoint, nullptr, nullptr, error, error_size); +} +dsh_frame_forwarding_client* dsh_frame_forwarding_connect_with_options(const char* endpoint, + const dsh_frame_forwarding_connect_options* options, char* error, size_t error_size) { + if (!options || !options->timeout_ms) { copy_error(error, error_size, "Connection requires a positive timeout"); return nullptr; } + return connect_impl(endpoint, options->device, options, error, error_size); +} +dsh_frame_forwarding_surface* dsh_frame_forwarding_acquire(dsh_frame_forwarding_client* client, uint32_t width, uint32_t height) { + if (!client || client->stopped) return nullptr; + std::lock_guard lock(client->pool_mutex); + if (!width || !height || width > 16384 || height > 16384) { client->error = "Frame-forwarding dimensions outside supported range"; return nullptr; } + dsh_frame_forwarding_surface *granted_surface = nullptr; + bool allocation_pending = false; + for (auto& surface : client->surfaces) { + if (surface->width != width || surface->height != height) continue; + if (surface->state == dsh_frame_forwarding_surface::available) { + surface->state = dsh_frame_forwarding_surface::acquired; return surface.get(); + } + if (surface->state == dsh_frame_forwarding_surface::pending) allocation_pending = true; + if (surface->state == dsh_frame_forwarding_surface::granted && !granted_surface) granted_surface = surface.get(); + } + if (!granted_surface && allocation_pending) return nullptr; + if (!granted_surface) { + release_idle(client); + uint64_t allocated_bytes = 0; + for (auto& surface : client->surfaces) allocated_bytes += surface->bytes; +#if defined(__APPLE__) + auto row_bytes = IOSurfaceAlignProperty(kIOSurfaceBytesPerRow, static_cast(width) * 4); + uint64_t required_bytes = IOSurfaceAlignProperty(kIOSurfaceAllocSize, row_bytes * height); + const uint64_t page_bytes = static_cast(getpagesize()); + required_bytes = (required_bytes + page_bytes - 1) / page_bytes * page_bytes; +#else + uint64_t required_bytes = static_cast(width) * height * 4; +#endif + if (required_bytes > client->max_bytes) { client->error = "Frame-forwarding texture exceeds view byte budget"; return nullptr; } + if (client->surfaces.size() >= client->max_frames || allocated_bytes + required_bytes > client->max_bytes) return nullptr; + auto pending_surface = std::make_unique(); + pending_surface->width = width; pending_surface->height = height; pending_surface->owner = client; + pending_surface->bytes = required_bytes; pending_surface->allocation_id = client->next_allocation++; + Packet request; request.kind = allocate; request.allocation_id = pending_surface->allocation_id; request.max_bytes = required_bytes; + if (!client->channel->send(request)) { client->error = "Frame-forwarding allocation channel closed"; return nullptr; } + client->surfaces.push_back(std::move(pending_surface)); return nullptr; + } + auto surface = granted_surface; +#if defined(__APPLE__) + auto properties = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + set_number(properties, kIOSurfaceWidth, width); set_number(properties, kIOSurfaceHeight, height); + set_number(properties, kIOSurfaceAllocSize, surface->bytes); + set_number(properties, kIOSurfaceBytesPerElement, 4); set_number(properties, kIOSurfacePixelFormat, 0x42475241); + surface->surface = IOSurfaceCreate(properties); CFRelease(properties); + if (!surface->surface) { client->error = "IOSurface allocation failed"; return nullptr; } + surface->stride = static_cast(IOSurfaceGetBytesPerRow(surface->surface)); + surface->bytes = IOSurfaceGetAllocSize(surface->surface); +#else + D3D11_TEXTURE2D_DESC desc{}; + desc.Width = width; desc.Height = height; desc.MipLevels = 1; desc.ArraySize = 1; + desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; desc.SampleDesc.Count = 1; + desc.Usage = D3D11_USAGE_DEFAULT; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET; + desc.MiscFlags = D3D11_RESOURCE_MISC_SHARED_NTHANDLE | D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX; + if (FAILED(client->device->CreateTexture2D(&desc, nullptr, &surface->texture))) { client->error = "D3D11 shared texture allocation failed"; return nullptr; } + if (FAILED(surface->texture.As(&surface->keyed_mutex))) { client->error = "DXGI producer keyed mutex unavailable"; return nullptr; } + ComPtr shared; + if (FAILED(surface->texture.As(&shared)) || FAILED(shared->CreateSharedHandle(nullptr, DXGI_SHARED_RESOURCE_READ | DXGI_SHARED_RESOURCE_WRITE, nullptr, &surface->handle))) { client->error = "DXGI shared handle creation failed"; return nullptr; } + surface->stride = width * 4; surface->bytes = static_cast(width) * height * 4; +#endif + surface->state = dsh_frame_forwarding_surface::acquired; + return surface; +} +static int write_bgra(dsh_frame_forwarding_surface* surface, const void* pixels, size_t stride, uint32_t timeout_ms) { + if (!surface || !pixels || stride < static_cast(surface->width) * 4 || stride > UINT32_MAX) return 0; + auto client = surface->owner; std::lock_guard lock(client->pool_mutex); + if (surface->state != dsh_frame_forwarding_surface::acquired || client->stopped) return 0; +#if defined(__APPLE__) + (void)timeout_ms; + if (IOSurfaceLock(surface->surface, 0, nullptr) != kIOReturnSuccess) return 0; + auto target = static_cast(IOSurfaceGetBaseAddress(surface->surface)); + for (uint32_t row = 0; row < surface->height; ++row) + std::memcpy(target + static_cast(row) * surface->stride, static_cast(pixels) + static_cast(row) * stride, surface->width * 4); + return IOSurfaceUnlock(surface->surface, 0, nullptr) == kIOReturnSuccess; +#else + const auto acquired = surface->keyed_mutex->AcquireSync(0, timeout_ms); + if (acquired != S_OK) { client->error = "Producer write keyed mutex acquisition failed or timed out"; return 0; } + client->context->UpdateSubresource(surface->texture.Get(), 0, nullptr, pixels, static_cast(stride), 0); + const auto released = surface->keyed_mutex->ReleaseSync(0); + client->context->Flush(); + if (released != S_OK) { client->error = "Producer write keyed mutex release failed"; return 0; } + return 1; +#endif +} +int dsh_frame_forwarding_write_bgra(dsh_frame_forwarding_surface* surface, const void* pixels, size_t stride) { + return write_bgra(surface, pixels, stride, 1000); +} +int dsh_frame_forwarding_submit(dsh_frame_forwarding_client* client, dsh_frame_forwarding_surface* surface, uint64_t frame_id, const char* metadata_json) { + if (!client || !surface || surface->owner != client || !frame_id || frame_id > 9007199254740991ULL || client->stopped) return 0; + if (!metadata_json || std::strlen(metadata_json) >= DSH_FRAME_FORWARDING_TEXT_CAPACITY) return 0; + std::lock_guard lock(client->pool_mutex); + if (surface->state != dsh_frame_forwarding_surface::acquired) return 0; + for (auto& other : client->surfaces) { + if (other->state == dsh_frame_forwarding_surface::submitted + && other->frame_id == frame_id) return 0; + } + return send_frame(client, surface, frame_id, metadata_json) ? 1 : 0; +} +int dsh_frame_forwarding_trim(dsh_frame_forwarding_client* client) { + if (!client || client->stopped) return 0; + std::lock_guard lock(client->pool_mutex); + const bool sent = release_idle(client); +#if defined(_WIN32) + // D3D11 destroys a released texture only when its context next flushes, which an idle producer would not do. + client->context->Flush(); +#endif + if (sent) return 1; + client->error = "Frame-forwarding allocation channel closed"; return 0; +} +int dsh_frame_forwarding_poll(dsh_frame_forwarding_client* client, uint32_t timeout, dsh_frame_forwarding_event* event) { + if (!client || !event) return -1; + event->kind = 0; event->text[0] = 0; + { + std::lock_guard lock(client->pool_mutex); + if (!client->error.empty()) { event->kind = -1; copy_error(event->text, sizeof(event->text), client->error.c_str()); return -1; } + } + Received received; + auto result = client->channel->receive(received, std::min(timeout, 100U)); + if (received.resource) release_resource(received.resource); + if (result < 0 || client->stopped) { event->kind = -1; return -1; } + if (!result) return 0; + if (received.packet.marker != magic || received.packet.version != DSH_FRAME_FORWARDING_PROTOCOL_VERSION) { event->kind = -1; return -1; } + if (received.packet.kind == release) { + std::lock_guard lock(client->pool_mutex); + for (auto& surface : client->surfaces) { + if (surface->state == dsh_frame_forwarding_surface::submitted && surface->frame_id == received.packet.frame_id) { + surface->state = dsh_frame_forwarding_surface::available; break; + } + } + } else if (received.packet.kind == allocated) { + std::lock_guard lock(client->pool_mutex); + for (auto& surface : client->surfaces) { + if (surface->allocation_id == received.packet.allocation_id && surface->state == dsh_frame_forwarding_surface::pending) { + surface->state = dsh_frame_forwarding_surface::granted; break; + } + } + } else if (received.packet.kind == message && std::memchr(received.packet.text, 0, sizeof(received.packet.text))) { + event->kind = 1; std::strcpy(event->text, received.packet.text); + } else if (received.packet.kind == goodbye) { client->stopped = true; event->kind = -1; return -1; } + else { event->kind = -1; return -1; } + return event->kind; +} +int dsh_frame_forwarding_send(dsh_frame_forwarding_client* client, const char* json) { + if (!client || client->stopped) return 0; + Packet packet; packet.kind = message; + return set_text(packet, json) && client->channel->send(packet); +} +void dsh_frame_forwarding_interrupt(dsh_frame_forwarding_client* client) { if (client) { client->stopped = true; client->channel->interrupt(); } } +void dsh_frame_forwarding_close(dsh_frame_forwarding_client* client) { + if (!client) return; + Packet packet; packet.kind = goodbye; client->channel->send(packet); + dsh_frame_forwarding_interrupt(client); delete client; +} diff --git a/apps/desktop/tests/frame-forwarding/fixtures/fixture-client.h b/apps/desktop/tests/frame-forwarding/fixtures/fixture-client.h new file mode 100644 index 0000000000..38962d4870 --- /dev/null +++ b/apps/desktop/tests/frame-forwarding/fixtures/fixture-client.h @@ -0,0 +1,21 @@ +#pragma once +#include "transport.h" +typedef struct dsh_frame_forwarding_client dsh_frame_forwarding_client; +typedef struct dsh_frame_forwarding_surface dsh_frame_forwarding_surface; +typedef struct dsh_frame_forwarding_event { int kind; char text[DSH_FRAME_FORWARDING_TEXT_CAPACITY]; } dsh_frame_forwarding_event; +dsh_frame_forwarding_client* dsh_frame_forwarding_connect(const char* tx, char* error, size_t error_size); +typedef struct dsh_frame_forwarding_connect_options { + void* device; + uint32_t timeout_ms; + void* cancellation_context; + int (*cancelled)(void*); +} dsh_frame_forwarding_connect_options; +dsh_frame_forwarding_client* dsh_frame_forwarding_connect_with_options(const char* tx, + const dsh_frame_forwarding_connect_options* options, char* error, size_t error_size); +dsh_frame_forwarding_surface* dsh_frame_forwarding_acquire(dsh_frame_forwarding_client* client, uint32_t width, uint32_t height); +int dsh_frame_forwarding_write_bgra(dsh_frame_forwarding_surface* surface, const void* pixels, size_t stride); +int dsh_frame_forwarding_submit(dsh_frame_forwarding_client* client, dsh_frame_forwarding_surface* surface, uint64_t frame_id, const char* metadata_json); +int dsh_frame_forwarding_trim(dsh_frame_forwarding_client* client); +int dsh_frame_forwarding_poll(dsh_frame_forwarding_client* client, uint32_t timeout_ms, dsh_frame_forwarding_event* event); +int dsh_frame_forwarding_send(dsh_frame_forwarding_client* client, const char* json); +void dsh_frame_forwarding_close(dsh_frame_forwarding_client* client); diff --git a/apps/desktop/tests/frame-forwarding/fixtures/mach-port-census.cc b/apps/desktop/tests/frame-forwarding/fixtures/mach-port-census.cc new file mode 100644 index 0000000000..cc2af05d65 --- /dev/null +++ b/apps/desktop/tests/frame-forwarding/fixtures/mach-port-census.cc @@ -0,0 +1,43 @@ +/** + * Test-only addon: count the dead names of the process that loads it, and their references, so reconnect tests can + * verify that neither crashed nor graceful producer disconnects accumulate dead names in the Host's port table. + */ +#include +#include +#include + +namespace { +napi_value census(napi_env env, napi_callback_info) { + mach_port_name_array_t names = nullptr; + mach_port_type_array_t types = nullptr; + mach_msg_type_number_t name_count = 0, type_count = 0; + if (mach_port_names(mach_task_self(), &names, &name_count, &types, &type_count) != KERN_SUCCESS) { + napi_throw_error(env, nullptr, "cannot list Mach port names"); + return nullptr; + } + uint32_t dead = 0; + uint64_t references = 0; + for (mach_msg_type_number_t index = 0; index < name_count && index < type_count; ++index) { + if (!(types[index] & MACH_PORT_TYPE_DEAD_NAME)) continue; + mach_port_urefs_t urefs = 0; + if (mach_port_get_refs(mach_task_self(), names[index], MACH_PORT_RIGHT_DEAD_NAME, &urefs) != KERN_SUCCESS) continue; + ++dead; references += urefs; + } + vm_deallocate(mach_task_self(), reinterpret_cast(names), name_count * sizeof(mach_port_name_t)); + vm_deallocate(mach_task_self(), reinterpret_cast(types), type_count * sizeof(mach_port_type_t)); + napi_value result, dead_value, references_value; + napi_create_object(env, &result); + napi_create_uint32(env, dead, &dead_value); + napi_create_double(env, static_cast(references), &references_value); + napi_set_named_property(env, result, "deadNames", dead_value); + napi_set_named_property(env, result, "deadNameRefs", references_value); + return result; +} +} // namespace + +NAPI_MODULE_INIT() { + napi_value function; + if (napi_create_function(env, "count", NAPI_AUTO_LENGTH, census, nullptr, &function) != napi_ok) return nullptr; + napi_set_named_property(env, exports, "count", function); + return exports; +} diff --git a/apps/desktop/tests/frame-forwarding/fixtures/malicious-producer.cc b/apps/desktop/tests/frame-forwarding/fixtures/malicious-producer.cc new file mode 100644 index 0000000000..9df2e7e2db --- /dev/null +++ b/apps/desktop/tests/frame-forwarding/fixtures/malicious-producer.cc @@ -0,0 +1,360 @@ +/** Test-only hostile peer. Uses the receiver transport, deliberately bypassing the producer API's validation. */ +#include "transport.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace dsh_frame_forwarding; + +static void number(CFMutableDictionaryRef props, CFStringRef key, int value) { + auto item = CFNumberCreate(nullptr, kCFNumberIntType, &value); + CFDictionarySetValue(props, key, item); CFRelease(item); +} +static IOSurfaceRef surface(const std::string& mode) { + auto props = CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + number(props, kIOSurfaceWidth, 64); number(props, kIOSurfaceHeight, 64); + number(props, kIOSurfaceBytesPerElement, 4); + number(props, kIOSurfacePixelFormat, mode == "format" ? 'RGBA' : mode == "planes" ? '420v' : 'BGRA'); + if (mode == "planes") { + auto planes = CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks); + for (int i = 0; i < 2; ++i) { + auto plane = CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + number(plane, kIOSurfacePlaneWidth, i ? 32 : 64); number(plane, kIOSurfacePlaneHeight, i ? 32 : 64); + number(plane, kIOSurfacePlaneBytesPerElement, i ? 2 : 1); + number(plane, kIOSurfacePlaneBytesPerRow, 64); number(plane, kIOSurfacePlaneOffset, i ? 4096 : 0); + number(plane, kIOSurfacePlaneSize, i ? 2048 : 4096); + CFArrayAppendValue(planes, plane); CFRelease(plane); + } + CFDictionarySetValue(props, kIOSurfacePlaneInfo, planes); CFRelease(planes); + } + auto result = IOSurfaceCreate(props); CFRelease(props); + if (!result) throw std::runtime_error("IOSurfaceCreate failed"); + return result; +} +static void send(Channel& channel, Packet packet, IOSurfaceRef resource = nullptr) { + if (!channel.send(packet, reinterpret_cast(resource))) throw std::runtime_error("packet send failed"); +} +static Packet receive(Channel& channel) { + Received result{}; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (std::chrono::steady_clock::now() < deadline) { + const int status = channel.receive(result, 100); + if (status == 1) return result.packet; + if (status < 0) throw std::runtime_error("peer closed"); + } + throw std::runtime_error("peer did not answer"); +} +static uint64_t generation = 0; +static void control(Channel& channel, const Packet& packet) { + const std::string text(packet.text); + if (text.find("\"type\":\"viewport\"") == std::string::npos) return; + auto version = text.find("\"version\":"); + auto id = text.find("\"requestId\":\""); + if (version == std::string::npos || id == std::string::npos) throw std::runtime_error("invalid viewport"); + generation = std::strtoull(text.c_str() + version + 10, nullptr, 10); + id += 13; auto end = text.find('"', id); + Packet response; response.kind = message; + std::snprintf(response.text, sizeof(response.text), "{\"type\":\"viewport-applied\",\"version\":%llu,\"requestId\":\"%s\"}", + static_cast(generation), text.substr(id, end - id).c_str()); + send(channel, response); +} +/** A receiver connection reached over raw Mach, keeping the port and identifier the transport channel hides. */ +struct RawChannel { + mach_port_t local = MACH_PORT_NULL, remote = MACH_PORT_NULL; + uint64_t connection = 0; +}; +/** One message in the receiver's layout, followed by room for the trailer the kernel appends after it. */ +struct RawMessage { + mach_msg_header_t header; + mach_msg_body_t body; + mach_msg_port_descriptor_t port; + WireHeader wire; + char text[DSH_FRAME_FORWARDING_TEXT_CAPACITY]; + mach_msg_audit_trailer_t trailer; +}; +static mach_port_t receive_port() { + mach_port_t port = MACH_PORT_NULL; + if (mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &port) != KERN_SUCCESS || + mach_port_insert_right(mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND) != KERN_SUCCESS) + throw std::runtime_error("cannot allocate a Mach port"); + return port; +} +/** Lay `packet` out exactly as the receiver decodes it, stamped with `token`. */ +static void compose(RawMessage& message, const Packet& packet, const char* token) { + std::memset(&message, 0, sizeof(message)); + message.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0) | MACH_MSGH_BITS_COMPLEX; + message.body.msgh_descriptor_count = 1; + message.port.type = MACH_MSG_PORT_DESCRIPTOR; + message.port.disposition = MACH_MSG_TYPE_COPY_SEND; + message.wire.marker = magic; message.wire.version = DSH_FRAME_FORWARDING_PROTOCOL_VERSION; message.wire.kind = packet.kind; + message.wire.max_frames = packet.max_frames; + message.wire.text_size = static_cast(std::strlen(packet.text)); + std::snprintf(message.wire.token, sizeof(message.wire.token), "%s", token); + std::memcpy(message.text, packet.text, message.wire.text_size); + message.header.msgh_size = static_cast(offsetof(RawMessage, text) + ((message.wire.text_size + 3u) & ~3u)); +} +static void send_raw(mach_port_t destination, RawMessage& message) { + message.header.msgh_remote_port = destination; + const auto result = mach_msg(&message.header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, message.header.msgh_size, 0, MACH_PORT_NULL, 1000, MACH_PORT_NULL); + if (result != KERN_SUCCESS) throw std::runtime_error("raw Mach message send failed"); +} +/** Receive one raw message; false when none arrives within `timeout` milliseconds. */ +static bool receive_raw(mach_port_t port, uint32_t timeout, RawMessage& received) { + std::memset(&received, 0, sizeof(received)); + const auto result = mach_msg(&received.header, MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0, sizeof(received), port, timeout, MACH_PORT_NULL); + if (result == MACH_RCV_TIMED_OUT) return false; + if (result != KERN_SUCCESS) throw std::runtime_error("raw Mach message receive failed"); + return true; +} +/** The kind of a received message, or zero for anything that is not a protocol packet. */ +static uint32_t packet_kind(const RawMessage& received) { + if (received.header.msgh_size < offsetof(RawMessage, wire) + sizeof(WireHeader)) return 0; + if (received.wire.marker != magic || received.wire.version != DSH_FRAME_FORWARDING_PROTOCOL_VERSION) return 0; + return received.wire.kind; +} +/** Connect straight over Mach, so the hostile message can name the receiver's own connection port. */ +static RawChannel connect_raw(const Endpoint& endpoint) { + RawChannel channel; + channel.local = receive_port(); + mach_port_t listener = MACH_PORT_NULL; + if (bootstrap_look_up(bootstrap_port, endpoint.name.c_str(), &listener) != KERN_SUCCESS) throw std::runtime_error("listener lookup failed"); + Packet greeting; greeting.kind = hello; greeting.max_frames = hello_capabilities; + RawMessage outbound; + compose(outbound, greeting, endpoint.token.c_str()); + outbound.port.name = channel.local; + send_raw(listener, outbound); + mach_port_deallocate(mach_task_self(), listener); + RawMessage response; + if (!receive_raw(channel.local, 10000, response)) throw std::runtime_error("receiver did not answer the handshake"); + if (packet_kind(response) != ready || !response.port.name) throw std::runtime_error("handshake refused"); + channel.connection = parse_connection(response.wire.token); + if (!channel.connection) throw std::runtime_error("handshake returned no connection identifier"); + // The descriptor is the receiver's connection port; this producer keeps the send right it received. + channel.remote = response.port.name; + return channel; +} +/** Wait for the send right of `port` to become a dead name, which the destroyed receive right leaves behind. */ +static bool dead_name_within(mach_port_t port, uint32_t timeout) { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout); + for (;;) { + mach_port_type_t type = 0; + if (mach_port_type(mach_task_self(), port, &type) == KERN_SUCCESS && (type & MACH_PORT_TYPE_DEAD_NAME)) return true; + if (std::chrono::steady_clock::now() >= deadline) return false; + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } +} +/** Wait for the send-once notice the kernel posts when the receiver destroys the reply right it was handed. */ +static bool send_once_within(mach_port_t port, uint32_t timeout) { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout); + while (std::chrono::steady_clock::now() < deadline) { + RawMessage received; + if (!receive_raw(port, 50, received)) continue; + const bool notice = received.header.msgh_id == MACH_NOTIFY_SEND_ONCE; + mach_msg_destroy(&received.header); + if (notice) return true; + } + return false; +} +/** Wait for the receiver's answer to the normal message sent behind the hostile one. */ +static bool answer_within(mach_port_t port, uint32_t timeout) { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout); + while (std::chrono::steady_clock::now() < deadline) { + RawMessage received; + if (!receive_raw(port, 50, received)) continue; + const bool answer = packet_kind(received) == dsh_frame_forwarding::message && std::strcmp(received.text, "go") == 0; + mach_msg_destroy(&received.header); + if (answer) return true; + } + return false; +} +/** Send a non-complex message posing as a kernel notification (`id`), optionally carrying a send-once reply right. */ +static void send_forged_notice(mach_port_t destination, mach_msg_id_t id, mach_port_t reply) { + struct { + mach_msg_header_t header; + char body[12]; + } notice{}; + notice.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, reply ? MACH_MSG_TYPE_MAKE_SEND_ONCE : 0); + notice.header.msgh_size = sizeof(notice); + notice.header.msgh_remote_port = destination; + notice.header.msgh_local_port = reply; + notice.header.msgh_id = id; + const auto sent = mach_msg(¬ice.header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, sizeof(notice), 0, MACH_PORT_NULL, 5000, MACH_PORT_NULL); + if (sent != KERN_SUCCESS) throw std::runtime_error("forged Mach notice send failed"); +} +int main(int argc, char** argv) { + if (argc != 3) return 2; + std::vector surfaces; + try { + const std::string mode(argv[2]); + if (mode == "mach-oversize") { + // A message larger than the receiver's buffer, sent straight to the listener port without a hello. + auto endpoint = parse_endpoint(argv[1]); + mach_port_t listener = MACH_PORT_NULL; + if (bootstrap_look_up(bootstrap_port, endpoint.name.c_str(), &listener) != KERN_SUCCESS) throw std::runtime_error("listener lookup failed"); + static struct { mach_msg_header_t header; char payload[64 * 1024]; } message; + message.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0); + message.header.msgh_size = sizeof(message); + message.header.msgh_remote_port = listener; + const auto sent = mach_msg(&message.header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, sizeof(message), 0, MACH_PORT_NULL, 5000, MACH_PORT_NULL); + mach_port_deallocate(mach_task_self(), listener); + if (sent != KERN_SUCCESS) throw std::runtime_error("oversized Mach message send failed"); + return 0; + } + if (mode == "mach-forged-notice-listener") { + // Forged dead-name and no-senders notices carrying send-once reply rights, sent straight to the listener port + // without a handshake. The receiver must destroy every reply right so the sender observes send-once notices. + auto endpoint = parse_endpoint(argv[1]); + mach_port_t listener = MACH_PORT_NULL; + if (bootstrap_look_up(bootstrap_port, endpoint.name.c_str(), &listener) != KERN_SUCCESS) throw std::runtime_error("listener lookup failed"); + mach_port_t watched_dead = receive_port(); + mach_port_t watched_no_senders = receive_port(); + send_forged_notice(listener, MACH_NOTIFY_DEAD_NAME, watched_dead); + send_forged_notice(listener, MACH_NOTIFY_NO_SENDERS, watched_no_senders); + mach_port_deallocate(mach_task_self(), listener); + const bool dead_destroyed = send_once_within(watched_dead, 10000); + const bool no_senders_destroyed = send_once_within(watched_no_senders, 10000); + mach_port_destroy(mach_task_self(), watched_dead); + mach_port_destroy(mach_task_self(), watched_no_senders); + if (!dead_destroyed) { std::fputs("the listener kept the reply right of a forged dead-name notice\n", stderr); return 1; } + if (!no_senders_destroyed) { std::fputs("the listener kept the reply right of a forged no-senders notice\n", stderr); return 1; } + return 0; + } + if (mode == "mach-forged-notice-channel") { + // Forged dead-name and no-senders notices sent on an active connection port: two carrying send-once reply rights + // and a bare no-senders notice trying to end the connection. All three must be rejected while the connection stays up. + auto channel = connect_raw(parse_endpoint(argv[1])); + char token[65]; + std::snprintf(token, sizeof(token), "%llu", static_cast(channel.connection)); + mach_port_t watched_dead = receive_port(); + mach_port_t watched_no_senders = receive_port(); + send_forged_notice(channel.remote, MACH_NOTIFY_DEAD_NAME, watched_dead); + send_forged_notice(channel.remote, MACH_NOTIFY_NO_SENDERS, watched_no_senders); + send_forged_notice(channel.remote, MACH_NOTIFY_NO_SENDERS, MACH_PORT_NULL); + Packet armed; armed.kind = message; std::strcpy(armed.text, "armed"); + RawMessage normal; + compose(normal, armed, token); + send_raw(channel.remote, normal); + const bool dead_destroyed = send_once_within(watched_dead, 10000); + const bool no_senders_destroyed = send_once_within(watched_no_senders, 10000); + mach_port_destroy(mach_task_self(), watched_dead); + mach_port_destroy(mach_task_self(), watched_no_senders); + if (!dead_destroyed) { std::fputs("the channel kept the reply right of a forged dead-name notice\n", stderr); return 1; } + if (!no_senders_destroyed) { std::fputs("the channel kept the reply right of a forged no-senders notice\n", stderr); return 1; } + if (!answer_within(channel.local, 10000)) { std::fputs("a forged notice ended the connection\n", stderr); return 1; } + Packet bye; bye.kind = goodbye; + RawMessage close; + compose(close, bye, token); + send_raw(channel.remote, close); + return 0; + } + if (mode == "mach-move-receive" || mode == "mach-reply-port") { + // A message of the protocol's shape that carries a port right the protocol never sends. The receiver must + // destroy the whole message; the producer then observes the right die, and reports it when it survives. + auto channel = connect_raw(parse_endpoint(argv[1])); + char token[65]; + std::snprintf(token, sizeof(token), "%llu", static_cast(channel.connection)); + mach_port_t watched = receive_port(); + Packet smuggled; smuggled.kind = message; std::strcpy(smuggled.text, "smuggled"); + RawMessage hostile; + compose(hostile, smuggled, token); + if (mode == "mach-move-receive") { hostile.port.disposition = MACH_MSG_TYPE_MOVE_RECEIVE; hostile.port.name = watched; } + else { + // A reply right in the header, with the complex bit kept so the shape still passes without the fix. + hostile.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_MAKE_SEND_ONCE) | MACH_MSGH_BITS_COMPLEX; + hostile.header.msgh_local_port = watched; + } + send_raw(channel.remote, hostile); + // A normal message behind it proves the receiver dropped the hostile one and kept the connection. + Packet armed; armed.kind = message; std::strcpy(armed.text, "armed"); + RawMessage normal; + compose(normal, armed, token); + send_raw(channel.remote, normal); + const bool destroyed = mode == "mach-move-receive" ? dead_name_within(watched, 10000) : send_once_within(watched, 10000); + if (!destroyed) { + std::fprintf(stderr, "%s\n", mode == "mach-move-receive" + ? "the receiver kept the transferred receive right" : "the receiver kept the send-once reply right"); + return 1; + } + if (!answer_within(channel.local, 10000)) { std::fputs("the connection stopped answering\n", stderr); return 1; } + Packet bye; bye.kind = goodbye; + RawMessage close; + compose(close, bye, token); + send_raw(channel.remote, close); + return 0; + } + auto endpoint = parse_endpoint(argv[1]); auto channel = connect_channel(endpoint); + Packet greeting; greeting.kind = hello; greeting.max_frames = hello_capabilities; + std::snprintf(greeting.token, sizeof(greeting.token), "%s", endpoint.token.c_str()); send(*channel, greeting); + auto readyPacket = receive(*channel); + if (readyPacket.kind != ready) throw std::runtime_error("handshake refused"); + channel->bind_connection(parse_connection(readyPacket.token)); + if (mode == "foreign") { + channel->bind_connection(channel->connection() + 1); + Packet invalid; invalid.kind = message; send(*channel, invalid); + } else { + auto image = surface(mode); surfaces.push_back(image); + Packet allocation; allocation.kind = allocate; allocation.allocation_id = 1; + allocation.max_bytes = mode == "allocation" ? readyPacket.max_bytes + 1 : IOSurfaceGetAllocSize(image); + send(*channel, allocation); + if (mode != "allocation") { + for (;;) { auto packet = receive(*channel); if (packet.kind == allocated) break; control(*channel, packet); } + if (mode == "allocation-reuse") send(*channel, allocation); + else { + Packet armed; armed.kind = message; std::strcpy(armed.text, "armed"); send(*channel, armed); + // Tests send "go" after their viewport acknowledgement, so metadata has a deterministic generation. + for (;;) { auto packet = receive(*channel); control(*channel, packet); if (std::strcmp(packet.text, "go") == 0) break; } + Packet value; value.kind = frame; value.frame_id = 1; value.allocation_id = 1; + value.width = mode == "oversize" ? 16385 : mode == "zero" ? 0 : 64; + value.height = mode == "oversize" ? 65535 : mode == "zero" ? 0 : 64; + value.stride = IOSurfaceGetBytesPerRow(image) + (mode == "stride-plus" ? 1 : mode == "stride-minus" ? -1 : 0); + std::snprintf(value.text, sizeof(value.text), "{\"requestId\":\"\",\"generation\":%llu,\"revision\":1}", static_cast(generation)); + if (mode == "metadata") std::memset(value.text, 'x', sizeof(value.text)); + if (mode == "metadata-deep") { std::string deep(2000, '['); deep += "0"; deep += std::string(2000, ']'); std::strcpy(value.text, deep.c_str()); } + if (mode == "metadata-utf8") { value.text[0] = char(0xff); value.text[1] = 0; } + send(*channel, value, image); + if (mode == "frame-reuse") send(*channel, value, image); + if (mode == "deallocate") { Packet invalid; invalid.kind = deallocate; invalid.allocation_id = 1; send(*channel, invalid); } + std::puts("submitted"); std::fflush(stdout); + if (mode == "flood") { + unsigned submitted = 1, attempts = 0; bool credit = false; + const auto start = std::chrono::steady_clock::now(); + for (; attempts < 1000; ++attempts) { + Received result{}; const int status = channel->receive(result, 0); + if (status < 0) throw std::runtime_error("flood peer closed"); + if (status == 1) { control(*channel, result.packet); if (result.packet.kind == release) credit = true; } + if (credit) { value.frame_id++; send(*channel, value, image); submitted++; credit = false; } + std::this_thread::sleep_until(start + std::chrono::milliseconds(attempts + 1)); + } + Packet done; done.kind = message; std::snprintf(done.text, sizeof(done.text), "{\"attempts\":1000,\"submitted\":%u}", submitted); send(*channel, done); + } + } + } + } + for (;;) { + Received result{}; const int status = channel->receive(result, 10000); + if (status < 0) break; + if (status == 0) continue; + if (result.packet.kind == goodbye) break; + control(*channel, result.packet); + if (std::strcmp(result.packet.text, "exit") == 0) { Packet bye; bye.kind = goodbye; send(*channel, bye); break; } + if (std::strcmp(result.packet.text, "check") == 0) { + int inUse = 0; for (auto image : surfaces) inUse += IOSurfaceIsInUse(image) ? 1 : 0; + Packet report; report.kind = message; std::snprintf(report.text, sizeof(report.text), "{\"inUse\":%d}", inUse); send(*channel, report); + } + } + for (auto image : surfaces) CFRelease(image); + return 0; + } catch (const std::exception& error) { + for (auto image : surfaces) CFRelease(image); + std::fprintf(stderr, "%s\n", error.what()); return 3; + } +} diff --git a/apps/desktop/tests/frame-forwarding/fixtures/producer.cc b/apps/desktop/tests/frame-forwarding/fixtures/producer.cc new file mode 100644 index 0000000000..c0c0fc0c7e --- /dev/null +++ b/apps/desktop/tests/frame-forwarding/fixtures/producer.cc @@ -0,0 +1,38 @@ +#include "fixture-client.h" +#include +#include +#include +#include +int main(int argc, char** argv) { + if (argc != 2) return 2; + char error[256] = {}; + auto client = dsh_frame_forwarding_connect(argv[1], error, sizeof(error)); + if (!client) { std::fprintf(stderr, "%s\n", error); return 3; } + uint64_t frame = 1; + bool requested = true; + // `render ` submits its metadata and reports `{"submitted":}` once the frame is submitted. + std::string metadata = "{\"tile\":\"test\"}"; + bool report = false; + while (true) { + if (requested) { + auto surface = dsh_frame_forwarding_acquire(client, 64, 64); + if (surface) { + std::vector pixels(64 * 64, 0xff3366cc); + if (!dsh_frame_forwarding_write_bgra(surface, pixels.data(), 64 * 4) || !dsh_frame_forwarding_submit(client, surface, frame++, metadata.c_str())) return 4; + requested = false; + if (report) dsh_frame_forwarding_send(client, ("{\"submitted\":" + std::to_string(frame - 1) + "}").c_str()); + } + } + dsh_frame_forwarding_event event{}; + if (dsh_frame_forwarding_poll(client, 100, &event) < 0) break; + if (event.kind == 1) { + if (std::strcmp(event.text, "exit") == 0) break; + if (std::strcmp(event.text, "render") == 0) requested = true; + if (std::strncmp(event.text, "render ", 7) == 0) { requested = true; report = true; metadata = event.text + 7; } + if (std::strcmp(event.text, "ack") == 0) dsh_frame_forwarding_send(client, "{\"applied\":1}"); + // A hidden view returns its idle surfaces to the shared budget. + if (std::strcmp(event.text, "trim") == 0 && dsh_frame_forwarding_trim(client)) dsh_frame_forwarding_send(client, "{\"trimmed\":1}"); + } + } + dsh_frame_forwarding_close(client); return 0; +} diff --git a/apps/desktop/tests/frame-forwarding/fixtures/surface-pixel.cc b/apps/desktop/tests/frame-forwarding/fixtures/surface-pixel.cc new file mode 100644 index 0000000000..4b3b4e4782 --- /dev/null +++ b/apps/desktop/tests/frame-forwarding/fixtures/surface-pixel.cc @@ -0,0 +1,39 @@ +// Test-only reader of one BGRA pixel from a Host-local IOSurfaceRef handle delivered by the receiver. +#include +#include +#include +#include +static napi_value pixel(napi_env env, napi_callback_info info) { + size_t count = 3; + napi_value args[3]; + void* data = nullptr; + size_t size = 0; + uint32_t x = 0, y = 0; + if (napi_get_cb_info(env, info, &count, args, nullptr, nullptr) != napi_ok || count != 3 + || napi_get_buffer_info(env, args[0], &data, &size) != napi_ok || size != sizeof(uintptr_t) + || napi_get_value_uint32(env, args[1], &x) != napi_ok || napi_get_value_uint32(env, args[2], &y) != napi_ok) { + napi_throw_type_error(env, nullptr, "Expected an eight-byte handle and pixel coordinates"); + return nullptr; + } + uintptr_t handle; + std::memcpy(&handle, data, sizeof(handle)); + auto surface = reinterpret_cast(handle); + if (x >= IOSurfaceGetWidth(surface) || y >= IOSurfaceGetHeight(surface) + || IOSurfaceLock(surface, kIOSurfaceLockReadOnly, nullptr) != kIOReturnSuccess) { + napi_throw_range_error(env, nullptr, "Pixel is outside the surface or the surface cannot be read"); + return nullptr; + } + auto row = static_cast(IOSurfaceGetBaseAddress(surface)) + static_cast(y) * IOSurfaceGetBytesPerRow(surface); + uint32_t bgra; + std::memcpy(&bgra, row + static_cast(x) * 4, sizeof(bgra)); + IOSurfaceUnlock(surface, kIOSurfaceLockReadOnly, nullptr); + napi_value result; + napi_create_uint32(env, bgra, &result); + return result; +} +NAPI_MODULE_INIT() { + napi_value function; + napi_create_function(env, "pixel", NAPI_AUTO_LENGTH, pixel, nullptr, &function); + napi_set_named_property(env, exports, "pixel", function); + return exports; +} diff --git a/apps/desktop/tests/frame-forwarding/fuzz/README.i18n.yaml b/apps/desktop/tests/frame-forwarding/fuzz/README.i18n.yaml new file mode 100644 index 0000000000..3e5b4cf712 --- /dev/null +++ b/apps/desktop/tests/frame-forwarding/fuzz/README.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write apps/desktop/tests/frame-forwarding/fuzz/README.md +/frame-forwarding-wire-protocol-fuzz-targets: + en: bd1987338940c30d + zh: 4ab14df2903a7f3e +/frame-forwarding-wire-protocol-fuzz-targets/targets: + en: 4771e92b7db05572 + zh: a39f94cc47d29264 +/frame-forwarding-wire-protocol-fuzz-targets/seed-corpus: + en: 860401a8f1500b10 + zh: 793dc744bc21c4d8 +/frame-forwarding-wire-protocol-fuzz-targets/run-on-windows: + en: 67b261c0532c1e8f + zh: 86790cb17d7a830b +/frame-forwarding-wire-protocol-fuzz-targets/run-on-macos: + en: 4dc45e7832658303 + zh: 1f61e17acff708a2 +/frame-forwarding-wire-protocol-fuzz-targets/read-a-run: + en: 4876ac4150522f1a + zh: d7b7750f8f97b13c diff --git a/apps/desktop/tests/frame-forwarding/fuzz/README.md b/apps/desktop/tests/frame-forwarding/fuzz/README.md new file mode 100644 index 0000000000..d41875b28f --- /dev/null +++ b/apps/desktop/tests/frame-forwarding/fuzz/README.md @@ -0,0 +1,55 @@ +# Frame-forwarding wire-protocol fuzz targets + +English | [中文](README.zh.md) + +These libFuzzer harnesses cover the native parsing code in `packages/experimental/frame-forwarding/native`. They feed arbitrary bytes to the parsers for what a producer process sends to the receiver and what a producer reads from a receiver, under AddressSanitizer on Windows and macOS and also UndefinedBehaviorSanitizer on macOS, since MSVC has no UBSan. The targets run only when started by hand; no test suite or CI job runs them. + +The harnesses compile the production `transport.cc` into their own translation unit, which reaches its file-local `decode_packet` and `encode_header` without exporting them from the addon. The scripts build a source snapshot such as `git archive HEAD` output, so edits in the working tree do not change a run. + +## Targets + +| Source | Entry points | Checks | +| --- | --- | --- | +| `packet-fuzzer.cc` | `decode_packet` as a Windows pipe message (`padded=false`) and as a macOS Mach message (`padded=true`) | An accepted packet re-encodes with `encode_header` and decodes to the same fields, token, and text; the text ends with NUL inside its capacity unless it fills the capacity; both conventions agree whenever both accept the input. | +| `endpoint-fuzzer.cc` | `parse_endpoint`, `parse_connection`, and the identifier that `Channel::send` stamps | An accepted endpoint fits the protocol and parses back from its `1\|\|\|` form; an accepted connection identifier is at most 2^53-1 and parses back from its decimal form. | + +A failed check prints the input in hex and aborts, so libFuzzer keeps the input as a crash artifact. + +## Seed corpus + +`corpus/` holds one legal packet of each kind, written by `corpus-gen.cc` with the production `encode_header`. The run scripts add seeds the repository does not store: a protocol 1 hello, a current hello that ends before the header, a message whose text fills the capacity without a terminator, and the Mach-padded form of each seed whose text length is not a multiple of 4. + +## Run on Windows + +Visual Studio 2022 with the C++ AddressSanitizer component provides the toolchain. From the repository root: + +```powershell +$root = Join-Path $env:TEMP 'dsh-frame-forwarding-fuzz' +New-Item -ItemType Directory -Force "$root\src" | Out-Null +git archive --output "$root\src.tar" HEAD packages/experimental/frame-forwarding/native +tar -x -f "$root\src.tar" -C "$root\src" +apps/desktop/tests/frame-forwarding/fuzz/run-windows.ps1 -NativeDir "$root\src\packages\experimental\frame-forwarding\native" -MaxTotalTime 600 +``` + +The script locates `vcvarsall.bat`, builds with `/fsanitize=address /fsanitize=fuzzer` because MSVC rejects the comma-separated form, puts the directory holding `clang_rt.asan_dynamic-x86_64.dll` on `PATH`, and runs each target with `-timeout=10 -rss_limit_mb=2048`. `-Build` or `-Run` performs one of the two steps. Binaries, the generated corpus, logs, and crash artifacts go under `%TEMP%\dsh-frame-forwarding-fuzz\work`. + +## Run on macOS + +Apple clang ships no libFuzzer, so the script uses Homebrew LLVM. From the repository root: + +```bash +d=$(mktemp -d /tmp/dsh-frame-forwarding-fuzz.XXXXXX) +git archive HEAD packages/experimental/frame-forwarding/native | tar -x -C "$d" +CXX=/opt/homebrew/opt/llvm/bin/clang++ bash apps/desktop/tests/frame-forwarding/fuzz/run-macos.sh \ + --native "$d/packages/experimental/frame-forwarding/native" --work "$d/work" --max-total-time 600 +``` + +The script builds with `-fsanitize=fuzzer,address,undefined -fno-sanitize-recover=undefined` and links `IOSurface`, `CoreFoundation`, and `libbsm`. + +## Read a run + +Each run ends with a `DONE` line and the `-print_final_stats=1` statistics. MSVC builds report features (`ft:`) only; clang builds also report covered edges (`cov:`). An input that crashes, times out, or exhausts memory is written as `crash-*`, `timeout-*`, or `oom-*` under `/artifacts-/`. Minimize it with: + +``` +/-fuzzer -minimize_crash=1 -timeout=10 -rss_limit_mb=2048 /artifacts-/crash- +``` diff --git a/apps/desktop/tests/frame-forwarding/fuzz/README.zh.md b/apps/desktop/tests/frame-forwarding/fuzz/README.zh.md new file mode 100644 index 0000000000..89dbb6970d --- /dev/null +++ b/apps/desktop/tests/frame-forwarding/fuzz/README.zh.md @@ -0,0 +1,55 @@ +# 帧转发线路协议的模糊测试目标 + +[English](README.md) | 中文 + +这些 libFuzzer 测试覆盖 `packages/experimental/frame-forwarding/native` 中的原生解析代码。它们把任意字节交给两类解析器:一类解析 producer 进程发给 receiver 的数据,另一类是 producer 解析从 receiver 收到的数据。Windows 和 macOS 上都启用 AddressSanitizer,macOS 上另外启用 UndefinedBehaviorSanitizer,因为 MSVC 不支持 UBSan。这些目标只在手动启动时运行,任何测试套件和 CI 任务都不会运行它们。 + +测试把生产代码的 `transport.cc` 编译进自己的翻译单元,因而不必从 addon 导出,就能调用其文件内的 `decode_packet` 和 `encode_header`。脚本编译的是源码快照,例如 `git archive HEAD` 的输出,因此工作区里正在进行的修改不会影响运行结果。 + +## 测试目标 + +| 源文件 | 入口 | 检查 | +| --- | --- | --- | +| `packet-fuzzer.cc` | `decode_packet`,分别按 Windows 管道消息(`padded=false`)和 macOS Mach 消息(`padded=true`)解析 | 被接受的包用 `encode_header` 重新编码后,再解码得到相同的字段、token 和文本;文本在容量内以 NUL 结尾,除非正好占满容量;两种约定都接受同一输入时,结果一致。 | +| `endpoint-fuzzer.cc` | `parse_endpoint`、`parse_connection`,以及 `Channel::send` 写入的标识符 | 被接受的 endpoint 符合协议,并能从其 `1\|\|\|` 形式解析回来;被接受的连接标识符不超过 2^53-1,并能从其十进制形式解析回来。 | + +检查失败时会打印十六进制的输入并中止,libFuzzer 会把这个输入保存为崩溃样本。 + +## 种子语料 + +`corpus/` 中每种包各有一个合法样本,由 `corpus-gen.cc` 用生产代码的 `encode_header` 生成。运行脚本还会加入仓库里不保存的种子:协议 1 的 hello、在包头之前就结束的当前版本 hello、文本占满容量且没有终止符的消息,以及文本长度不是 4 的倍数的每个种子的 Mach 填充形式。 + +## 在 Windows 上运行 + +工具链来自安装了 C++ AddressSanitizer 组件的 Visual Studio 2022。在仓库根目录运行: + +```powershell +$root = Join-Path $env:TEMP 'dsh-frame-forwarding-fuzz' +New-Item -ItemType Directory -Force "$root\src" | Out-Null +git archive --output "$root\src.tar" HEAD packages/experimental/frame-forwarding/native +tar -x -f "$root\src.tar" -C "$root\src" +apps/desktop/tests/frame-forwarding/fuzz/run-windows.ps1 -NativeDir "$root\src\packages\experimental\frame-forwarding\native" -MaxTotalTime 600 +``` + +脚本会找到 `vcvarsall.bat`,用 `/fsanitize=address /fsanitize=fuzzer` 编译(MSVC 不接受逗号分隔的写法),把包含 `clang_rt.asan_dynamic-x86_64.dll` 的目录加入 `PATH`,并以 `-timeout=10 -rss_limit_mb=2048` 运行每个目标。`-Build` 或 `-Run` 只执行其中一步。二进制文件、生成的语料、日志和崩溃样本都放在 `%TEMP%\dsh-frame-forwarding-fuzz\work` 下。 + +## 在 macOS 上运行 + +Apple clang 不带 libFuzzer,因此脚本使用 Homebrew LLVM。在仓库根目录运行: + +```bash +d=$(mktemp -d /tmp/dsh-frame-forwarding-fuzz.XXXXXX) +git archive HEAD packages/experimental/frame-forwarding/native | tar -x -C "$d" +CXX=/opt/homebrew/opt/llvm/bin/clang++ bash apps/desktop/tests/frame-forwarding/fuzz/run-macos.sh \ + --native "$d/packages/experimental/frame-forwarding/native" --work "$d/work" --max-total-time 600 +``` + +脚本用 `-fsanitize=fuzzer,address,undefined -fno-sanitize-recover=undefined` 编译,并链接 `IOSurface`、`CoreFoundation` 和 `libbsm`。 + +## 查看运行结果 + +每次运行都以一行 `DONE` 和 `-print_final_stats=1` 的统计结束。MSVC 构建只报告特征数(`ft:`),clang 构建还报告覆盖的边数(`cov:`)。导致崩溃、超时或内存耗尽的输入会以 `crash-*`、`timeout-*` 或 `oom-*` 的名字写入 `/artifacts-/`。用下面的命令把它最小化: + +``` +/-fuzzer -minimize_crash=1 -timeout=10 -rss_limit_mb=2048 /artifacts-/crash- +``` diff --git a/apps/desktop/tests/frame-forwarding/fuzz/corpus-gen.cc b/apps/desktop/tests/frame-forwarding/fuzz/corpus-gen.cc new file mode 100644 index 0000000000..13be538a96 --- /dev/null +++ b/apps/desktop/tests/frame-forwarding/fuzz/corpus-gen.cc @@ -0,0 +1,186 @@ +/** + * Write the seed corpus of the frame-forwarding wire parser with the production encoder. + * + * Usage: `corpus-gen [canonical|extras]` + * + * `canonical` writes one legal packet of each kind, unpadded as a Windows pipe message. `extras` writes the seeds that + * are too large or too specific for the checked-in corpus: a protocol-1 hello that only the version check reads, a + * header-only hello, a message whose text fills the capacity without a terminator, and the Mach-padded form of seeds + * whose text is not already a multiple of 4 bytes. + */ +#include +#include +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#include +#else +#include +#endif + +#include "transport.cc" + +using namespace dsh_frame_forwarding; + +namespace { + +void make_directory(const std::string& path) { +#if defined(_WIN32) + _mkdir(path.c_str()); +#else + mkdir(path.c_str(), 0755); +#endif +} + +/** Write `packet` as a wire message; Mach pads the text to a multiple of 4 bytes with zeros. */ +bool write_packet(const std::string& directory, const std::string& name, const Packet& packet, bool padded) { + WireHeader wire; + const uint32_t text_size = encode_header(packet, wire); + const size_t aligned = padded ? (static_cast(text_size) + 3u) & ~size_t{3} : text_size; + std::vector bytes(sizeof(WireHeader) + aligned, 0); + std::memcpy(bytes.data(), &wire, sizeof(wire)); + std::memcpy(bytes.data() + sizeof(WireHeader), packet.text, text_size); + const std::string path = directory + "/" + name; + auto* file = std::fopen(path.c_str(), "wb"); + if (!file) { std::fprintf(stderr, "corpus-gen: cannot write %s\n", path.c_str()); return false; } + const bool written = std::fwrite(bytes.data(), 1, bytes.size(), file) == bytes.size(); + std::fclose(file); + if (!written) std::fprintf(stderr, "corpus-gen: short write to %s\n", path.c_str()); + return written; +} + +void append(const std::string& directory, const std::string& name, const Packet& packet, bool padded) { + if (!write_packet(directory, name, packet, padded)) std::exit(1); +} + +Packet make_hello() { + Packet packet; + packet.kind = hello; + packet.max_frames = hello_capabilities; + std::memset(packet.token, 'k', sizeof(packet.token) - 1); + std::snprintf(packet.text, sizeof(packet.text), "d3d11:0:1234"); + return packet; +} + +void write_canonical(const std::string& directory) { + append(directory, "hello.bin", make_hello(), false); + + Packet ready; + ready.kind = dsh_frame_forwarding::ready; + ready.max_frames = 3; + ready.max_bytes = 64ull << 20; + ready.stride = hello_capabilities; + append(directory, "ready.bin", ready, false); + + Packet frame; + frame.kind = dsh_frame_forwarding::frame; + frame.frame_id = 1; + frame.width = 800; frame.height = 600; frame.stride = 3200; + frame.max_frames = frame_replaceable; + frame.resource = 0x1234; + append(directory, "frame.bin", frame, false); + + Packet release; + release.kind = dsh_frame_forwarding::release; + release.frame_id = 1; + append(directory, "release.bin", release, false); + + Packet message; + message.kind = dsh_frame_forwarding::message; + std::snprintf(message.text, sizeof(message.text), "{\"n\":1}"); + append(directory, "message.bin", message, false); + + Packet goodbye; + goodbye.kind = dsh_frame_forwarding::goodbye; + std::snprintf(goodbye.text, sizeof(goodbye.text), "%s", reject_busy); + append(directory, "goodbye.bin", goodbye, false); + + Packet allocate; + allocate.kind = dsh_frame_forwarding::allocate; + allocate.allocation_id = 1; + allocate.max_bytes = 64ull << 20; + allocate.width = 800; allocate.height = 600; + append(directory, "allocate.bin", allocate, false); + + Packet allocated; + allocated.kind = dsh_frame_forwarding::allocated; + allocated.allocation_id = 1; + append(directory, "allocated.bin", allocated, false); + + Packet deallocate; + deallocate.kind = dsh_frame_forwarding::deallocate; + deallocate.allocation_id = 1; + append(directory, "deallocate.bin", deallocate, false); +} + +/** Write a raw seed, such as the credential text the endpoint parser reads. */ +void write_bytes(const std::string& directory, const std::string& name, const std::string& bytes) { + const std::string path = directory + "/" + name; + auto* file = std::fopen(path.c_str(), "wb"); + if (!file) { std::fprintf(stderr, "corpus-gen: cannot write %s\n", path.c_str()); std::exit(1); } + const bool written = std::fwrite(bytes.data(), 1, bytes.size(), file) == bytes.size(); + std::fclose(file); + if (!written) { std::fprintf(stderr, "corpus-gen: short write to %s\n", path.c_str()); std::exit(1); } +} + +/** Write `size` bytes of a header prefix, which is all decode_packet reads of a foreign-version hello. */ +void write_prefix(const std::string& directory, const std::string& name, uint32_t version) { + const uint32_t prefix[3] = {magic, version, hello}; + const std::string path = directory + "/" + name; + auto* file = std::fopen(path.c_str(), "wb"); + if (!file) { std::fprintf(stderr, "corpus-gen: cannot write %s\n", path.c_str()); std::exit(1); } + const bool written = std::fwrite(prefix, 1, sizeof(prefix), file) == sizeof(prefix); + std::fclose(file); + if (!written) { std::fprintf(stderr, "corpus-gen: short write to %s\n", path.c_str()); std::exit(1); } +} + +void write_extras(const std::string& directory) { + // A protocol-1 hello: decode reads only marker, version, and kind so the receiver can refuse it by version. + write_prefix(directory, "legacy-hello-v1.bin", 1); + // A current-version hello that stops before the header: the version check does not apply, so it is refused. + write_prefix(directory, "hello-truncated.bin", DSH_FRAME_FORWARDING_PROTOCOL_VERSION); + + // A message whose text has no terminator: the sender sends it whole and the receiver refuses it. + Packet capacity; + capacity.kind = message; + std::memset(capacity.text, 'a', sizeof(capacity.text)); + append(directory, "message-capacity.bin", capacity, false); + + // Mach pads a text that is not a multiple of 4 bytes; seed both conventions. + Packet odd_message; + odd_message.kind = message; + std::snprintf(odd_message.text, sizeof(odd_message.text), "{\"n\":12}"); + append(directory, "message.padded.bin", odd_message, true); + Packet odd_goodbye; + odd_goodbye.kind = goodbye; + std::snprintf(odd_goodbye.text, sizeof(odd_goodbye.text), "channel-busy!"); + append(directory, "goodbye.padded.bin", odd_goodbye, true); + append(directory, "hello.padded.bin", make_hello(), true); + + // Credentials the endpoint parser accepts, one it must refuse, and connection identifiers the handshake parses. + const std::string secret(64, 'k'); + write_bytes(directory, "credential-valid.bin", "1|4321|" + secret + "|frame-forwarding"); + write_bytes(directory, "credential-short-token.bin", "1|4321|" + secret.substr(1) + "|frame-forwarding"); + write_bytes(directory, "connection-token.bin", "42"); + write_bytes(directory, "connection-token-limit.bin", "9007199254740991"); +} + +} // namespace + +int main(int argc, char** argv) { + if (argc < 2 || argc > 3) { + std::fprintf(stderr, "usage: corpus-gen [canonical|extras]\n"); + return 2; + } + const std::string directory = argv[1]; + const std::string mode = argc == 3 ? argv[2] : "canonical"; + make_directory(directory); + if (mode == "canonical") write_canonical(directory); + else if (mode == "extras") write_extras(directory); + else { std::fprintf(stderr, "corpus-gen: unknown mode %s\n", mode.c_str()); return 2; } + return 0; +} diff --git a/apps/desktop/tests/frame-forwarding/fuzz/corpus/allocate.bin b/apps/desktop/tests/frame-forwarding/fuzz/corpus/allocate.bin new file mode 100644 index 0000000000..9749e20155 Binary files /dev/null and b/apps/desktop/tests/frame-forwarding/fuzz/corpus/allocate.bin differ diff --git a/apps/desktop/tests/frame-forwarding/fuzz/corpus/allocated.bin b/apps/desktop/tests/frame-forwarding/fuzz/corpus/allocated.bin new file mode 100644 index 0000000000..98de722331 Binary files /dev/null and b/apps/desktop/tests/frame-forwarding/fuzz/corpus/allocated.bin differ diff --git a/apps/desktop/tests/frame-forwarding/fuzz/corpus/deallocate.bin b/apps/desktop/tests/frame-forwarding/fuzz/corpus/deallocate.bin new file mode 100644 index 0000000000..39aa650255 Binary files /dev/null and b/apps/desktop/tests/frame-forwarding/fuzz/corpus/deallocate.bin differ diff --git a/apps/desktop/tests/frame-forwarding/fuzz/corpus/frame.bin b/apps/desktop/tests/frame-forwarding/fuzz/corpus/frame.bin new file mode 100644 index 0000000000..aa9ab433b9 Binary files /dev/null and b/apps/desktop/tests/frame-forwarding/fuzz/corpus/frame.bin differ diff --git a/apps/desktop/tests/frame-forwarding/fuzz/corpus/goodbye.bin b/apps/desktop/tests/frame-forwarding/fuzz/corpus/goodbye.bin new file mode 100644 index 0000000000..a78b1931b1 Binary files /dev/null and b/apps/desktop/tests/frame-forwarding/fuzz/corpus/goodbye.bin differ diff --git a/apps/desktop/tests/frame-forwarding/fuzz/corpus/hello.bin b/apps/desktop/tests/frame-forwarding/fuzz/corpus/hello.bin new file mode 100644 index 0000000000..5b9071ce91 Binary files /dev/null and b/apps/desktop/tests/frame-forwarding/fuzz/corpus/hello.bin differ diff --git a/apps/desktop/tests/frame-forwarding/fuzz/corpus/message.bin b/apps/desktop/tests/frame-forwarding/fuzz/corpus/message.bin new file mode 100644 index 0000000000..ed003b8a46 Binary files /dev/null and b/apps/desktop/tests/frame-forwarding/fuzz/corpus/message.bin differ diff --git a/apps/desktop/tests/frame-forwarding/fuzz/corpus/ready.bin b/apps/desktop/tests/frame-forwarding/fuzz/corpus/ready.bin new file mode 100644 index 0000000000..b8744826fe Binary files /dev/null and b/apps/desktop/tests/frame-forwarding/fuzz/corpus/ready.bin differ diff --git a/apps/desktop/tests/frame-forwarding/fuzz/corpus/release.bin b/apps/desktop/tests/frame-forwarding/fuzz/corpus/release.bin new file mode 100644 index 0000000000..03816a2904 Binary files /dev/null and b/apps/desktop/tests/frame-forwarding/fuzz/corpus/release.bin differ diff --git a/apps/desktop/tests/frame-forwarding/fuzz/endpoint-fuzzer.cc b/apps/desktop/tests/frame-forwarding/fuzz/endpoint-fuzzer.cc new file mode 100644 index 0000000000..204b029d74 --- /dev/null +++ b/apps/desktop/tests/frame-forwarding/fuzz/endpoint-fuzzer.cc @@ -0,0 +1,145 @@ +/** + * libFuzzer harness for the frame-forwarding trust establishment text paths. + * + * It mutates the three parsers that run before any pixel or handle crosses a process boundary: + * + * - `parse_endpoint` over a TX credential, which must either throw for an unusable credential or return an endpoint + * that survives being re-encoded into the `1|||` form and parsed again; + * - `parse_connection` over a 65-byte received token, which must either refuse it or return a safe integer that its own + * decimal form parses back to; + * - the receiver's stamping of `Channel::send` together with the producer's `parse_connection`, which must agree on + * every connection identifier the receiver can assign. + * + * Rejecting malformed input by throwing is the documented behaviour of `parse_endpoint`; the harness catches it. A + * violated check aborts with the input in hex, and libFuzzer records it as a crash artifact. + */ +#include +#include +#include +#include +#include +#include +#include + +#include "transport.cc" + +using namespace dsh_frame_forwarding; + +namespace { + +/** Largest connection identifier the protocol accepts, matching the largest exactly representable JavaScript integer. */ +constexpr uint64_t largest_connection = 9007199254740991ULL; + +[[noreturn]] void fail(const char* check, const char* detail, const uint8_t* data, size_t size) { + constexpr size_t shown = 4096; + std::fprintf(stderr, "\n[ff-fuzz] %s FAILED: %s\n[ff-fuzz] input_size=%zu input_hex=", check, detail, size); + for (size_t index = 0; index < size && index < shown; ++index) std::fprintf(stderr, "%02x", data[index]); + std::fprintf(stderr, "%s\n", size > shown ? "..." : ""); + std::fflush(stderr); + std::abort(); +} + +/** Stands in for a producer or receiver channel and keeps the token `Channel::send` stamped into the packet. */ +class StampingChannel final : public Channel { + public: + char token[65] = {}; + int receive_packet(Received&, uint32_t) override { return 0; } + bool send_packet(const Packet& packet, uintptr_t) override { std::memcpy(token, packet.token, sizeof(token)); return true; } + void interrupt() override {} + uint32_t peer_pid() const override { return 0; } +}; + +/** The packet a bound channel stamps; it carries no token of its own. */ +Packet unstamped_packet; + +void check_endpoint(const uint8_t* data, size_t size) { + const std::string value(reinterpret_cast(data), size); + Endpoint endpoint; + try { + endpoint = parse_endpoint(value); + } catch (const std::exception&) { + // A credential the receiver cannot use is refused by throwing, before any channel exists. + return; + } + // Whatever the parser accepted must be a usable endpoint, because the receiver publishes it and the producer parses + // it back from the same text. + if (endpoint.pid == 0 || endpoint.token.size() != 64 || endpoint.name.empty() || endpoint.name.size() > 200) + fail("parse_endpoint", "accepted an endpoint the protocol cannot carry", data, size); + // The pid field is decimal digits only on every platform: no sign, no whitespace, and no wrap through a 32-bit + // `unsigned long`. Leading zeros are accepted. + const auto first = value.find('|'), second = value.find('|', first + 1); + const std::string pid_text = value.substr(first + 1, second - first - 1); + if (pid_text.empty() || pid_text.find_first_not_of("0123456789") != std::string::npos + || std::stoull(pid_text) != endpoint.pid) + fail("parse_endpoint", "accepted a pid field that is not the decimal pid", data, size); + const std::string encoded = + "1|" + std::to_string(endpoint.pid) + "|" + endpoint.token + "|" + endpoint.name; + try { + const Endpoint again = parse_endpoint(encoded); + if (again.pid != endpoint.pid || again.token != endpoint.token || again.name != endpoint.name) + fail("parse_endpoint", "endpoint fields differ after re-encoding", data, size); + } catch (const std::exception&) { + fail("parse_endpoint", "an accepted endpoint no longer parses after re-encoding", data, size); + } +} + +void check_connection(const uint8_t* data, size_t size) { + char token[65] = {}; + std::memcpy(token, data, size < sizeof(token) ? size : sizeof(token)); + const uint64_t connection = parse_connection(token); + if (!connection) return; + if (connection > largest_connection) + fail("parse_connection", "accepted an identifier above the exact-integer limit", data, size); + char encoded[65] = {}; + std::snprintf(encoded, sizeof(encoded), "%llu", static_cast(connection)); + if (parse_connection(encoded) != connection) + fail("parse_connection", "an accepted identifier does not parse back from its decimal form", data, size); +} + +void check_stamped_connection(const uint8_t* data, size_t size) { + uint64_t connection = 0; + std::memcpy(&connection, data, size < sizeof(connection) ? size : sizeof(connection)); + static StampingChannel channel; + std::memset(channel.token, 0, sizeof(channel.token)); + channel.bind_connection(connection); + if (!channel.send(unstamped_packet)) fail("Channel::send", "refused a packet on a bound connection", data, size); + // A bound channel stamps the identifier into the token the producer parses back; an unbound one stamps nothing. + const uint64_t parsed = parse_connection(channel.token); + const uint64_t expected = connection >= 1 && connection <= largest_connection ? connection : 0; + if (parsed != expected) + fail("Channel::send", "the stamped connection identifier does not parse back", data, size); +} + +} // namespace + +/** + * Check fixed `parse_endpoint` cases once per run, so the sign, whitespace, and 32-bit range rules hold as a + * deterministic regression on both platforms before any mutation starts. + */ +extern "C" int LLVMFuzzerInitialize(int*, char***) { + const std::string token(64, 'k'); + const struct { const char* pid; uint32_t expected; } cases[] = { + {"5", 5}, {"007", 7}, {"4294967295", 4294967295u}, + {"0", 0}, {"-5", 0}, {"+7", 0}, {" 5", 0}, {"5 ", 0}, {"", 0}, {"4294967296", 0}, {"-4294967295", 0}, + {"18446744073709551621", 0}, + }; + for (const auto& entry : cases) { + const std::string credential = std::string("1|") + entry.pid + "|" + token + "|x"; + uint32_t pid = 0; + try { pid = parse_endpoint(credential).pid; } catch (const std::exception&) { pid = 0; } + if (pid != entry.expected) { + std::fprintf(stderr, "\n[ff-fuzz] parse_endpoint FAILED: pid field \"%s\" gave %u, expected %u\n", entry.pid, pid, entry.expected); + std::fflush(stderr); + std::abort(); + } + } + return 0; +} + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + if (size == 0) return 0; + check_endpoint(data, size); + check_connection(data, size); + check_stamped_connection(data, size); + return 0; +} diff --git a/apps/desktop/tests/frame-forwarding/fuzz/packet-fuzzer.cc b/apps/desktop/tests/frame-forwarding/fuzz/packet-fuzzer.cc new file mode 100644 index 0000000000..5583ef35de --- /dev/null +++ b/apps/desktop/tests/frame-forwarding/fuzz/packet-fuzzer.cc @@ -0,0 +1,99 @@ +/** + * libFuzzer harness for the frame-forwarding v2 wire parser. + * + * The harness includes the production `transport.cc` as a unity build so that the file-local `decode_packet` and + * `encode_header` are reachable without changing production code. It parses every input twice, once as a Windows pipe + * message (`padded=false`) and once as a macOS Mach message (`padded=true`), then checks the parser's contract: + * + * - a decoded packet must re-encode into a message that decodes to the same marker, version, kind, geometry, frame and + * allocation fields, token, and text, and whose text is NUL-terminated inside the capacity unless it fills it; + * - both padding conventions must agree on every field when both accept the same bytes, because a producer's bytes + * reach one receiver over a pipe and another over Mach. + * + * A violated check aborts with the input in hex; libFuzzer records it as a crash artifact. Reusable packet buffers + * mirror the receiver, which decodes into one `Received` for the life of a connection. + */ +#include +#include +#include +#include +#include +#include + +#include "transport.cc" + +using namespace dsh_frame_forwarding; + +namespace { + +/** One decoded packet per padding convention, plus the re-decoded packet of the round-trip check. */ +Packet unpadded_packet, padded_packet, roundtrip_packet; + +[[noreturn]] void fail(const char* check, const char* detail, const uint8_t* data, size_t size) { + constexpr size_t shown = 4096; + std::fprintf(stderr, "\n[ff-fuzz] %s FAILED: %s\n[ff-fuzz] input_size=%zu input_hex=", check, detail, size); + for (size_t index = 0; index < size && index < shown; ++index) std::fprintf(stderr, "%02x", data[index]); + std::fprintf(stderr, "%s\n", size > shown ? "..." : ""); + std::fflush(stderr); + std::abort(); +} + +bool same_fields(const Packet& left, const Packet& right) { + return left.marker == right.marker && left.version == right.version && left.kind == right.kind && + left.width == right.width && left.height == right.height && left.stride == right.stride && + left.max_frames == right.max_frames && left.frame_id == right.frame_id && + left.allocation_id == right.allocation_id && left.max_bytes == right.max_bytes && left.resource == right.resource; +} + +/** Compare two packet texts the way both peers read them: as a NUL-terminated string, or whole when unterminated. */ +bool same_text(const Packet& left, const Packet& right) { + const auto* left_end = static_cast(std::memchr(left.text, 0, sizeof(left.text))); + const auto* right_end = static_cast(std::memchr(right.text, 0, sizeof(right.text))); + if (!left_end || !right_end) { + return !left_end && !right_end && std::memcmp(left.text, right.text, sizeof(left.text)) == 0; + } + const size_t left_size = static_cast(left_end - left.text), right_size = static_cast(right_end - right.text); + return left_size == right_size && std::memcmp(left.text, right.text, left_size) == 0; +} + +/** + * Re-encode a decoded packet and decode it again. + * @param padded Whether the peer's message padded the text to a multiple of 4 bytes, as Mach does. + */ +void check_roundtrip(const Packet& packet, bool padded, const uint8_t* data, size_t size) { + WireHeader wire; + const uint32_t text_size = encode_header(packet, wire); + if (text_size > DSH_FRAME_FORWARDING_TEXT_CAPACITY || wire.text_size != text_size) + fail("roundtrip", "encode_header reports an impossible text size", data, size); + const size_t aligned = padded ? (static_cast(text_size) + 3u) & ~size_t{3} : text_size; + std::vector rebuilt(sizeof(WireHeader) + aligned, 0); + std::memcpy(rebuilt.data(), &wire, sizeof(wire)); + std::memcpy(rebuilt.data() + sizeof(WireHeader), packet.text, text_size); + if (!decode_packet(rebuilt.data(), rebuilt.size(), padded, roundtrip_packet)) + fail("roundtrip", "a re-encoded packet is refused", data, size); + if (!same_fields(packet, roundtrip_packet)) + fail("roundtrip", "packet fields differ after re-encoding", data, size); + if (std::memcmp(packet.token, roundtrip_packet.token, sizeof(packet.token)) != 0) + fail("roundtrip", "token differs after re-encoding", data, size); + if (!same_text(packet, roundtrip_packet)) fail("roundtrip", "text differs after re-encoding", data, size); + // The text a receiver reads must end inside the buffer, unless the sender filled it without a terminator, which the + // receiver refuses; decode_packet leaves exactly that case unterminated. + if (text_size < DSH_FRAME_FORWARDING_TEXT_CAPACITY && roundtrip_packet.text[text_size] != '\0') + fail("roundtrip", "text is not terminated at its reported size", data, size); +} + +} // namespace + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + if (size == 0) return 0; + const auto* bytes = reinterpret_cast(data); + const bool unpadded = decode_packet(bytes, size, false, unpadded_packet); + const bool padded = decode_packet(bytes, size, true, padded_packet); + if (unpadded && padded && (!same_fields(unpadded_packet, padded_packet) || + std::memcmp(unpadded_packet.token, padded_packet.token, sizeof(unpadded_packet.token)) != 0 || + !same_text(unpadded_packet, padded_packet))) + fail("padding", "pipe and Mach decodes of the same bytes differ", data, size); + if (unpadded) check_roundtrip(unpadded_packet, false, data, size); + if (padded) check_roundtrip(padded_packet, true, data, size); + return 0; +} diff --git a/apps/desktop/tests/frame-forwarding/fuzz/run-macos.sh b/apps/desktop/tests/frame-forwarding/fuzz/run-macos.sh new file mode 100755 index 0000000000..fac8935fde --- /dev/null +++ b/apps/desktop/tests/frame-forwarding/fuzz/run-macos.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# Build and run the frame-forwarding fuzz targets on macOS with libFuzzer, AddressSanitizer, and UndefinedBehaviorSanitizer. +# +# Apple clang ships no libFuzzer, so the script uses Homebrew LLVM when it is installed. It compiles against a native +# source snapshot (the directory holding transport.cc), never against a working tree, so a fuzz run is unaffected by +# edits in flight. Crashes, generated corpora, and logs stay under the work directory. +# +# Usage: +# ./run-macos.sh --native --work [--max-total-time 600] [--build|--run] +# +# Passing neither --build nor --run does both. + +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +native_dir="" +work_dir="${TMPDIR:-/tmp}/dsh-frame-forwarding-fuzz/work" +corpus_dir="$here/corpus" +targets="packet endpoint" +max_total_time=600 +do_build=0 +do_run=0 +cxx="${CXX:-}" + +usage() { + sed -n '2,12p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//' +} + +while [ "$#" -gt 0 ]; do + case "$1" in + --native) native_dir="$2"; shift 2 ;; + --work) work_dir="$2"; shift 2 ;; + --corpus) corpus_dir="$2"; shift 2 ;; + --targets) targets="$2"; shift 2 ;; + --max-total-time) max_total_time="$2"; shift 2 ;; + --build) do_build=1; shift ;; + --run) do_run=1; shift ;; + --help|-h) usage; exit 0 ;; + *) echo "run-macos.sh: unknown argument $1" >&2; exit 2 ;; + esac +done + +if [ -z "$native_dir" ]; then + echo "run-macos.sh: --native is required" >&2 + exit 2 +fi +if [ ! -f "$native_dir/transport.cc" ]; then + echo "run-macos.sh: $native_dir does not hold transport.cc" >&2 + exit 2 +fi +if [ -z "$cxx" ]; then + cxx=clang++ + if [ -x /opt/homebrew/opt/llvm/bin/clang++ ]; then + cxx=/opt/homebrew/opt/llvm/bin/clang++ + fi +fi +if [ "$do_build" -eq 0 ] && [ "$do_run" -eq 0 ]; then do_build=1; do_run=1; fi +mkdir -p "$work_dir" + +# IOSurface and CoreFoundation hold the producer frames, and these sources take the producer's audit token from libbsm. +frameworks=(-framework IOSurface -framework CoreFoundation -lbsm) +common=(-std=c++17 -g -O1 -I"$native_dir") + +if [ "$do_build" -eq 1 ]; then + echo "building corpus-gen" + "$cxx" "${common[@]}" -O2 "$here/corpus-gen.cc" -o "$work_dir/corpus-gen" "${frameworks[@]}" + for target in $targets; do + echo "building $target-fuzzer" + "$cxx" "${common[@]}" -fsanitize=fuzzer,address,undefined -fno-sanitize-recover=undefined \ + "$here/$target-fuzzer.cc" -o "$work_dir/$target-fuzzer" "${frameworks[@]}" + done +fi + +if [ "$do_run" -eq 1 ]; then + mkdir -p "$work_dir/logs" + for target in $targets; do + # Each target keeps its own corpus: a wire packet is meaningless to the credential parser and the other way round. + corpus="$work_dir/corpus-$target" + mkdir -p "$corpus" + # The checked-in seeds plus the large, Mach-padded, and credential seeds the repository does not carry. + find "$corpus_dir" -name '*.bin' -exec cp {} "$corpus" \; 2>/dev/null || true + "$work_dir/corpus-gen" "$corpus" extras + max_len=20000 + if [ "$target" = endpoint ]; then max_len=4096; fi + artifacts="$work_dir/artifacts-$target" + mkdir -p "$artifacts" + echo "fuzzing $target for $max_total_time s; log $work_dir/logs/$target-fuzzer.log" + "$work_dir/$target-fuzzer" "-max_total_time=$max_total_time" -timeout=10 -rss_limit_mb=2048 \ + "-max_len=$max_len" -print_final_stats=1 "-artifact_prefix=$artifacts/" "$corpus" 2>&1 \ + | tee "$work_dir/logs/$target-fuzzer.log" + done +fi diff --git a/apps/desktop/tests/frame-forwarding/fuzz/run-windows.ps1 b/apps/desktop/tests/frame-forwarding/fuzz/run-windows.ps1 new file mode 100644 index 0000000000..4b02093faa --- /dev/null +++ b/apps/desktop/tests/frame-forwarding/fuzz/run-windows.ps1 @@ -0,0 +1,152 @@ +<# +.SYNOPSIS +Builds and runs the frame-forwarding native fuzz targets with MSVC AddressSanitizer and libFuzzer. + +.DESCRIPTION +Compiles the harnesses in this directory against a native source snapshot, never against the working tree, so a fuzz +run is unaffected by edits in flight. The snapshot is the directory that contains `transport.cc` and `transport.h`, for example an export of `git archive HEAD +packages/experimental/frame-forwarding/native`. + +`cl.exe` is not on PATH. The script locates `vcvarsall.bat`, builds through it, and puts the MSVC bin directory that +holds `clang_rt.asan_dynamic-x86_64.dll` on PATH for the runs. + +.PARAMETER NativeDir +Directory of the native source snapshot to compile. Required. + +.PARAMETER WorkDir +Directory for binaries, the generated corpus, crash artifacts, and logs. Defaults to `%TEMP%\dsh-frame-forwarding-fuzz\work`. + +.PARAMETER CorpusDir +Checked-in seed corpus merged into the generated corpus. Defaults to `corpus` beside this script. + +.PARAMETER Targets +Fuzz targets to handle: `packet`, `endpoint`, or both. Defaults to both. + +.PARAMETER MaxTotalTime +Seconds each fuzz target runs. Defaults to 600. + +.PARAMETER Build +Build only, or build before running. + +.PARAMETER Run +Run only, or build before running. Passing neither builds and runs. + +.EXAMPLE +.\run-windows.ps1 -NativeDir "$env:TEMP\dsh-frame-forwarding-fuzz\src\packages\experimental\frame-forwarding\native" -Build +#> +[CmdletBinding()] +param( + [Parameter(Mandatory = $true)][string]$NativeDir, + [string]$WorkDir = (Join-Path $env:TEMP 'dsh-frame-forwarding-fuzz\work'), + [string]$CorpusDir = (Join-Path $PSScriptRoot 'corpus'), + [ValidateSet('packet', 'endpoint')][string[]]$Targets = @('packet', 'endpoint'), + [int]$MaxTotalTime = 600, + [switch]$Build, + [switch]$Run, + [string]$VcVarsAll = '' +) + +$ErrorActionPreference = 'Stop' +Set-StrictMode -Version Latest + +# The longest input each target needs: a packet with a full text, or a credential built from a few hundred bytes. +$maxLengths = @{ packet = 20000; endpoint = 4096 } + +function Find-VcVarsAll { + if ($VcVarsAll) { + if (-not (Test-Path -LiteralPath $VcVarsAll)) { throw "vcvarsall.bat not found: $VcVarsAll" } + return $VcVarsAll + } + $vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe' + $roots = @() + if (Test-Path -LiteralPath $vswhere) { + $roots = @(& $vswhere -all -products * -property installationPath 2>$null) + } + $roots += @( + 'C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools', + 'C:\Program Files\Microsoft Visual Studio\2022\BuildTools', + 'C:\Program Files\Microsoft Visual Studio\2022\Community' + ) + foreach ($root in $roots) { + $candidate = Join-Path $root 'VC\Auxiliary\Build\vcvarsall.bat' + if (Test-Path -LiteralPath $candidate) { return $candidate } + } + throw 'vcvarsall.bat not found; pass -VcVarsAll with the Visual Studio developer environment script.' +} + +function Find-AsanRuntimeDirectory { + # vcvarsall.bat sits in \VC\Auxiliary\Build; the MSVC tools are under the same VC directory. + $vc = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $script:vcvars)) + $tools = Join-Path $vc 'Tools\MSVC' + if (-not (Test-Path -LiteralPath $tools)) { throw "MSVC tools directory not found: $tools" } + $directory = Get-ChildItem -LiteralPath $tools -Directory | + Sort-Object Name -Descending | + ForEach-Object { Join-Path $_.FullName 'bin\Hostx64\x64' } | + Where-Object { Test-Path -LiteralPath (Join-Path $_ 'clang_rt.asan_dynamic-x86_64.dll') } | + Select-Object -First 1 + if (-not $directory) { throw 'clang_rt.asan_dynamic-x86_64.dll not found under the MSVC tools directories.' } + return $directory +} + +# Run a command line inside the developer environment of vcvarsall.bat. +function Invoke-DeveloperCommand([string]$CommandLine) { + $batch = Join-Path $WorkDir 'invoke-developer-command.bat' + @( + '@echo off', + "cd /d `"$WorkDir`"", + "call `"$script:vcvars`" x64 >nul || exit /b 1", + $CommandLine + ) | Set-Content -LiteralPath $batch -Encoding ascii + & cmd.exe /c $batch + if ($LASTEXITCODE -ne 0) { throw "developer command failed ($LASTEXITCODE): $CommandLine" } +} + +function Build-Target([string]$Name, [string]$Source, [string]$Extra) { + $native = (Resolve-Path -LiteralPath $NativeDir).Path + $exe = Join-Path $WorkDir "$Name.exe" + Write-Host "building $Name" + Invoke-DeveloperCommand "cl /nologo /std:c++17 /O1 /Zi /EHsc /MD $Extra /D_WIN32_WINNT=0x0602 /I`"$native`" `"$Source`" /Fe:`"$exe`" /Fd:`"$WorkDir\$Name.pdb`" /Fo:`"$WorkDir\$Name.obj`" /link /DEBUG /INCREMENTAL:NO d3d11.lib dxgi.lib advapi32.lib bcrypt.lib" + return $exe +} + +# Each target keeps its own corpus: a wire packet is meaningless to the credential parser and the other way round. +function New-Corpus([string]$Target) { + $corpus = Join-Path $WorkDir "corpus-$Target" + New-Item -ItemType Directory -Force -Path $corpus | Out-Null + if (Test-Path -LiteralPath $CorpusDir) { + Copy-Item -Path (Join-Path $CorpusDir '*.bin') -Destination $corpus -Force -ErrorAction SilentlyContinue + } + $generator = Join-Path $WorkDir 'corpus-gen.exe' + & $generator $corpus 'extras' + if ($LASTEXITCODE -ne 0) { throw 'corpus-gen failed' } + return $corpus +} + +$script:vcvars = Find-VcVarsAll +New-Item -ItemType Directory -Force -Path $WorkDir | Out-Null +if (-not $Build -and -not $Run) { $Build = $true; $Run = $true } + +if ($Build) { + Build-Target 'corpus-gen' (Join-Path $PSScriptRoot 'corpus-gen.cc') '' | Out-Null + $sanitized = '/fsanitize=address /fsanitize=fuzzer' + foreach ($target in $Targets) { + Build-Target "$target-fuzzer" (Join-Path $PSScriptRoot "$target-fuzzer.cc") $sanitized | Out-Null + } +} + +if ($Run) { + $env:PATH = "$(Find-AsanRuntimeDirectory);$env:PATH" + $logs = Join-Path $WorkDir 'logs' + New-Item -ItemType Directory -Force -Path $logs | Out-Null + foreach ($target in $Targets) { + $corpus = New-Corpus $target + $artifacts = Join-Path $WorkDir "artifacts-$target" + New-Item -ItemType Directory -Force -Path $artifacts | Out-Null + $log = Join-Path $logs "$target-fuzzer.log" + Write-Host "fuzzing $target for $MaxTotalTime s; log $log" + & (Join-Path $WorkDir "$target-fuzzer.exe") ` + "-max_total_time=$MaxTotalTime" '-timeout=10' '-rss_limit_mb=2048' "-max_len=$($maxLengths[$target])" ` + '-print_final_stats=1' "-artifact_prefix=$artifacts/" $corpus 2>&1 | Tee-Object -FilePath $log + if ($LASTEXITCODE -ne 0) { Write-Warning "$target fuzzer exited with $LASTEXITCODE; see $artifacts" } + } +} diff --git a/apps/desktop/tests/host-process.spec.ts b/apps/desktop/tests/host-process.spec.ts index f2490f4b48..dc32679417 100644 --- a/apps/desktop/tests/host-process.spec.ts +++ b/apps/desktop/tests/host-process.spec.ts @@ -399,15 +399,18 @@ process.send({ type: 'starting', runId: randomUUID() }) expect(failure).not.toHaveBeenCalled() }) - it('passes external dependencies and package-manager paths to the Host', async () => { + it('passes external dependencies, package-manager paths and the named receiver path to the Host', async () => { const runtime = projectWithHost(HTTP_HOST.replace('runtime: process.argv[2]', - 'pnpm: process.argv[5], nodeBin: process.argv[6], primaryRuntime: process.argv[4], runtime: process.argv[2]')) + 'receiverArgs: process.argv.slice(7), pnpm: process.argv[5], nodeBin: process.argv[6], primaryRuntime: process.argv[4], runtime: process.argv[2]')) const primaryRuntime = join(runtime, 'external-primary-runtime') const host = new DesktopHostProcess(process.execPath, runtime, runtime, undefined, process.env, undefined, primaryRuntime, { pnpm: join(runtime, 'pnpm.mjs'), nodeBin: join(runtime, 'bin') }) hosts.push(host) - const { url } = await host.start() - expect(await (await fetch(url)).json()).toMatchObject({ primaryRuntime, pnpm: join(runtime, 'pnpm.mjs'), nodeBin: join(runtime, 'bin') }) + const receiverPath = join(runtime, 'Desktop resources', 'frame-forwarding.node') + const { url } = await host.start(receiverPath) + expect(await (await fetch(url)).json()).toMatchObject({ + primaryRuntime, pnpm: join(runtime, 'pnpm.mjs'), nodeBin: join(runtime, 'bin'), receiverArgs: ['--frame-receiver-path', receiverPath], + }) }) it('reports a fatal event after readiness once', async () => { diff --git a/apps/desktop/tests/main-startup.spec.ts b/apps/desktop/tests/main-startup.spec.ts index e5f21086ce..8e4a4ca3f1 100644 --- a/apps/desktop/tests/main-startup.spec.ts +++ b/apps/desktop/tests/main-startup.spec.ts @@ -3157,6 +3157,7 @@ describe('desktop main startup', () => { profile: 'desktop-test-profile', }) expect(harness.hosts[0]!.environment).not.toBe(process.env) + expect(harness.hosts[0]!.start).toHaveBeenCalledWith(join('desktop-test-resources', 'app.asar.unpacked', 'lib', 'native', 'win32-x64', 'frame-forwarding.node')) expect(harness.hosts[0]!.environment?.DSH_CLIENT_VERSION).toBe('1.2.3') expect(harness.hosts[0]!.environment?.DSH_TEST_LOGIN_SHELL).toBe('login') expect(console.warn).toHaveBeenCalledWith('desktop login shell: /account/shell failed (timeout)') @@ -3176,6 +3177,7 @@ describe('desktop main startup', () => { const project = join(harness.app.getAppPath(), '.desktop-build', 'development', 'project') expect(harness.hosts[0]).toMatchObject({ node: process.execPath, runtime: project, primaryRuntime: 'test-primary-runtime', profile: 'desktop-test-profile' }) + expect(harness.hosts[0]!.start).toHaveBeenCalledWith(join(harness.app.getAppPath(), 'lib', 'native', 'win32-x64', 'frame-forwarding.node')) expect(harness.applyRelease).toHaveBeenCalledOnce() harness.hosts[0]!.ready.resolve() await harness.navigated.promise diff --git a/apps/desktop/tests/native-package-builds.spec.ts b/apps/desktop/tests/native-package-builds.spec.ts index 1318e2462f..b7c3b2340a 100644 --- a/apps/desktop/tests/native-package-builds.spec.ts +++ b/apps/desktop/tests/native-package-builds.spec.ts @@ -1,8 +1,28 @@ -/** Native addon build environment and object-file architecture checks. */ +/** Desktop packaging builds and verifies the native addons runtime packages declare in `dsh.native`, knowing no package by name. */ +import { createHash } from 'node:crypto' import { existsSync } from 'node:fs' +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' import { join } from 'node:path' -import { describe, expect, it } from 'vitest' -import { matchingArchitecture, nativeBuildEnvironment, parseDeveloperEnvironment, vcvarsallTarget } from '../scripts/native-package-builds.mjs' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { + buildNativePackage, buildNativePackages, matchingArchitecture, nativeBuildEnvironment, nativePackageBuildAt, nativePackageBuilds, + parseDeveloperEnvironment, vcvarsallTarget, verifyNativePackages, +} from '../scripts/native-package-builds.mjs' + +const roots: string[] = [] +const targets = ['darwin-arm64', 'darwin-x64', 'win32-arm64', 'win32-x64'] as const +afterEach(async () => { + vi.unstubAllEnvs() + await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))) +}) +/** + * The fixture builds only run Node, so on Windows they present an MSVC environment already set up for `arch` instead + * of probing for a C++ toolchain of that architecture; the conditional test below covers the real probe. + */ +function toolchainFor(arch: string): void { + vi.stubEnv('VSCMD_ARG_TGT_ARCH', arch) +} function binaryFor(platform: string, arch: string): Buffer { const binary = Buffer.alloc(80) @@ -17,6 +37,133 @@ function binaryFor(platform: string, arch: string): Buffer { } return binary } +function split(name: string): { platform: string; arch: string } { + const [platform, arch] = name.split('-') as [string, string] + return { platform, arch } +} + +/** + * A runtime root with one declaring package, optionally nested under another package, whose build script writes the + * addon and its record for the requested architecture. + */ +async function runtime(options: { nested?: boolean; native?: unknown; failBuild?: boolean } = {}) { + const runtimeRoot = await mkdtemp(join(tmpdir(), 'native-package-builds-')) + roots.push(runtimeRoot) + const packageRoot = options.nested === true + ? join(runtimeRoot, 'node_modules', 'host', 'node_modules', '@deepseek-ai', 'dsh-addon-package') + : join(runtimeRoot, 'node_modules', '@deepseek-ai', 'dsh-addon-package') + await mkdir(join(packageRoot, 'native'), { recursive: true }) + if (options.nested === true) await writeFile(join(runtimeRoot, 'node_modules', 'host', 'package.json'), JSON.stringify({ name: 'host' })) + await mkdir(join(runtimeRoot, 'node_modules', 'plain'), { recursive: true }) + await writeFile(join(runtimeRoot, 'node_modules', 'plain', 'package.json'), JSON.stringify({ name: 'plain' })) + await mkdir(join(runtimeRoot, 'node_modules', '.bin'), { recursive: true }) + const native = options.native ?? { build: 'native/build.mjs', addons: ['native/out/{platform}-{arch}/addon.node'] } + await writeFile(join(packageRoot, 'package.json'), JSON.stringify({ name: '@deepseek-ai/dsh-addon-package', dsh: { native } })) + await writeFile(join(packageRoot, 'native', 'build.mjs'), ` + import { createHash } from 'node:crypto' + import { mkdirSync, writeFileSync } from 'node:fs' + if (${String(options.failBuild === true)}) process.exit(3) + const arch = process.argv[process.argv.indexOf('--arch') + 1] + const bytes = Buffer.alloc(80) + bytes.writeUInt32LE(0xfeedfacf, 0) + bytes.writeUInt32LE(arch === 'arm64' ? 0x100000c : 0x1000007, 4) + const directory = 'native/out/darwin-' + arch + mkdirSync(directory, { recursive: true }) + writeFileSync(directory + '/addon.node', bytes) + writeFileSync(directory + '/addon.json', JSON.stringify({ platform: 'darwin-' + arch, sha256: createHash('sha256').update(bytes).digest('hex') })) + writeFileSync(directory + '/headers.txt', process.env.DSH_NODE_API_HEADERS ?? '') + `) + return { runtimeRoot, packageRoot } +} + +async function writeAddon(packageRoot: string, name: string, binary = binaryFor(...Object.values(split(name)) as [string, string])) { + const directory = join(packageRoot, 'native', 'out', name) + await mkdir(directory, { recursive: true }) + await writeFile(join(directory, 'addon.node'), binary) + const record = { platform: name, sha256: createHash('sha256').update(binary).digest('hex') } + await writeFile(join(directory, 'addon.json'), JSON.stringify(record)) + return { directory, record } +} + +describe('discovery', () => { + it('finds declaring packages at the top level and nested under other packages, and skips the rest', async () => { + const top = await runtime() + expect(nativePackageBuilds(top.runtimeRoot)).toEqual([{ + name: '@deepseek-ai/dsh-addon-package', root: top.packageRoot, build: 'native/build.mjs', addons: ['native/out/{platform}-{arch}/addon.node'], + }]) + const nested = await runtime({ nested: true }) + expect(nativePackageBuilds(nested.runtimeRoot).map(declaration => declaration.root)).toEqual([nested.packageRoot]) + expect(nativePackageBuilds(join(tmpdir(), 'no-such-runtime'))).toEqual([]) + expect(nativePackageBuildAt(join(top.runtimeRoot, 'node_modules', 'plain'))).toBeUndefined() + expect(nativePackageBuildAt(join(top.runtimeRoot, 'missing'))).toBeUndefined() + }) + it('ignores the declaration of a package outside DeepSeek Harness and never runs its build', async () => { + const f = await runtime() + const foreign = join(f.runtimeRoot, 'node_modules', 'foreign') + await mkdir(foreign, { recursive: true }) + await writeFile(join(foreign, 'package.json'), JSON.stringify({ name: 'foreign', dsh: { native: { build: 'build.mjs', addons: ['a.node'] } } })) + await writeFile(join(foreign, 'build.mjs'), 'require(\'node:fs\').writeFileSync(\'ran\', \'\')') + const scoped = join(f.runtimeRoot, 'node_modules', '@deepseek-ai', 'libreoffice-kit') + await mkdir(scoped, { recursive: true }) + await writeFile(join(scoped, 'package.json'), JSON.stringify({ name: '@deepseek-ai/libreoffice-kit', dsh: { native: 'invalid' } })) + expect(nativePackageBuilds(f.runtimeRoot).map(declaration => declaration.name)).toEqual(['@deepseek-ai/dsh-addon-package']) + toolchainFor('arm64') + expect(buildNativePackages(f.runtimeRoot, 'arm64')).toEqual(['@deepseek-ai/dsh-addon-package']) + await expect(readFile(join(foreign, 'ran'))).rejects.toThrow('ENOENT') + }) + it.each([ + ['no object', 'native/build.mjs'], + ['an absolute build', { build: '/tmp/build.mjs', addons: ['a.node'] }], + ['an escaping build', { build: '../build.mjs', addons: ['a.node'] }], + ['no addons', { build: 'native/build.mjs', addons: [] }], + ['an addon that is not .node', { build: 'native/build.mjs', addons: ['native/a.dll'] }], + ])('rejects a declaration with %s', async (_name, native) => { + const f = await runtime({ native }) + expect(() => nativePackageBuilds(f.runtimeRoot)).toThrow('@deepseek-ai/dsh-addon-package declares an invalid dsh.native') + }) +}) + +describe('build environment', () => { + it('names the vcvarsall.bat target for native and cross builds', () => { + expect(vcvarsallTarget('x64', 'x64')).toBe('x64') + expect(vcvarsallTarget('x64', 'arm64')).toBe('x64_arm64') + expect(vcvarsallTarget('arm64', 'x64')).toBe('arm64_x64') + }) + it('reads the environment set prints after the marker, ignoring the vcvarsall.bat banner', () => { + const output = [ + '** Visual Studio 2022 Developer Command Prompt', 'BANNER=not environment', '--- dsh native build environment --- ', + 'Path=C:\\VS\\bin;C:\\Windows', 'VSCMD_ARG_TGT_ARCH=arm64', 'EMPTY=', 'not a variable', '', + ].join('\r\n') + expect(parseDeveloperEnvironment(output)).toEqual({ Path: 'C:\\VS\\bin;C:\\Windows', VSCMD_ARG_TGT_ARCH: 'arm64', EMPTY: '' }) + expect(() => parseDeveloperEnvironment('[ERROR:vcvarsall.bat] Invalid argument found')).toThrow('printed no environment') + }) + it.skipIf(process.platform === 'win32')('keeps the packaging environment outside Windows and names Desktop\'s Node-API headers', () => { + const { DSH_NODE_API_HEADERS: headers, ...rest } = nativeBuildEnvironment('arm64', { PATH: '/usr/bin' }) + expect(rest).toEqual({ PATH: '/usr/bin' }) + if (headers === undefined) throw new Error('DSH_NODE_API_HEADERS is unset') + expect(headers).toMatch(/node-api-headers$/u) + expect(existsSync(join(headers, 'include', 'node_api.h'))).toBe(true) + expect(existsSync(join(headers, 'def', 'node_api.def'))).toBe(true) + }) +}) + +describe('build', () => { + it('runs each declared build for the target architecture and leaves an addon packaging accepts', async () => { + const f = await runtime({ nested: true }) + toolchainFor('x64') + expect(buildNativePackages(f.runtimeRoot, 'x64')).toEqual(['@deepseek-ai/dsh-addon-package']) + const record = JSON.parse(await readFile(join(f.packageRoot, 'native', 'out', 'darwin-x64', 'addon.json'), 'utf8')) as { platform: string } + expect(record.platform).toBe('darwin-x64') + expect(await readFile(join(f.packageRoot, 'native', 'out', 'darwin-x64', 'headers.txt'), 'utf8')).toMatch(/node-api-headers$/u) + expect(() => { verifyNativePackages(f.runtimeRoot, { platform: 'darwin', arch: 'x64' }) }).not.toThrow() + }) + it('names the package whose build fails', async () => { + const f = await runtime({ failBuild: true }) + toolchainFor('arm64') + expect(() => buildNativePackages(f.runtimeRoot, 'arm64')).toThrow('@deepseek-ai/dsh-addon-package native build failed (3)') + expect(() => { buildNativePackage({ name: 'missing', root: f.runtimeRoot, build: 'nothing.mjs' }, 'arm64') }).toThrow('missing native build failed') + }) +}) const vswhere = join(process.env['ProgramFiles(x86)'] ?? '', 'Microsoft Visual Studio', 'Installer', 'vswhere.exe') @@ -50,6 +197,36 @@ describe('build environment', () => { }) describe('verification', () => { + it.each(targets)('accepts the built %s addon', async (name) => { + const f = await runtime() + await writeAddon(f.packageRoot, name) + expect(() => { verifyNativePackages(f.runtimeRoot, split(name)) }).not.toThrow() + }) + it('requires the addon of the packaged target and names the package that builds it', async () => { + const f = await runtime() + await writeAddon(f.packageRoot, 'darwin-arm64') + expect(() => { verifyNativePackages(f.runtimeRoot, { platform: 'darwin', arch: 'x64' }) }).toThrow('prepare:dsh builds @deepseek-ai/dsh-addon-package') + }) + it.each([ + ['a stale hash', { sha256: '0'.repeat(64) }], + ['another platform', { platform: 'darwin-x64' }], + ] as const)('rejects a build record from %s', async (_name, override) => { + const f = await runtime() + const { directory, record } = await writeAddon(f.packageRoot, 'darwin-arm64') + await writeFile(join(directory, 'addon.json'), JSON.stringify({ ...record, ...override })) + expect(() => { verifyNativePackages(f.runtimeRoot, { platform: 'darwin', arch: 'arm64' }) }).toThrow('differs from its build record') + }) + it('rejects an addon without a build record', async () => { + const f = await runtime() + const { directory } = await writeAddon(f.packageRoot, 'darwin-arm64') + await rm(join(directory, 'addon.json')) + expect(() => { verifyNativePackages(f.runtimeRoot, { platform: 'darwin', arch: 'arm64' }) }).toThrow('differs from its build record') + }) + it('rejects an addon for another CPU even when its directory and record name the target', async () => { + const f = await runtime() + await writeAddon(f.packageRoot, 'darwin-arm64', binaryFor('darwin', 'x64')) + expect(() => { verifyNativePackages(f.runtimeRoot, { platform: 'darwin', arch: 'arm64' }) }).toThrow('is not darwin-arm64') + }) it('recognizes only the target operating system object format', () => { expect(matchingArchitecture(binaryFor('darwin', 'arm64'), { platform: 'win32', arch: 'arm64' })).toBe(false) expect(matchingArchitecture(binaryFor('win32', 'x64'), { platform: 'darwin', arch: 'x64' })).toBe(false) diff --git a/apps/desktop/tests/preload-menu.client.spec.ts b/apps/desktop/tests/preload-menu.client.spec.ts index 945463638f..a106e827cf 100644 --- a/apps/desktop/tests/preload-menu.client.spec.ts +++ b/apps/desktop/tests/preload-menu.client.spec.ts @@ -141,3 +141,9 @@ it('restores a contenteditable selection before opening Edit with the keyboard', expect(document.getSelection()!.toString()).toBe('itable') await vi.waitFor(() => { expect(buttons[1]!.getAttribute('aria-expanded')).toBe('false') }) }) + +it('hides the caption menu when the document enters native fullscreen', () => { + menu = installWindowsMenu() + const style = document.querySelector('[data-windows-menu]')!.shadowRoot!.querySelector('style')! + expect(style.textContent).toContain(':host-context(html[data-fullscreen]) { display: none; }') +}) diff --git a/apps/desktop/tests/preload.e2e.ts b/apps/desktop/tests/preload.e2e.ts index 476fbb152c..337825b53b 100644 --- a/apps/desktop/tests/preload.e2e.ts +++ b/apps/desktop/tests/preload.e2e.ts @@ -76,6 +76,8 @@ describe.skipIf(!existsSync(preload('preload-app')))('built sandboxed Desktop pr expect(on.mock.calls.filter(([channel]) => channel === 'dsh-desktop:shared-texture')).toHaveLength(name === 'preload-app' ? 1 : 0) if (name === 'preload-app') { expect(Object.keys((exposed.get('dshDesktop') as { textures: object }).textures)).toEqual(['onFrame']) + // Frame forwarding offers fullscreen to plugins through the document's Fullscreen API; Desktop exposes no window control. + expect(exposed.get('dshDesktop')).not.toHaveProperty('window') const product = exposed.get('dshDesktop') as { deviceInfo(): Promise } invoke.mockResolvedValueOnce('platform=darwin; memory_gib=32.0') await expect(product.deviceInfo()).resolves.toBe('platform=darwin; memory_gib=32.0') diff --git a/apps/desktop/tests/shared-texture-runtime.spec.ts b/apps/desktop/tests/shared-texture-runtime.spec.ts index b28a5f00f3..8a9019f66f 100644 --- a/apps/desktop/tests/shared-texture-runtime.spec.ts +++ b/apps/desktop/tests/shared-texture-runtime.spec.ts @@ -29,18 +29,18 @@ function split(name: typeof targets[number]): { platform: string; arch: string } } describe('Desktop shared-texture addons', () => { - async function fixture(name: typeof targets[number] = 'darwin-arm64', binaries: Partial> = {}) { + async function fixture(name: typeof targets[number] = 'darwin-arm64', binaries: Partial> = {}) { const appDir = await mkdtemp(join(tmpdir(), 'shared-texture-addons-')) roots.push(appDir) const target = split(name) const directory = join(appDir, 'lib', 'native', name) await mkdir(directory, { recursive: true }) const records: Record = {} - for (const addon of ['hop', 'ingress'] as const) { + for (const addon of ['shared-texture-hop', 'shared-texture-ingress', 'frame-forwarding'] as const) { const bytes = binaries[addon] ?? binaryFor(target.platform, target.arch) - await writeFile(join(directory, `shared-texture-${addon}.node`), bytes) + await writeFile(join(directory, `${addon}.node`), bytes) records[addon] = { platform: name, sha256: createHash('sha256').update(bytes).digest('hex') } - await writeFile(join(directory, `shared-texture-${addon}.json`), JSON.stringify(records[addon])) + await writeFile(join(directory, `${addon}.json`), JSON.stringify(records[addon])) } return { appDir, directory, records, target } } @@ -53,10 +53,10 @@ describe('Desktop shared-texture addons', () => { const f = await fixture('darwin-arm64') await expect(verifySharedTextureAddons(f.appDir, { platform: 'darwin', arch: 'x64' })).rejects.toThrow('build:native --arch x64') }) - it.each([['darwin-arm64', 'ingress'], ['win32-x64', 'hop']] as const)('requires both addons on %s', async (name, addon) => { + it.each([['darwin-arm64', 'shared-texture-ingress'], ['win32-x64', 'shared-texture-hop'], ['win32-x64', 'frame-forwarding']] as const)('requires each addon on %s', async (name, addon) => { const f = await fixture(name) - await rm(join(f.directory, `shared-texture-${addon}.node`)) - await expect(verifySharedTextureAddons(f.appDir, f.target)).rejects.toThrow(`shared-texture-${addon}.node is missing`) + await rm(join(f.directory, `${addon}.node`)) + await expect(verifySharedTextureAddons(f.appDir, f.target)).rejects.toThrow(`${addon}.node is missing`) }) it('requires no addon where Desktop has no texture transport', async () => { const appDir = await mkdtemp(join(tmpdir(), 'shared-texture-addons-')) @@ -68,12 +68,12 @@ describe('Desktop shared-texture addons', () => { ['another platform', { platform: 'darwin-x64' }], ] as const)('rejects a build record from %s', async (_name, override) => { const f = await fixture() - await writeFile(join(f.directory, 'shared-texture-hop.json'), JSON.stringify({ ...f.records.hop, ...override })) + await writeFile(join(f.directory, 'shared-texture-hop.json'), JSON.stringify({ ...f.records['shared-texture-hop'], ...override })) await expect(verifySharedTextureAddons(f.appDir, f.target)).rejects.toThrow('differs from its build record') }) it.each([['darwin-arm64', 'darwin', 'x64'], ['win32-x64', 'win32', 'arm64']] as const)( 'rejects a %s addon for another CPU even when its directory and record name the target', async (name, platform, arch) => { - const f = await fixture(name, { ingress: binaryFor(platform, arch) }) + const f = await fixture(name, { 'shared-texture-ingress': binaryFor(platform, arch) }) await expect(verifySharedTextureAddons(f.appDir, f.target)).rejects.toThrow(`ingress addon is not ${name}`) }) }) diff --git a/apps/desktop/tests/shell-file-selection.spec.ts b/apps/desktop/tests/shell-file-selection.spec.ts index aeb0c40032..79b6522811 100644 --- a/apps/desktop/tests/shell-file-selection.spec.ts +++ b/apps/desktop/tests/shell-file-selection.spec.ts @@ -121,8 +121,8 @@ it.each([ const destination = join(resources, 'app') await mkdir(resources, { recursive: true }) const names = sharedTextureAddonNames(platform) - expect(names).toEqual(['shared-texture-hop', 'shared-texture-ingress']) - const paths = names.map(name => `lib/native/${platform}-${arch}/${name}.node`) + expect(names).toEqual(['shared-texture-hop', 'shared-texture-ingress', 'frame-forwarding']) + const paths = [...names.map(name => `lib/native/${platform}-${arch}/${name}.node`), `lib/native/${platform}-${arch}/frame-forwarding.json`] const desktopConfig = createElectronBuilderConfig({ DSH_DESKTOP_APP_ID: 'com.example.texture-files', DSH_DESKTOP_UNSIGNED: '1', DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN: 'https://policy.example.com', diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index 35fdac8e69..9f3c469b0b 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: ae2e3f6a59a9a7ee - zh: 9fcde04bb95424f4 + en: 20d2bcc6ee1ea353 + zh: daa830e26d32c640 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 829e4e29b1..3ae42e8d15 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -98,6 +98,7 @@ flowchart LR pkg_cua_mcp["cua-mcp"] pkg_shared_texture["shared-texture"] svc_sharedTexture["ctx.sharedTexture
Shared-texture presentation"] + pkg_frame_forwarding["frame-forwarding"] pkg_office_kit["office-kit"] svc_officeKit["ctx.officeKit
Office rendering, conversion, and recalculation"] pkg_client_ui_sidebar_documentpreview["client-ui-sidebar-documentpreview"] @@ -657,6 +658,7 @@ flowchart LR svc_sessions --> pkg_session_query_sqlite svc_sessions --> pkg_subagent svc_settings --> pkg_api_settings_controller + svc_sharedTexture --> pkg_frame_forwarding svc_shell --> pkg_hooks_claude_code svc_shell --> pkg_hooks_codex svc_shell --> pkg_tool_bash @@ -762,7 +764,7 @@ flowchart LR | `ctx.computerUse` | `seam` | [`computer-use`](../packages/computer-use/computer-use) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | - | One provider-owned name per service instance. Each provider also owns its model tools; the service has no common action API, runtime selection, or Session workflow lock. | | `ctx.cuaAccess` | `core` | [`cua`](../packages/experimental/cua) | - | [`cua`](../packages/experimental/cua) | - | The native provider owns application consent and cancellation; the optional Client page queries and changes those decisions through its Remote. | | `ctx.cuaPrograms` | `core` | [`cua`](../packages/experimental/cua) | - | [`cua-mcp`](../packages/experimental/cua-mcp) | - | The provider owns the retained cua_run_code runtime; a host without a model releases one Agent's environment and reads the configured screenshot request target through it. | -| `ctx.sharedTexture` | `seam` | [`shared-texture`](../packages/shared-texture/shared-texture) | - | - | - | Desktop Host implements the exclusive Host claim that submits GPU-backed frames to Desktop; the Client half of the package provides the Desktop preload bridge as the Client service. Consumers never touch Mach ports, Win32 handles, or Electron. | +| `ctx.sharedTexture` | `seam` | [`shared-texture`](../packages/shared-texture/shared-texture) | - | [`frame-forwarding`](../packages/experimental/frame-forwarding) | - | Desktop Host implements the exclusive Host claim that submits GPU-backed frames to Desktop; the Client half of the package provides the Desktop preload bridge as the Client service. Consumers never touch Mach ports, Win32 handles, or Electron. | | `ctx.officeKit` | `core` | [`office-kit`](../packages/document/office-kit) | - | [`client-ui-sidebar-documentpreview`](../packages/client/ui-sidebar-documentpreview), [`tool-document`](../packages/document/tool-document) | - | Authorized Office bytes are rendered as PDFs or images, converted, or recalculated on the Host using the declared native target engine, or Node WASM when no native target is declared. | | `ctx.attachments` | `seam` | [`attachment`](../packages/attachment/attachment) | [`attachment-local`](../packages/attachment/attachment-local) | [`api-session-controller`](../packages/api/session-controller), [`tool-fs`](../packages/fs/tool-fs), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-deepseek`](../packages/llm/llm-deepseek) | - | The host commits accepted images before session events; provider adapters resolve authorized durable references into provider-native content. | | `ctx.fileUploads` | `core` | [`client-file-upload`](../packages/client/file-upload) | - | [`api-session-controller`](../packages/api/session-controller) | - | Owns streaming intake, durable storage, and staged receipt lifetime; the Session controller binds receipts to accepted submissions. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index ca24e85bf0..d85da4f12a 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -100,6 +100,7 @@ flowchart LR pkg_cua_mcp["cua-mcp"] pkg_shared_texture["shared-texture"] svc_sharedTexture["ctx.sharedTexture
Shared-texture presentation"] + pkg_frame_forwarding["frame-forwarding"] pkg_office_kit["office-kit"] svc_officeKit["ctx.officeKit
Office rendering, conversion, and recalculation"] pkg_client_ui_sidebar_documentpreview["client-ui-sidebar-documentpreview"] @@ -659,6 +660,7 @@ flowchart LR svc_sessions --> pkg_session_query_sqlite svc_sessions --> pkg_subagent svc_settings --> pkg_api_settings_controller + svc_sharedTexture --> pkg_frame_forwarding svc_shell --> pkg_hooks_claude_code svc_shell --> pkg_hooks_codex svc_shell --> pkg_tool_bash @@ -764,7 +766,7 @@ flowchart LR | `ctx.computerUse` | `seam` | [`computer-use`](../packages/computer-use/computer-use) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | - | 每个服务实例只注册一个提供方自定的名称。各提供方也拥有自己的模型工具;服务不提供通用操作 API、运行时选择或 Session 流程锁。 | | `ctx.cuaAccess` | `core` | [`cua`](../packages/experimental/cua) | - | [`cua`](../packages/experimental/cua) | - | 原生 provider 负责应用授权和取消操作;可选的 Client 权限页面通过 Remote 查询和修改授权。 | | `ctx.cuaPrograms` | `core` | [`cua`](../packages/experimental/cua) | - | [`cua-mcp`](../packages/experimental/cua-mcp) | - | 提供方持有保留的 cua_run_code 运行时;没有模型的宿主通过它释放单个 Agent 的环境,并读取已配置的截图请求目标。 | -| `ctx.sharedTexture` | `seam` | [`shared-texture`](../packages/shared-texture/shared-texture) | - | - | - | Desktop Host 实现独占的 Host 认领,把基于 GPU 的帧提交给 Desktop;本包的 Client 半边把 Desktop preload 桥接提供为 Client 服务。使用方不接触 Mach 端口、Win32 句柄或 Electron。 | +| `ctx.sharedTexture` | `seam` | [`shared-texture`](../packages/shared-texture/shared-texture) | - | [`frame-forwarding`](../packages/experimental/frame-forwarding) | - | Desktop Host 实现独占的 Host 认领,把基于 GPU 的帧提交给 Desktop;本包的 Client 半边把 Desktop preload 桥接提供为 Client 服务。使用方不接触 Mach 端口、Win32 句柄或 Electron。 | | `ctx.officeKit` | `core` | [`office-kit`](../packages/document/office-kit) | - | [`client-ui-sidebar-documentpreview`](../packages/client/ui-sidebar-documentpreview), [`tool-document`](../packages/document/tool-document) | - | 已授权的 Office 字节在宿主上使用已声明的原生目标引擎渲染为 PDF 或图片、转换或重算;未声明原生目标时使用 Node WASM。 | | `ctx.attachments` | `seam` | [`attachment`](../packages/attachment/attachment) | [`attachment-local`](../packages/attachment/attachment-local) | [`api-session-controller`](../packages/api/session-controller), [`tool-fs`](../packages/fs/tool-fs), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-deepseek`](../packages/llm/llm-deepseek) | - | 宿主会在会话事件之前提交已接受的图片;提供方适配器将已授权的持久引用解析为提供方原生内容。 | | `ctx.fileUploads` | `core` | [`client-file-upload`](../packages/client/file-upload) | - | [`api-session-controller`](../packages/api/session-controller) | - | 负责流式接收、持久存储和暂存回执生命周期;Session Controller 将回执绑定到已接受的提交。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index e407d875cb..9e8dc07cee 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1989,6 +1989,43 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-frame-forwarding` + +- `source`: [`packages/experimental/frame-forwarding/src/config.ts:13`](../packages/experimental/frame-forwarding/src/config.ts) + +```ts config-catalog +/** Receiver limits passed to the Host service. */ +export interface Config { + /** Maximum surfaces per channel. Video needs one displayed surface, one in flight and one for the producer to render into. */ + maxFrames: number + /** + * Native surface allocation budget that every channel of the Desktop window shares, including idle pooled surfaces: + * `auto` is half of physical memory and at least 256 MiB. The budget never exceeds physical memory; a larger byte + * count is reduced to it with a Host warning when the first channel opens. A producer whose allocation does not fit + * waits until other channels return surfaces. + */ + maxBytes: 'auto' | number + /** + * Deadline for adapter detection, native frame delivery including each Desktop shared-texture exchange, producer + * handshakes, and producer acknowledgements, in milliseconds. A frame's presentation through Desktop waits at most + * 30000 of them, Desktop's limit. + */ + requestTimeoutMs: number + /** Maximum control requests per producer connection awaiting acknowledgement. */ + maxPendingRequests: number + /** + * Channel events retained for a renderer that has not read them yet. A newer state of a channel replaces its queued + * one; beyond the limit the unread events become one snapshot of every channel's state, including unread closures of + * channels already torn down, and unread frame errors are dropped. + */ + maxQueuedEvents: number +} +``` + + diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index a7e0f37b9a..6590704cb6 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1991,6 +1991,43 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-frame-forwarding` + +- `source`: [`packages/experimental/frame-forwarding/src/config.ts:13`](../packages/experimental/frame-forwarding/src/config.ts) + +```ts config-catalog +/** Receiver limits passed to the Host service. */ +export interface Config { + /** Maximum surfaces per channel. Video needs one displayed surface, one in flight and one for the producer to render into. */ + maxFrames: number + /** + * Native surface allocation budget that every channel of the Desktop window shares, including idle pooled surfaces: + * `auto` is half of physical memory and at least 256 MiB. The budget never exceeds physical memory; a larger byte + * count is reduced to it with a Host warning when the first channel opens. A producer whose allocation does not fit + * waits until other channels return surfaces. + */ + maxBytes: 'auto' | number + /** + * Deadline for adapter detection, native frame delivery including each Desktop shared-texture exchange, producer + * handshakes, and producer acknowledgements, in milliseconds. A frame's presentation through Desktop waits at most + * 30000 of them, Desktop's limit. + */ + requestTimeoutMs: number + /** Maximum control requests per producer connection awaiting acknowledgement. */ + maxPendingRequests: number + /** + * Channel events retained for a renderer that has not read them yet. A newer state of a channel replaces its queued + * one; beyond the limit the unread events become one snapshot of every channel's state, including unread closures of + * channels already torn down, and unread frame errors are dropped. + */ + maxQueuedEvents: number +} +``` + + diff --git a/docs/module-graph.md b/docs/module-graph.md index 3573251ecc..21907ac685 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -336,6 +336,7 @@ flowchart TD pkg_experimental_webworker_runtime["experimental-webworker-runtime"] pkg_experimental_worktree["experimental-worktree"] pkg_forge_gitlab["forge-gitlab"] + pkg_frame_forwarding["frame-forwarding"] pkg_hook_protocol["hook-protocol"] pkg_hooks_claude_code["hooks-claude-code"] pkg_hooks_codex["hooks-codex"] @@ -1854,6 +1855,7 @@ flowchart TD | [`experimental-terminal-bundle`](../packages/experimental/terminal-bundle) | `experimental` | — | | [`experimental-voice-input-bundle`](../packages/experimental/voice-input-bundle) | `experimental` | — | | [`experimental-webworker-packer`](../packages/experimental/webworker-packer) | `experimental` | — | +| [`frame-forwarding`](../packages/experimental/frame-forwarding) | `experimental` | — | | [`im-bundle`](../packages/experimental/im-bundle) | `experimental` | — | | [`read-aloud-bundle`](../packages/experimental/read-aloud-bundle) | `experimental` | — | | [`client-ui-cordis`](../packages/extensions/ui-cordis) | `extensions` | — | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index eedbe54a49..c58ab69488 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -338,6 +338,7 @@ flowchart TD pkg_experimental_webworker_runtime["experimental-webworker-runtime"] pkg_experimental_worktree["experimental-worktree"] pkg_forge_gitlab["forge-gitlab"] + pkg_frame_forwarding["frame-forwarding"] pkg_hook_protocol["hook-protocol"] pkg_hooks_claude_code["hooks-claude-code"] pkg_hooks_codex["hooks-codex"] @@ -1856,6 +1857,7 @@ flowchart TD | [`experimental-terminal-bundle`](../packages/experimental/terminal-bundle) | `experimental` | — | | [`experimental-voice-input-bundle`](../packages/experimental/voice-input-bundle) | `experimental` | — | | [`experimental-webworker-packer`](../packages/experimental/webworker-packer) | `experimental` | — | +| [`frame-forwarding`](../packages/experimental/frame-forwarding) | `experimental` | — | | [`im-bundle`](../packages/experimental/im-bundle) | `experimental` | — | | [`read-aloud-bundle`](../packages/experimental/read-aloud-bundle) | `experimental` | — | | [`client-ui-cordis`](../packages/extensions/ui-cordis) | `extensions` | — | diff --git a/packages/experimental/README.i18n.yaml b/packages/experimental/README.i18n.yaml index d370199ab1..f0e5543c8a 100644 --- a/packages/experimental/README.i18n.yaml +++ b/packages/experimental/README.i18n.yaml @@ -18,8 +18,8 @@ en: 55d9e37b0a8dd4d8 zh: 3acb6415f92698fb /packages-experimental/packages: - en: e926b436ef69cb55 - zh: 96e7989c0259cadc + en: a5a2eb03f762f338 + zh: 628131bb6531904f /packages-experimental/related-documentation: en: a45c77fe17366c4d zh: ec96fac7e0e48694 diff --git a/packages/experimental/README.md b/packages/experimental/README.md index 8c60db75a7..7be8b9a412 100644 --- a/packages/experimental/README.md +++ b/packages/experimental/README.md @@ -36,6 +36,7 @@ Promotion requires a named product role, documented public behavior and limitati | Package | Role | ctx key | |---|---|---| +| [`frame-forwarding`](frame-forwarding/README.md) | Native frame forwarding for Host plugins through Desktop shared textures | `ctx.frameForwarding` | | [`tool-session-query`](tool-session-query/README.md) | Workspace-authorized model session search, trace, and event reads | — | | [`session-search`](session-search/README.md) | Optional experimental global session search tools | — | | [`deepseek-chat-import`](deepseek-chat-import/README.md) | Optional upload of DeepSeek website chat exports as Sessions in a chosen Workspace | `ctx.deepseekChatImport` | diff --git a/packages/experimental/README.zh.md b/packages/experimental/README.zh.md index 96fc45c00c..f947111e35 100644 --- a/packages/experimental/README.zh.md +++ b/packages/experimental/README.zh.md @@ -36,6 +36,7 @@ kind: "package-group" | 包 | 职责 | ctx 键 | |---|---|---| +| [`frame-forwarding`](frame-forwarding/README.zh.md) | Host 插件经 Desktop 共享纹理的原生帧转发 | `ctx.frameForwarding` | | [`tool-session-query`](tool-session-query/README.zh.md) | 按工作区授权的模型会话搜索、追踪与事件读取 | — | | [`session-search`](session-search/README.zh.md) | 可选实验性全局会话搜索工具 | — | | [`deepseek-chat-import`](deepseek-chat-import/README.zh.md) | 可选上传 DeepSeek 官网会话导出,存为所选工作区中的会话 | `ctx.deepseekChatImport` | diff --git a/packages/experimental/frame-forwarding/README.i18n.yaml b/packages/experimental/frame-forwarding/README.i18n.yaml new file mode 100644 index 0000000000..963681673e --- /dev/null +++ b/packages/experimental/frame-forwarding/README.i18n.yaml @@ -0,0 +1,37 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/experimental/frame-forwarding/README.md +/: + en: 8fe2cfa62e9d1917 + zh: f2ce6265d95593a3 +/deepseek-ai-dsh-frame-forwarding: + en: 8808a7b78b1c7a54 + zh: 80ae465c219ccd26 +/deepseek-ai-dsh-frame-forwarding/summary: + en: 2741a27a2e3506b7 + zh: d568e5367f5f65e9 +/deepseek-ai-dsh-frame-forwarding/table-of-contents: + en: 5163cf3b0e765765 + zh: 81a0600301a417d5 +/deepseek-ai-dsh-frame-forwarding/use-this-package: + en: 6ae5eff2b61fb733 + zh: 5cab5682d456816f +/deepseek-ai-dsh-frame-forwarding/security-semantics: + en: b146c7ce0ac1196c + zh: c340ed00ec958851 +/deepseek-ai-dsh-frame-forwarding/understand-the-implementation: + en: 0631cb2156ea8428 + zh: 5c2458db7841e427 +/deepseek-ai-dsh-frame-forwarding/model-experience: + en: f2b63814794ab9f8 + zh: 9ecf4374968f6448 +/deepseek-ai-dsh-frame-forwarding/model-experience/kv-cache-effect: + en: 4f0eadf94828e66e + zh: 97d3eb3e79199354 +/deepseek-ai-dsh-frame-forwarding/known-limitations-and-deferred-work: + en: 1fc54b1036407265 + zh: 0849bfaa99142b9e +/deepseek-ai-dsh-frame-forwarding/known-limitations-and-deferred-work/dev-note: + en: 426d6a6ebbabdab1 + zh: bba1861c2b9e536d diff --git a/packages/experimental/frame-forwarding/README.md b/packages/experimental/frame-forwarding/README.md new file mode 100644 index 0000000000..7104d7c628 --- /dev/null +++ b/packages/experimental/frame-forwarding/README.md @@ -0,0 +1,123 @@ +--- +description: "Native frame forwarding for Host plugins: transferable channels whose producer processes present frames in the Desktop renderer without pixel copies." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-frame-forwarding + +English | [中文](README.zh.md) + +## Summary + +A Host plugin that renders in its own native process can show those frames in the Desktop document without copying pixels. The `frameForwarding` Host service opens channels with transferable producer credentials, serves one producer per channel at a time, hands a channel to a successor once the previous producer's frames drain, enforces frame and byte budgets, and has Desktop present accepted textures; the `frameForwarding` Client service connects the renderer to a channel and lends each frame to the consumer's drawing callback. The LibreOffice Kit is the first producer. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Security semantics](#security-semantics) +- [Understand the implementation](#understand-the-implementation) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +Desktop preinstalls the frame receiver on macOS and Windows. Both the bundled preview and a frame-forwarding plugin installed through Plugin Manager use the receiver supplied by the running Desktop. + +Insert the package beside the consumer plugin as the row `frame-forwarding` without a config. Every consumer bundle inserts that same row, and the Loader keeps one row per id, so consumers enabled together share one instance: disabling one consumer leaves frame forwarding and the other consumers' channels running. Tune its limits with a patch targeting `frame-forwarding`, which applies after every bundle. Consumers share the window's byte budget, its fullscreen holder, and coverage. In the Host, read the service with `ctx.get('frameForwarding')`, probe `capabilities()`, then call `channel()` for `{ tx, rx }`. Hand `tx` to the producer process, for example as the credential a child process receives from its parent; any process holding a copy may connect, nothing binds a PID, and `tx` never goes to the renderer, a log, or a diagnostic. Send `rx` to the renderer. A second producer is refused as `channel-busy` while one is connected; after it disconnects or exits, one successor with the same `tx` connects once the previous producer's frames are released. `isOpen(rx)` reports whether the channel still serves producers, and `close(rx)` closes it permanently. A channel also closes when the Cordis scope that read the service with `ctx.get` is disposed, for example when its plugin reloads; a Remote method's `this.ctx` is the Remote gateway's scope, so a consumer that opens channels during Remote calls closes them in its own disposal. A channel closes as `lost` when Desktop can no longer account for a frame it presented, for example after Chromium's GPU process exits; its owner probes `capabilities()` again and opens a channel in its place. `capabilities()` reports `gpu-compositing-disabled` once Chromium composites in software, for example after repeated GPU process crashes. A Host that cannot present frames, such as any Host outside Desktop, reports `supported: false` with a reason, and `channel()` rejects; reasons are diagnostics from an open set, so consumers branch only on `supported`. + +In the Client, read `ctx.get('frameForwarding')`, which exists only in a document that displays the Host's frames, the Desktop document, so consumers test for the service rather than for Desktop, and `connect(rx)` to obtain a `FrameRx` that serves every producer the channel has. `setViewport` sends a strictly increasing viewport version; the Host keeps the latest one and applies it to each new producer before delivering that producer's frames. The Host delivers a producer's frames whose generation does not exceed the channel's latest viewport version, including earlier generations still in flight, and none while that viewport is invisible; outside a document mount, the receive channel releases frames of other versions unseen. A receive channel connected again, for example after a renderer reload, starts counting below the version the Host kept: `mount()` retries above it, while `setViewport` rejects with an error that names it. A viewport whose producer ended before acknowledging it rejects with `producer-changed`; one sent without a producer resolves and is applied later. A viewport the producer refuses or does not acknowledge within `requestTimeoutMs` rejects with that error and leaves the channel open; the next viewport is still sent. `ready(signal)` resolves with the connection ID once a producer acknowledged the latest viewport. `closed` settles once with why the receive channel stopped routing: `closed` after its owner or `close()` closed it, `lost`, or `failed`. A receive channel has one consumer kind at a time: + +- **Mounted video.** Call `mount(element, failure)` on a sized container to feed received frames to a video element through `MediaStreamTrackGenerator`. When a new mount reuses an open channel, it advances past the viewport version the Host retained. Call the returned disposer to detach the video and stop its track. Unmounting a visible view queues an invisible viewport so the producer can trim idle surfaces. +- **Continuous stream.** `consume(present, failure)` presents frames newest first and stays subscribed across producer switches. While `present` runs, only the newest arrived frame waits; a newer arrival releases the waiting one unpresented. `failure` receives the connected producer's errors, the channel's closure, or an error `present` raised, and the stream stays subscribed. + +`onEvent(listener)` reports channel state, viewport, fullscreen, errors and content submissions. A content event identifies the generation submitted to the video track. It cannot confirm when Chromium displays those pixels. + +The mount reports its physical size, device pixel ratio and visibility to the producer, coalescing viewport changes. A hidden document sends an invisible viewport immediately. + +While mounted, `setContentView({ x, y, scale })` sets the content coordinate at the element’s top-left corner and CSS pixels per content unit; `undefined` restores fill mode. `setContentWindow({ x, y, width, height })` binds a window to a new viewport version and resolves with the acknowledged viewport to use as paint generation; an unchanged window returns the current acknowledgement without incrementing. Call it only after the previous paint resolves, then request the next paint after this promise resolves. Frame forwarding serializes viewport updates, not paints: a mount update already in flight completes first, and unsent window requests coalesce to the latest window. Numeric validation synchronously throws `TypeError` without sending messages for non-finite values, coordinates beyond ±2²⁴, non-positive extents or extents above 2²⁴, or scale outside (0, 64]. Both setters throw outside a mount; a window request during producer draining rejects with `producer-changed`. + +The video uses the current content view and window for CSS placement. Frames fill the mount in the absence of content mapping. + +Each consumer callback receives a `FrameForwardingFrame`, `{ image, metadata }`, lent until the callback returns or its promise settles; frame forwarding then closes `image`, which returns its resources to the Host. Draw, upload, or copy `image` during that period. A Desktop shared texture returns to the producer only after Desktop reports every Electron reference gone, which Electron reports after GPU work that used the image completes ([`getVideoFrame`](https://www.electronjs.org/docs/latest/api/structures/shared-texture-imported)). A retained `image` or clone keeps its resources in use until it closes. How `image` is backed and its pixel `format` depend on the Host, so read pixels only through `drawImage`, or through `copyTo` with an explicit `format`. Consumers pass no queue sizes and release no frames; `close()` stops consumption and completes after every lent frame is released. Frame metadata carries `rx`, `connectionId`, `requestId`, `frameId`, `generation`, `revision`, `width`, and `height`; `generation` is the viewport version, and the consumer chooses `requestId` and the producer echoes it. + +A receive channel also shows its consumer's view fullscreen through the document's Fullscreen API. `requestFullscreen(element)` makes `element`, typically the view's root, the fullscreen element; Chromium grants fullscreen only while the document handles a user gesture, so call it before the gesture's handler awaits anything. One channel holds fullscreen at a time, and another channel's request rejects meanwhile; `exitFullscreen()` and `close()` leave the fullscreen the channel holds, including its earlier elements that Chromium keeps below a later one, and Escape leaves it too. Once one of the channel's elements has been fullscreen, the hold lasts until the document leaves fullscreen, also while another element covers it, because the document reports only its topmost fullscreen element. `fullscreen` reads the document's state as the channel sees it, `{ active, holder }`, and `onFullscreen(listener)` reports each change. While another element is fullscreen (`active` without `holder`), the channel's view is covered: its consumer sends its next viewport version with `visible: false`, so the producer pauses and returns its idle surfaces to the window budget, and a visible viewport once `active` ends. A holder that sees `active: false` ends what it showed fullscreen. + +Config, read by the Host plugin only: `maxFrames` (frames per channel that the producer, Host, Desktop, and renderer hold together, default 3, 3–16), `maxBytes` (allocation budget that every channel of the window shares: `auto`, the default, is half of physical memory and at least 256 MiB; the budget never exceeds physical memory, and a larger byte count is reduced to it with a Host warning when the first channel opens), `requestTimeoutMs` (adapter detection, frame delivery including each Desktop shared-texture exchange, producer handshakes, and producer acknowledgements; a frame's presentation through Desktop waits at most 30000 ms, Desktop's limit), `maxPendingRequests` (control requests per connection awaiting acknowledgement), and `maxQueuedEvents` (channel events retained for a renderer that has not read them; a newer state of a channel replaces its queued one, and beyond the limit the unread events become one snapshot of every channel's state, including the newest `maxQueuedEvents` unread closures of channels already torn down, and dropping unread frame errors and older closures). A stream producer that keeps one of its `maxFrames` surfaces out of flight always has a render target, so its state advances without waiting for credit and its newest complete frame goes out when a surface returns. + +The plugin reads the absolute addon path from Desktop Host, checks the build record for the platform, protocol version and handshake capabilities it requires, then loads the receiver on first use. For development builds run `pnpm --dir apps/desktop run build:native`. + +The native producer interface is internal. The [design decision](../../../.agents/notes/implemented/architecture/2026-10-15-desktop-shared-texture-api.md#native-producer-sdk) explains why SDK publication is deferred. + +**Stability.** The package is experimental: breaking changes to its Host and Client services follow its semver. Its package name carries no `experimental` prefix, so bundle patches and profiles that name it keep their reference when it leaves the experimental group; the experimental classification still governs its dependency isolation and promotion. The wire protocol is at version 2, and a receiver refuses a producer of another version; within a version it changes only by adding handshake capabilities that both sides check, so a receiver refuses a producer without a capability it requires, and a producer refuses a receiver that does not acknowledge one the producer relies on. + +----- + + +## Security semantics + +Frame forwarding is the only native-rendering API plugins use; these are its guarantees. + +- **Who can open channels.** Any Host plugin can read `frameForwarding`. A channel grants authority only to holders of its `tx`; the plugin decides which processes receive it, and copying it revokes nothing. +- **Producer authentication.** `channel()` returns a credential with a 256-bit random secret and an unguessable endpoint name: a Mach service on macOS, and on Windows a named pipe that admits only the receiver's user and rejects remote clients. The producer's `hello` must carry the secret, protocol version 2, and the `transferable-tx` and `producer-local-handles` capabilities; the receiver compares the secret in constant time, refuses a mismatch as `invalid-credential`, another version as `protocol-mismatch`, and a producer without a capability as `transferable-tx-required` or `producer-local-handles-required`, and closes only that candidate. Each physical connection checks that every later packet comes from the kernel-reported sender of its handshake (Mach audit trailer, `GetNamedPipeClientProcessId`) and carries its connection ID; that PID grants no authority. `close(rx)` withdraws the endpoint, so the credential stops connecting. +- **Producer handles.** A producer names only objects it owns. On Windows each frame carries a handle value in the producer's process, and the receiver duplicates it from that process with the access it opened when the producer connected; a value that names no handle of a live producer ends that connection without touching any Host handle. ready echoes the capabilities the receiver accepted, so a producer refuses a receiver that would read its values as Host handles. macOS transfers Mach port rights, which the kernel names in the receiver. +- **Producer isolation.** One producer is connected at a time and is never preempted. A successor connects only after the previous producer's frames, allocations, budget, and GPU work are released; frames and credit of one connection never reach another, and late releases or messages of an earlier connection affect nothing. +- **Resource bounds.** Each channel holds at most `maxFrames` surfaces in flight, including the frames its renderer holds; all channels share one `maxBytes` allocation budget, and each connection queues at most `maxPendingRequests` control requests. A producer whose allocation does not fit the remaining budget waits until other channels return surfaces; its channel stays open, so its consumer keeps what it shows and draws a placeholder where content has not arrived. Handshakes and acknowledgement waits end at `requestTimeoutMs`. A producer whose view is hidden or covered returns its idle surfaces to the shared budget: the Kit engine trims after acknowledging an invisible viewport. The producer's credit for a frame returns only after Desktop reports all Electron references to its texture gone; an `invalidated` settlement queues its notice, then stops the receiver and the frame's connection before releasing the frame, so the producer never regains that texture's credit; the forwarder closes the channel as `lost` when it handles the notice. +- **Renderer input.** Frame metadata is producer-supplied; the Client validates it and releases any texture without valid metadata or without a connected receive channel. The Host validates every renderer viewport and rejects a version that does not exceed the channel's current one. A frame of a generation the renderer never sent is released unseen, whatever the producer acknowledges. +- **What plugins do not see.** Plugins do not get Mach ports, Win32 handle transfer, Electron, or Desktop's internal texture interfaces, which are not supported for plugins. The Host plugin holds the only claim on the Desktop Host's `sharedTexture` service from load to unload, and the Client plugin consumes the Client `sharedTexture` service from its start to its disposal, so another consumer of either fails at once. When another consumer took the `sharedTexture` claim first, frame forwarding reports `desktop-shared-texture-claimed` until it or the Desktop Host's `sharedTexture` service reloads; it does not take the claim over when the other holder releases it. The Host-to-Main boundary is Desktop's own audited boundary and does not change with this package. + +----- + + +## Understand the implementation + +The workspace keeps the [native receiver](native/receiver.cc) and transport alongside the plugin. Desktop compiles them for its target architecture. The plugin’s npm package excludes the native sources and binary. Each channel is a stable listener; each producer connection owns its Mach ports or pipe instance, its frames and allocations, its credit, and its relay state, and the [channel note](../../../.agents/notes/implemented/architecture/2026-10-18-frame-forwarding-channels.md) owns the handoff rationale. When the producer's GPU differs from Chromium's, the Windows receiver reads each frame back and uploads it to Chromium's adapter, returning the producer's credit after the readback; a frame the producer marks replaceable (`frame_replaceable`, set by `dsh_frame_forwarding_submit_latest`) then replaces staged replaceable frames whose upload has not begun, while request frames stay queued in order. + +Windows relay keeps one import per allocation across staging slots, reusing it only for the same NT object and dimensions. Allocation retirement clears cached imports before returning credit; active GPU copies retain their source until completion. + +The Host [forwarder](src/host/forwarder.ts) creates receivers under one shared budget, follows each channel's connections, keeps the renderer's latest viewport and replays it to every new connection, binds each viewport request to the connection that received it, attaches the native sink of `sharedTexture.nativeSink` to each receiver, and keeps each receiver's presentation gate current: frames from the current connection up to the latest viewport's version, including earlier generations, while that viewport is visible. The gate moves before each viewport is sent, so a frame that reaches the receiver before its acknowledgement reaches the Host's JavaScript still passes. The receiver presents each frame that passes the gate in native code, through that sink, with its Host-local handle and the frame metadata, so frames do not pass through the Host's JavaScript; it returns a frame outside the gate, or with invalid metadata, to its producer at once. A delivery returns to the receiver only after Desktop settles the presentation; an `invalidated` settlement stops the receiver before it releases the frame and the forwarder then closes the channel as `lost`, and a presentation failure is reported to the renderer as a `presentation` error without closing the channel. A frame that Desktop alone refuses, for example at its presentation limit, is one such failure and leaves the receiver's sink attached; a receiver whose sink lost its connection to Main detaches it and delivers its next frame to the forwarder instead, which returns it to the producer and attaches a new sink to every channel. On Windows every channel takes Chromium's compositor adapter from `sharedTexture.adapterLuid()`, the LUID Desktop Main reads from a texture the compositor exports and reads again after Chromium's GPU process restarts, so each channel follows Chromium's current adapter. The Host plugin is a Typert Remote service: `viewport` applies the renderer's viewport to a channel, and each `events(signal)` subscription replaces the previous one. It streams a snapshot of every channel's state, then states with increasing sequence numbers and frame errors with their source, to the current renderer; unread events beyond `maxQueuedEvents` become a new snapshot. + +The Client half consumes the Client `sharedTexture` service (which the shared-texture Client plugin provides from Desktop's preload bridge) from its start to its disposal, also while no channel is open, routes each texture to its receive channel by the `rx` in its metadata and releases textures that carry none, sends viewports through the `viewport` Remote, and applies channel states in sequence order, with each snapshot replacing the states it knew; a channel absent from a new snapshot is reported `lost`, since the renderer cannot know why it closed. A closed channel's state stays until its consumer detaches, and only the 64 newest closed channels without a consumer keep theirs, so a late consumer still learns of the closure. Closing a receive channel detaches its frame and event callbacks before notifying close listeners, so a listener can reconnect the same `rx`. A [receive channel](src/client/rx.ts) holds only the frames being drawn, at most one newest stream frame behind them, and frames whose connection state has not arrived yet, so the Host's per-channel limit bounds the renderer without a queue of its own. The Client also records which channel requested the fullscreen element and reports every `fullscreenchange` to each channel; a channel whose element another element replaced as fullscreen no longer holds it. + +Desktop's internal shared-texture service, the Mach ingress, and the hop that carries handles into Electron Main belong to the [Desktop application](../../../apps/desktop/README.md); this package holds their only claim, and the [design record](../../../.agents/notes/implemented/architecture/2026-10-15-desktop-shared-texture-api.md) owns the ownership rationale. + +----- + + +## Model Experience + +None, as frame forwarding carries pixels between processes and adds no model context or Session events. + +#### KV Cache effect + +None. + +## Known Limitations and Deferred Work + + + +- During scroll or zoom, media playback and CSS placement can update on different frames. A submitted generation is not a display acknowledgement. +- Supported on macOS and Windows Desktop only; other Hosts report `unsupported-platform` or `desktop-shared-texture-unavailable`. +- Desktop answers a presentation once the renderer has imported the texture, so a renderer main thread blocked longer than `requestTimeoutMs` (10 s by default) reports that frame as failed, and the frame returns to its producer only when Desktop settles it; shorter stalls deliver the producer's newest frame when the renderer resumes. +- The Host does not learn of a renderer-side consumer failure; a consumer finds out when its next operation on the receive channel rejects. +- A producer that stays connected while it stops responding keeps its channel until it exits or the channel closes; nothing preempts it. +- Each connection can have at most 256 producer events pending in Host JavaScript: messages, presentation errors and frames not handed to Desktop. Exceeding the limit disconnects only that producer with a reason; the channel stays open and a successor can connect with the same `tx` after the drain. The receiver coalesces `rejected` warnings while one is pending. The limit is per connection, not per receiver: lifecycle notifications from successive short connections can accumulate while JavaScript is stalled. +- A GPU-process exit, renderer exit, committed navigation, or window closure invalidates the textures on screen and closes their channels as `lost`; the consumer opens a new channel to continue. +- Producers and receivers of protocol 1, such as the LibreOffice Kit 0.2.3 SDK and earlier, are refused; producers, receivers, and engines upgrade together. +- Escape always leaves fullscreen: the Client does not take Keyboard Lock, so a consumer such as a game cannot keep Escape for itself. +- On Windows the receiver opens each producer process to duplicate its frame handles, so a producer must run as the Host's user at or below the Host's integrity level. The receiver cannot open a producer elevated above the Host and closes that connection during the handshake without a Host diagnostic. +- On Windows the receiver keeps one listening pipe instance and opens the next only after it hands a candidate the current one, so a process of the Host's user that connects with a wrong credential every few milliseconds can keep the pipe busy. A producer retries a busy pipe until its connection deadline, 10 seconds by default or the timeout passed to `dsh_frame_forwarding_connect_with_options`, and gives up early only after the pipe name has been absent for 500 ms without interruption; every busy reply restarts that count. Such a storm therefore fails a producer only if it lasts until the deadline, with `receiver unavailable`, or `connection cancelled or timed out` when the producer passed a timeout. A second listening instance would close the gap. +- On Windows, when the producer's GPU differs from Chromium's, a producer trimming an invisible view returns its source allocations but not its relay targets and staging surfaces: they keep their GPU memory and their share of `maxBytes` at the largest allocation size until the connection ends. + + +### Dev Note + +
+Working context for maintainers + +The [native e2e](tests/receiver-native.e2e.ts) compiles a test producer, connects separate producer processes with a copied credential, takes over after a crash once the held frame is released, refuses test producers built with another protocol version, without transferable channels, or without producer-local handles, and returns a trimmed producer's idle allocation to another channel sharing its budget. The [Desktop bridge e2e](tests/desktop-bridge-native.e2e.ts) attaches a fixture sink that implements Desktop's sink ABI: frames outside the deliverable state and frames with invalid metadata return their credit without a presentation, a presented frame carries its identity as metadata and returns its credit when the sink releases it, an invalidated settlement stops the channel before the release, a frame Desktop refuses leaves the sink attached while a sink that lost its connection is detached so later frames reach JavaScript, and settlements after the receiver closed are safe; when Desktop's addons are built, frames cross Desktop's hop sink into Desktop's ingress and follow Main's settlements. The [Kit frames e2e](tests/kit-frames-native.e2e.ts) opens a two-slide deck in the installed Kit's LibreOffice process, forwards its frames to an in-process Desktop, and reads IOSurface pixels: requested frames arrive under their identifiers and return credit on release; while Desktop holds every slideshow frame the slideshow state still advances, then one release delivers the newest slide; and a replacement engine, normally and after a crash, connects only after the previous engine's frame is released and renders at the replayed viewport; it is skipped while the installed Kit speaks another protocol version than this receiver. The native suites run with `pnpm exec vitest run --config vitest.e2e.config.ts packages/experimental/frame-forwarding` on macOS after the Desktop native build; the Desktop bridge e2e also runs on Windows. + +
diff --git a/packages/experimental/frame-forwarding/README.zh.md b/packages/experimental/frame-forwarding/README.zh.md new file mode 100644 index 0000000000..ba74b48407 --- /dev/null +++ b/packages/experimental/frame-forwarding/README.zh.md @@ -0,0 +1,123 @@ +--- +description: "面向 Host 插件的原生帧转发:可转交通道让 producer 进程不经像素拷贝地在 Desktop renderer 中呈现帧。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-frame-forwarding + +[English](README.md) | 中文 + +## 概述 + +在自己的原生进程中渲染的 Host 插件,可以不经像素拷贝地把这些帧显示在 Desktop 文档中。`frameForwarding` Host 服务打开带可转交 producer 凭据的通道,每个通道同一时间服务一个 producer,在前一个 producer 的帧排空后把通道交给后继,执行帧数与字节预算,并让 Desktop 呈现被接受的纹理;`frameForwarding` Client 服务把 renderer 连接到通道,并把每一帧借给消费者的绘制回调。LibreOffice Kit 是第一个 producer。 + +## 目录 + +- [使用此包](#use-this-package) +- [安全语义](#security-semantics) +- [实现说明](#understand-the-implementation) +- [模型体验](#model-experience) +- [已知限制和后续工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用此包 + +Desktop 在 macOS 和 Windows 的安装包中预装帧接收器。预览 bundle 和通过 Plugin Manager 安装的帧转发插件都使用当前 Desktop 提供的接收器。 + +把本包作为不带 config 的 `frame-forwarding` 行与消费者插件一起插入。每个消费者 bundle 都插入这同一行,而 Loader 对每个 id 只保留一行,因此同时启用的消费者共享同一个实例:关闭其中一个消费者时,帧转发和其他消费者的通道继续运行。用针对 `frame-forwarding` 的 patch 调整其上限,它在所有 bundle 之后应用。消费者共享窗口的字节预算、全屏持有者和遮挡状态。在 Host 中用 `ctx.get('frameForwarding')` 读取服务,先探测 `capabilities()`,然后调用 `channel()` 得到 `{ tx, rx }`。把 `tx` 交给 producer 进程,例如作为子进程从父进程获得的凭据;任何持有副本的进程都可连接,不绑定任何 PID,`tx` 也从不进入 renderer、日志或诊断信息。把 `rx` 发给 renderer。已有 producer 在线时,第二个 producer 以 `channel-busy` 被拒绝;它断开或退出后,持有同一 `tx` 的一个后继在前一个 producer 的帧释放后连接。`isOpen(rx)` 报告通道是否仍服务 producer,`close(rx)` 永久关闭通道。用 `ctx.get` 读取服务的 Cordis 作用域被销毁时(例如其插件重载),通道也随之关闭;Remote 方法的 `this.ctx` 是 Remote 网关的作用域,因此在 Remote 调用中打开通道的消费者须在自己的销毁中关闭它们。Desktop 无法再追踪它呈现过的某一帧时(例如 Chromium 的 GPU 进程退出后),通道以 `lost` 关闭;其所有者再次探测 `capabilities()`,并打开一个通道替代它。Chromium 改用软件合成后(例如 GPU 进程多次崩溃后),`capabilities()` 报告 `gpu-compositing-disabled`。无法呈现帧的 Host(例如 Desktop 之外的任何 Host)报告带原因的 `supported: false`,`channel()` 拒绝;原因只用于诊断,取值是开放集合,因此消费者只按 `supported` 分支。 + +在 Client 中用 `ctx.get('frameForwarding')` 读取服务,它只存在于能显示 Host 帧的文档中,即 Desktop 文档,因此消费者检测该服务,而不是检测 Desktop;再以 `connect(rx)` 获得一个服务该通道所有 producer 的 `FrameRx`。`setViewport` 发送严格递增版本的 viewport;Host 保存最新的一个,并在交付新 producer 的帧之前把它应用到该 producer。Host 交付 generation 不超过通道最新 viewport 版本的帧,包括仍在途的更早 generation;该 viewport 不可见时不交付任何帧;文档挂载之外,接收通道释放其他版本的帧而不经消费。重新连接的接收通道(例如 renderer 重新加载后)从低于 Host 所保存版本的值开始计数:`mount()` 会改用更高的版本重试,`setViewport` 则以一个写明该版本的错误拒绝。producer 在确认前结束时,该 viewport 以 `producer-changed` 拒绝;没有 producer 时发送的 viewport 会完成,并在之后应用。producer 拒绝或未在 `requestTimeoutMs` 内确认的 viewport 以该错误拒绝,通道保持打开,下一个 viewport 照常发送。`ready(signal)` 在 producer 确认最新 viewport 后以连接 ID 完成。`closed` 在接收通道停止路由时以原因完成一次:被所有者或 `close()` 关闭时为 `closed`,另有 `lost` 和 `failed`。一个接收通道同一时间只有一种消费方式: + +- **视频挂载。** 在具有尺寸的容器上调用 `mount(element, failure)`,通过 `MediaStreamTrackGenerator` 把收到的帧送给 video 元素。新挂载复用一个仍然打开的通道时,会使用比 Host 保留的视口版本更高的版本。调用返回的清理函数即可卸载视频并停止轨道。卸载可见视图时会排队发送不可见视口,以便 producer 归还空闲 surface。 +- **连续流。** `consume(present, failure)` 按最新优先呈现帧,并在 producer 切换后保持订阅。`present` 运行期间只有最新到达的一帧在等待;更新的帧到达时,等待中的那一帧未经呈现即被释放。`failure` 接收在线 producer 的错误、通道关闭或 `present` 抛出的错误,流保持订阅。 + +`onEvent(listener)` 报告通道状态、视口、全屏、错误及内容提交。content 事件标识提交到视频轨道的 generation;Chromium 实际显示这些像素的时间不可观测。 + +挂载会合并视口更新,并将物理尺寸、设备像素比和可见性报告给 producer。文档隐藏时立即发送不可见视口。 + +挂载期间,`setContentView({ x, y, scale })` 设置元素左上角对应的内容坐标与每内容单位的 CSS 像素数;传入 `undefined` 恢复铺满模式。`setContentWindow({ x, y, width, height })` 把窗口绑定到新的 viewport 版本,完成时返回已确认的 viewport,其版本用于 paint generation;窗口不变时返回当前确认结果,不递增版本。必须等上一次 paint 完成后再调用,并等该 Promise 完成后才请求下一次 paint。帧转发只串行化 viewport 更新,不等待 paint:mount 已在途的更新先完成,未发送的窗口请求合并为最新窗口。数值非有限、坐标超出 ±2²⁴、宽高非正或大于 2²⁴、scale 不在 (0, 64] 时同步抛出 `TypeError`,不发送消息。两个 setter 在挂载之外均抛错;producer 排空期间的窗口请求以 `producer-changed` 拒绝。 + +video 根据当前内容视图和窗口设置 CSS 位置;未指定内容映射时,帧铺满容器。 + +每个消费者回调收到一个 `FrameForwardingFrame`,即 `{ image, metadata }`,借用期持续到回调返回或其 Promise 结束;随后帧转发关闭 `image`,把它占用的资源归还 Host。请在借用期内绘制、上传或复制 `image`。Desktop 共享纹理只有在 Desktop 报告 Electron 引用全部消失后才回到 producer,而 Electron 在使用该图像的 GPU 工作完成后才作此报告([`getVideoFrame`](https://www.electronjs.org/docs/latest/api/structures/shared-texture-imported))。保留 `image` 或其克隆会让它占用的资源一直处于使用中,直到它被关闭。`image` 的底层存储和像素 `format` 取决于 Host,因此读取像素只能通过 `drawImage`,或通过显式指定 `format` 的 `copyTo`。消费者不传队列大小,也不逐帧释放;`close()` 停止消费,并在所有借出的帧都释放后完成。帧元数据携带 `rx`、`connectionId`、`requestId`、`frameId`、`generation`、`revision`、`width` 和 `height`;`generation` 是 viewport 版本,`requestId` 由消费者选择、producer 回显。 + +接收通道还通过文档的 Fullscreen API 全屏显示其消费者的视图。`requestFullscreen(element)` 让 `element`(通常是视图的根元素)成为全屏元素;Chromium 只在文档处理用户手势期间允许全屏,因此要在手势处理函数 await 任何东西之前调用它。同一时间只有一个通道持有全屏,期间其他通道的请求会被拒绝;`exitFullscreen()` 和 `close()` 退出该通道持有的全屏,包括 Chromium 保留在后一个元素之下的该通道更早的全屏元素,按 Escape 也会退出。通道的某个元素进入过全屏后,持有会一直持续到文档退出全屏,期间被其他元素盖住也是如此,因为文档只报告最上层的全屏元素。`fullscreen` 读取该通道视角下的文档全屏状态 `{ active, holder }`,`onFullscreen(listener)` 报告每次变化。另一个元素全屏期间(`active` 而非 `holder`),该通道的视图被遮挡:消费者以下一个 viewport 版本发送 `visible: false`,producer 随之暂停并把空闲 surface 归还窗口预算,`active` 结束后再发送可见的 viewport。看到 `active: false` 的持有者结束它全屏显示的内容。 + +配置只由 Host 插件读取:`maxFrames`(producer、Host、Desktop 与 renderer 合计持有的每通道帧数,默认 3,范围 3–16)、`maxBytes`(窗口内所有通道共享的分配预算:默认值 `auto` 取物理内存的一半且不低于 256 MiB;预算不超过物理内存,更大的字节数在第一个通道打开时降为物理内存,并在 Host 日志中警告)、`requestTimeoutMs`(adapter 探测、帧交付(含每次 Desktop 共享纹理交换)、producer 握手和 producer 确认的期限;一帧经 Desktop 呈现最多等待 30000 ms,这是 Desktop 的上限)、`maxPendingRequests`(每个连接等待确认的控制请求数)和 `maxQueuedEvents`(为尚未读取的 renderer 保留的通道事件数;通道的新状态替换其排队中的状态,超出上限时未读事件改为一份所有通道状态的快照,其中保留已拆除通道最新的至多 `maxQueuedEvents` 个未读关闭状态,未读的帧错误和更早的关闭状态被丢弃)。连续流 producer 若始终让 `maxFrames` 个 surface 中的一个不在途,就总有渲染目标,因此其状态无需等待信用即可推进,surface 归还时即发出其最新的完整帧。 + +插件从 Desktop Host 取得预装模块的绝对路径,首次使用时校验构建清单中的平台、协议版本和握手能力,再加载接收器。源码开发时运行 `pnpm --dir apps/desktop run build:native`。 + +原生 producer 接口目前仅供内部集成使用。[设计决策](../../../.agents/notes/implemented/architecture/2026-10-15-desktop-shared-texture-api.zh.md#native-producer-sdk)说明了暂缓发布 SDK 的原因。 + +**稳定性。** 本包是 experimental:Host 与 Client 服务的破坏性变更随其 semver 发布。包名不带 `experimental` 前缀,因此它移出实验分组时,引用它的 bundle patch 和 profile 保持有效;依赖隔离和晋升仍由实验性分类约束。线上协议为版本 2,接收器拒绝其他版本的 producer;同一版本内只通过增加双方都检查的握手能力来演进:接收器拒绝缺少它所要求能力的 producer,producer 拒绝不确认 producer 所依赖能力的接收器。 + +----- + + +## 安全语义 + +帧转发是插件使用的唯一原生渲染 API;以下是它的保证。 + +- **谁可以打开通道。** 任何 Host 插件都可以读取 `frameForwarding`。通道只向其 `tx` 的持有者授予权限;由插件决定哪些进程获得它,复制凭据不会吊销任何持有者。 +- **producer 鉴别。** `channel()` 返回的凭据带 256 位随机密钥和不可猜测的 endpoint 名字:macOS 上是 Mach 服务,Windows 上是只允许接收器所属用户、拒绝远程客户端的命名管道。producer 的 `hello` 必须携带该密钥、协议版本 2 以及 `transferable-tx` 与 `producer-local-handles` 能力;接收器以恒定时间比较密钥,以 `invalid-credential` 拒绝不匹配者、以 `protocol-mismatch` 拒绝其他版本、以 `transferable-tx-required` 或 `producer-local-handles-required` 拒绝缺少相应能力的 producer,且只关闭该候选连接。每个物理连接都检查此后的每个包来自其握手时内核报告的发送方(Mach 审计 trailer、`GetNamedPipeClientProcessId`)并携带其连接 ID;该 PID 不授予任何权限。`close(rx)` 撤回 endpoint,凭据随即无法连接。 +- **producer 句柄。** producer 只能指名自己拥有的对象。Windows 上每帧携带的是 producer 进程中的句柄值,接收器用 producer 连接时打开的访问权限从该进程复制它;值若不对应仍在运行的 producer 的任何句柄,该连接即结束,且不触碰任何 Host 句柄。ready 回显接收器接受的能力,因此 producer 拒绝会把其句柄值当作 Host 句柄读取的接收器。macOS 传递 Mach 端口权限,由内核在接收器中为其命名。 +- **producer 隔离。** 同一时间只有一个 producer 在线,且不会被抢占。后继只在前一个 producer 的帧、分配、预算和 GPU 工作都释放后连接;一个连接的帧和信用不会到达另一个连接,较早连接迟到的释放或消息不产生任何影响。 +- **资源上限。** 每个通道最多有 `maxFrames` 个在途 surface,其中包括其 renderer 持有的帧;所有通道共享一个 `maxBytes` 分配预算,每个连接最多排队 `maxPendingRequests` 个控制请求。分配放不进剩余预算的 producer 会等待其他通道归还 surface;其通道保持打开,因此它的消费方保留已显示的内容,并在内容尚未到达处绘制占位。握手与确认等待在 `requestTimeoutMs` 结束。视图被隐藏或遮挡的 producer 把空闲 surface 归还共享预算:Kit 引擎在确认不可见的 viewport 后执行收缩。某一帧的 producer 信用只在 Desktop 报告其纹理的 Electron 引用全部消失后才归还;`invalidated` 结算先把通知排入队列,再停止接收器和这一帧所属的连接,然后才释放这一帧,因此 producer 不会重新得到该纹理的信用;forwarder 处理这条通知时以 `lost` 关闭通道。 +- **renderer 输入。** 帧元数据由 producer 提供;Client 会校验它,并释放元数据无效或没有已连接接收通道的纹理。Host 会校验每个来自 renderer 的 viewport,并拒绝不高于通道当前版本的 viewport。renderer 从未发送的 generation 的帧不予呈现,无论 producer 确认了什么。 +- **插件看不到什么。** 插件拿不到 Mach 端口、Win32 句柄传递、Electron,也拿不到 Desktop 内部的纹理接口,这些接口不支持插件使用。Host 插件从加载到卸载持有 Desktop Host `sharedTexture` 服务的唯一认领,Client 插件从启动到销毁消费 Client 的 `sharedTexture` 服务,因此二者的其他消费者都会立即失败。若其他消费者先取得 `sharedTexture` 的认领,帧转发会报告 `desktop-shared-texture-claimed`,直到它自身或 Desktop Host 的 `sharedTexture` 服务重新加载;对方释放认领时,帧转发不会接手。Host 到 Main 的边界是 Desktop 自己审计的边界,不随本包变化。 + +----- + + +## 实现说明 + +工作区将[原生接收器](native/receiver.cc)和传输源码放在插件目录,由 Desktop 按目标架构编译。插件 npm 包不含原生源码和二进制文件。每个通道是一个稳定的监听端;每个 producer 连接拥有自己的 Mach 端口或管道实例、帧与分配、信用和中继状态,[通道记录](../../../.agents/notes/implemented/architecture/2026-10-18-frame-forwarding-channels.zh.md)持有交接的理由。producer 的 GPU 与 Chromium 的不同时,Windows 接收器把每一帧读回并上传到 Chromium 的 adapter,读回后即归还 producer 的信用;producer 标记为可替换的帧(`frame_replaceable`,由 `dsh_frame_forwarding_submit_latest` 设置)随后会替换尚未开始上传的已暂存可替换帧,而请求帧按顺序保持排队。 + +Windows 中继按分配保留跨 staging 槽使用的导入纹理,仅为同一 NT 对象且尺寸一致的帧复用。分配退役时先清除缓存导入再返还额度;未完成的 GPU 复制继续持有其源纹理直至完成。 + +Host 的 [forwarder](src/host/forwarder.ts) 在一个共享预算下创建接收器,跟随每个通道的连接,保存 renderer 最新的 viewport 并向每个新连接重放,把每个 viewport 请求绑定到接收它的连接,把 `sharedTexture.nativeSink` 返回的原生 sink 挂到每个接收器上,并持续更新每个接收器的呈现门控:最新 viewport 可见时,放行当前连接发来、generation 不超过该 viewport 版本的帧,包括更早的 generation。门控在每个 viewport 发出前就已更新:即使帧到达接收器时 Host 的 JavaScript 还没处理对应的确认,该帧也能通过。接收器在原生代码里经该 sink 以 Host 本地句柄和帧元数据呈现通过门控的每一帧,帧不经过 Host 的 JavaScript;门控之外或元数据无效的帧立即归还给 producer。交付只在 Desktop 结算该呈现后才归还给接收器;`invalidated` 结算会让接收器先停止再释放该帧,随后 forwarder 以 `lost` 关闭通道,呈现失败则作为 `presentation` 错误报告给 renderer 而不关闭通道。仅由 Desktop 拒绝的单帧(例如达到其呈现上限时)就是这样一种失败,接收器的 sink 保持挂载;sink 与 Main 的连接丢失时,接收器解除该 sink,把下一帧交给 forwarder,forwarder 把它归还给 producer,并为每个通道挂上新的 sink。Windows 上,每个通道都从 `sharedTexture.adapterLuid()` 取得 Chromium 合成器的 adapter,即 Desktop Main 从合成器导出的纹理读出、并在 Chromium 的 GPU 进程重启后重新读取的 LUID,因此每个通道都跟随 Chromium 当前的 adapter。Host 插件是一个 Typert Remote 服务:`viewport` 把 renderer 的 viewport 应用到通道。每次调用 `events(signal)` 都会替换上一次订阅,向当前 renderer 先发送所有通道状态的快照,再发送带递增序号的状态和标明来源的帧错误;超出 `maxQueuedEvents` 的未读事件改为一份新快照。 + +Client 半边从启动到销毁都消费 Client 的 `sharedTexture` 服务(由共享纹理 Client 插件从 Desktop preload 桥接提供,没有打开的通道时也是如此),按元数据中的 `rx` 把每个纹理路由到其接收通道并释放不带元数据的纹理,通过 `viewport` Remote 发送 viewport,并按序号应用通道状态,每份快照替换它已知的状态;新快照中缺失的通道报告为 `lost`,因为 renderer 无法得知它为何关闭。已关闭通道的状态保留到其消费者解除挂载;没有消费者的已关闭通道只保留最新的 64 个,以便迟到的消费者仍能得知其关闭。关闭接收通道时,Client 先移除它的帧与事件回调,再通知关闭监听器,因此监听器可以重新连接同一 `rx`。[接收通道](src/client/rx.ts)只持有正在绘制的帧、其后至多一帧最新的流帧,以及连接状态尚未到达的帧,因此 Host 的每通道上限即可约束 renderer,无需自己的队列。Client 还记录是哪个通道请求了全屏元素,并把每次 `fullscreenchange` 报告给每个通道;全屏元素被另一个元素取代后,原通道不再持有全屏。 + +Desktop 内部的共享纹理服务、Mach ingress 以及把句柄带进 Electron Main 的跳转归 [Desktop 应用](../../../apps/desktop/README.zh.md)所有;本包持有它们唯一的认领,[设计记录](../../../.agents/notes/implemented/architecture/2026-10-15-desktop-shared-texture-api.zh.md)持有归属的理由。 + +----- + + +## 模型体验 + +无:帧转发只在进程间搬运像素,不增加模型上下文或 Session 事件。 + +#### KV Cache effect + +无。 + +## 已知限制和后续工作 + + + +- 滚动或缩放时,视频播放与 CSS 位置可能在不同帧更新;提交 generation 不表示画面已经上屏。 +- 仅支持 macOS 和 Windows Desktop;其他 Host 报告 `unsupported-platform` 或 `desktop-shared-texture-unavailable`。 +- Desktop 在 renderer 导入纹理后才应答一次呈现,因此 renderer 主线程阻塞超过 `requestTimeoutMs`(默认 10 s)时该帧报告失败,且只在 Desktop 结算后才归还其 producer;更短的卡顿在 renderer 恢复时送达 producer 的最新帧。 +- renderer 侧消费者的失败,Host 不会得知;消费者在对该接收通道的下一次操作被拒绝时才会发现。 +- 保持在线但停止响应的 producer 会一直占用其通道,直到它退出或通道关闭;没有任何机制抢占它。 +- 每个连接最多可有 256 条等待 Host JavaScript 处理的 producer 事件:消息、呈现错误和未交给 Desktop 的帧。超限时,接收器只断开该 producer 并报告原因;通道保持打开,排空后后继 producer 可用同一个 `tx` 连接。有一条 `rejected` 告警待处理时,接收器会合并后续拒绝告警。此上限按连接而非整个接收器计算:JavaScript 停顿期间,连续多个短连接的生命周期通知仍可能积压。 +- GPU 进程退出、renderer 退出、已提交的导航或窗口关闭会让画面上的纹理失效并以 `lost` 关闭其通道;消费者需打开新通道才能继续。 +- 协议 1 的 producer 和接收器(例如 LibreOffice Kit 0.2.3 及更早的 SDK)会被拒绝;producer、接收器和引擎须一起升级。 +- Escape 总会退出全屏:Client 不使用 Keyboard Lock,因此游戏这类消费者无法把 Escape 留给自己。 +- 在 Windows 上,接收器打开每个 producer 进程以复制其帧句柄,因此 producer 必须以 Host 的用户身份、在不高于 Host 的完整性级别下运行。接收器无法打开权限高于 Host 的 producer,会在握手时关闭该连接,且 Host 不记录诊断。 +- Windows 上接收端只保留一个监听管道实例,把当前实例交给候选连接之后才打开下一个;因此 Host 用户的某个进程若每隔几毫秒就用错误凭据连接一次,可以让管道一直处于忙碌状态。producer 遇到忙碌的管道会一直重试到连接期限(默认 10 秒,或传给 `dsh_frame_forwarding_connect_with_options` 的超时);只有管道名称连续 500 ms 不存在时才会提前放弃,而每次收到忙碌回复都会重新计时。因此这种风暴只有持续到期限才会让 producer 失败:报 `receiver unavailable`,传了超时则报 `connection cancelled or timed out`。再保留一个监听实例即可消除这段空档。 +- 在 Windows 上,当 producer 的 GPU 与 Chromium 的不同时,producer 为不可见视图收缩时只归还源分配,不归还中继目标与暂存 surface:它们按最大分配尺寸继续占用显存和 `maxBytes` 份额,直到连接结束。 + + +### 开发备注 + +
+维护者工作上下文 + +[原生 e2e](tests/receiver-native.e2e.ts) 编译测试用 producer,并用复制的凭据连接独立的 producer 进程,在崩溃后待扣住的帧释放即接管,拒绝测试用的其他协议版本、不具备可转交通道或不具备 producer-local handles 的 producer,并把被收缩的 producer 的空闲分配交给共享其预算的另一个通道。[Desktop 桥 e2e](tests/desktop-bridge-native.e2e.ts) 挂载实现 Desktop sink ABI 的 fixture sink:可交付状态之外的帧和 metadata 非法的帧不提交、直接归还信用;提交的帧以其标识作为 metadata,sink 释放后归还信用;invalidated 结算先停止通道再释放;Desktop 拒绝单帧时 sink 保持挂载,sink 失去连接时被解除,之后的帧交给 JavaScript;receiver 关闭后到达的结算也是安全的;Desktop 的 addon 已构建时,帧经 Desktop 的 hop sink 送进 Desktop 的 ingress 并遵循 Main 的结算。[Kit 帧 e2e](tests/kit-frames-native.e2e.ts) 在已安装 Kit 的 LibreOffice 进程中打开一份两页演示文稿,把其帧转给进程内的 Desktop 并读取 IOSurface 像素:按请求渲染的帧以其标识符到达、释放后归还信用;Desktop 扣住全部放映帧时放映状态仍继续推进,随后释放一帧即送达最新的幻灯片;正常替换和崩溃后的替代引擎都只在前一个引擎的帧释放后连接,并以重放的 viewport 渲染;已安装 Kit 的协议版本与本接收器不同时跳过该 e2e。原生测试均在 macOS 上构建 Desktop 原生模块 后用 `pnpm exec vitest run --config vitest.e2e.config.ts packages/experimental/frame-forwarding` 运行;Desktop 桥 e2e 也在 Windows 上运行。 + +
diff --git a/packages/experimental/frame-forwarding/locale/de.json b/packages/experimental/frame-forwarding/locale/de.json new file mode 100644 index 0000000000..babc8439b1 --- /dev/null +++ b/packages/experimental/frame-forwarding/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Frame-Weiterleitung", + "description": "Zeigt Frames, die native Prozesse von Host-Plugins rendern, ohne Kopieren von Pixeln im Desktop-Fenster an." + } +} diff --git a/packages/experimental/frame-forwarding/locale/en.json b/packages/experimental/frame-forwarding/locale/en.json new file mode 100644 index 0000000000..fc222d94a5 --- /dev/null +++ b/packages/experimental/frame-forwarding/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Frame forwarding", + "description": "Shows frames that native processes of Host plugins render in the Desktop window without copying pixels." + } +} diff --git a/packages/experimental/frame-forwarding/locale/es.json b/packages/experimental/frame-forwarding/locale/es.json new file mode 100644 index 0000000000..28ab5481b5 --- /dev/null +++ b/packages/experimental/frame-forwarding/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Reenvío de fotogramas", + "description": "Muestra en la ventana de Desktop los fotogramas que renderizan los procesos nativos de los plugins de Host, sin copiar píxeles." + } +} diff --git a/packages/experimental/frame-forwarding/locale/fr.json b/packages/experimental/frame-forwarding/locale/fr.json new file mode 100644 index 0000000000..8d9455cabd --- /dev/null +++ b/packages/experimental/frame-forwarding/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Transfert d'images", + "description": "Affiche dans la fenêtre Desktop les images que rendent les processus natifs des plugins Host, sans copier de pixels." + } +} diff --git a/packages/experimental/frame-forwarding/locale/ja.json b/packages/experimental/frame-forwarding/locale/ja.json new file mode 100644 index 0000000000..b688fd40b1 --- /dev/null +++ b/packages/experimental/frame-forwarding/locale/ja.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "フレーム転送", + "description": "Host プラグインのネイティブプロセスが描画したフレームを、ピクセルをコピーせずに Desktop ウィンドウに表示します。" + } +} diff --git a/packages/experimental/frame-forwarding/locale/pt.json b/packages/experimental/frame-forwarding/locale/pt.json new file mode 100644 index 0000000000..0f25020a88 --- /dev/null +++ b/packages/experimental/frame-forwarding/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Encaminhamento de quadros", + "description": "Mostra na janela do Desktop os quadros que os processos nativos dos plugins do Host renderizam, sem copiar pixels." + } +} diff --git a/packages/experimental/frame-forwarding/locale/ru.json b/packages/experimental/frame-forwarding/locale/ru.json new file mode 100644 index 0000000000..77792ba13a --- /dev/null +++ b/packages/experimental/frame-forwarding/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Пересылка кадров", + "description": "Показывает в окне Desktop кадры, которые отрисовывают нативные процессы плагинов Host, без копирования пикселей." + } +} diff --git a/packages/experimental/frame-forwarding/locale/zh.json b/packages/experimental/frame-forwarding/locale/zh.json new file mode 100644 index 0000000000..17beda2787 --- /dev/null +++ b/packages/experimental/frame-forwarding/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "帧转发", + "description": "把 Host 插件的原生进程渲染的帧显示在 Desktop 窗口中,无需复制像素。" + } +} diff --git a/packages/experimental/frame-forwarding/native/LICENSE b/packages/experimental/frame-forwarding/native/LICENSE new file mode 100644 index 0000000000..c1f7a78e89 --- /dev/null +++ b/packages/experimental/frame-forwarding/native/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 DeepSeek + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/experimental/frame-forwarding/native/desktop-bridge.cc b/packages/experimental/frame-forwarding/native/desktop-bridge.cc new file mode 100644 index 0000000000..f0c16db694 --- /dev/null +++ b/packages/experimental/frame-forwarding/native/desktop-bridge.cc @@ -0,0 +1,404 @@ +/** Non-template part of the Desktop sink bridge: sink ownership, metadata JSON, and the JavaScript argument checks. */ +#include "desktop-bridge.h" +#include +#include +#include +#include +#include +#include +#if defined(_WIN32) +#include +#else +#include +#endif + +namespace dsh_frame_forwarding { +namespace desktop_bridge { +namespace { + +constexpr double kMaxSafeInteger = 9007199254740991.0; +constexpr size_t kMaxRequestId = 512; +constexpr size_t kMaxRx = 128; +constexpr uint32_t kMaxTimeoutMs = 30000; + +/** Decode one code point at `at` the way the WHATWG UTF-8 decoder does, consuming the maximal invalid subpart. */ +uint32_t decode_utf8(const unsigned char*& at, const unsigned char* end) { + const unsigned char lead = *at++; + if (lead < 0x80) return lead; + uint32_t code; int needed; unsigned char lower = 0x80, upper = 0xBF; + if (lead >= 0xC2 && lead <= 0xDF) { needed = 1; code = lead & 0x1F; } + else if (lead >= 0xE0 && lead <= 0xEF) { needed = 2; code = lead & 0x0F; if (lead == 0xE0) lower = 0xA0; if (lead == 0xED) upper = 0x9F; } + else if (lead >= 0xF0 && lead <= 0xF4) { needed = 3; code = lead & 0x07; if (lead == 0xF0) lower = 0x90; if (lead == 0xF4) upper = 0x8F; } + else return 0xFFFD; + while (needed-- > 0) { + if (at == end || *at < lower || *at > upper) return 0xFFFD; + code = (code << 6) | (*at++ & 0x3F); + lower = 0x80; upper = 0xBF; + } + return code; +} + +void append_utf16(std::u16string& out, uint32_t code) { + if (code < 0x10000) { out.push_back(static_cast(code)); return; } + code -= 0x10000; + out.push_back(static_cast(0xD800 + (code >> 10))); + out.push_back(static_cast(0xDC00 + (code & 0x3FF))); +} + +void append_utf8(std::string& out, uint32_t code) { + if (code < 0x80) out.push_back(static_cast(code)); + else if (code < 0x800) { out.push_back(static_cast(0xC0 | (code >> 6))); out.push_back(static_cast(0x80 | (code & 0x3F))); } + else if (code < 0x10000) { + out.push_back(static_cast(0xE0 | (code >> 12))); out.push_back(static_cast(0x80 | ((code >> 6) & 0x3F))); + out.push_back(static_cast(0x80 | (code & 0x3F))); + } else { + out.push_back(static_cast(0xF0 | (code >> 18))); out.push_back(static_cast(0x80 | ((code >> 12) & 0x3F))); + out.push_back(static_cast(0x80 | ((code >> 6) & 0x3F))); out.push_back(static_cast(0x80 | (code & 0x3F))); + } +} + +void append_escape(std::string& out, char16_t unit) { + static const char hex[] = "0123456789abcdef"; + out += "\\u"; + for (int shift = 12; shift >= 0; shift -= 4) out.push_back(hex[(unit >> shift) & 0xF]); +} + +/** The JSON string literal `JSON.stringify` writes for UTF-16 text, escaping lone surrogates. */ +std::string json_string(const std::u16string& text) { + std::string out = "\""; + for (size_t index = 0; index < text.size(); ++index) { + const char16_t unit = text[index]; + switch (unit) { + case u'"': out += "\\\""; continue; + case u'\\': out += "\\\\"; continue; + case u'\b': out += "\\b"; continue; + case u'\f': out += "\\f"; continue; + case u'\n': out += "\\n"; continue; + case u'\r': out += "\\r"; continue; + case u'\t': out += "\\t"; continue; + default: break; + } + if (unit < 0x20) append_escape(out, unit); + else if (unit >= 0xD800 && unit <= 0xDBFF && index + 1 < text.size() && text[index + 1] >= 0xDC00 && text[index + 1] <= 0xDFFF) { + append_utf8(out, 0x10000 + ((static_cast(unit) - 0xD800) << 10) + (text[index + 1] - 0xDC00)); + ++index; + } else if (unit >= 0xD800 && unit <= 0xDFFF) append_escape(out, unit); + else append_utf8(out, unit); + } + return out + "\""; +} + +/** A number in C notation regardless of the process locale. */ +double parse_double(const std::string& text) { +#if defined(_WIN32) + static const _locale_t classic = _create_locale(LC_NUMERIC, "C"); + return _strtod_l(text.c_str(), nullptr, classic); +#else + static const locale_t classic = newlocale(LC_NUMERIC_MASK, "C", nullptr); + return strtod_l(text.c_str(), nullptr, classic); +#endif +} + +/** RFC 8259 reader over NUL-terminated UTF-8, with `JSON.parse` value semantics. */ +class Reader { + public: + explicit Reader(const char* text) : at_(reinterpret_cast(text)), end_(at_ + std::strlen(text)) {} + + std::string producer_frame(ProducerFrame& frame) { + enum class Field { missing, invalid, present }; + Field request = Field::missing, generation = Field::missing, revision = Field::missing; + std::u16string request_id; + double generation_value = 0, revision_value = 0; + space(); + if (at_ == end_ || *at_ != '{') return skip() && (space(), at_ == end_) ? "metadata is not a JSON object" : "metadata is not valid JSON"; + ++at_; space(); + if (at_ != end_ && *at_ == '}') ++at_; + else for (;;) { + std::u16string key; + if (!string(&key)) return "metadata is not valid JSON"; + space(); + if (at_ == end_ || *at_++ != ':') return "metadata is not valid JSON"; + space(); + bool valid; + if (key == u"requestId") { + const bool text = at_ != end_ && *at_ == '"'; + request_id.clear(); + valid = text ? string(&request_id) : skip(); + request = text ? Field::present : Field::invalid; + } else if (key == u"generation" || key == u"revision") { + const bool numeric = at_ != end_ && (*at_ == '-' || (*at_ >= '0' && *at_ <= '9')); + auto& value = key == u"generation" ? generation_value : revision_value; + valid = numeric ? number(&value) : skip(); + (key == u"generation" ? generation : revision) = numeric ? Field::present : Field::invalid; + } else valid = skip(); + if (!valid) return "metadata is not valid JSON"; + space(); + if (at_ == end_) return "metadata is not valid JSON"; + const unsigned char next = *at_++; + if (next == '}') break; + if (next != ',') return "metadata is not valid JSON"; + space(); + } + space(); + if (at_ != end_) return "metadata is not valid JSON"; + if (request != Field::present || request_id.empty() || request_id.size() > kMaxRequestId) + return "requestId must be a string of 1 to 512 characters"; + if (generation != Field::present || !safe(generation_value)) return "generation must be an integer from 0 to 9007199254740991"; + if (revision != Field::present || !safe(revision_value)) return "revision must be an integer from 0 to 9007199254740991"; + frame.request_id = json_string(request_id); + frame.generation = static_cast(generation_value); + frame.revision = static_cast(revision_value); + return {}; + } + + private: + static bool safe(double value) { return value >= 0 && value <= kMaxSafeInteger && std::floor(value) == value; } + + void space() { while (at_ != end_ && (*at_ == ' ' || *at_ == '\t' || *at_ == '\n' || *at_ == '\r')) ++at_; } + + bool hex(char16_t& unit) { + unit = 0; + for (int digit = 0; digit < 4; ++digit) { + if (at_ == end_) return false; + const unsigned char next = *at_++; + unit = static_cast(unit << 4); + if (next >= '0' && next <= '9') unit = static_cast(unit | (next - '0')); + else if (next >= 'a' && next <= 'f') unit = static_cast(unit | (next - 'a' + 10)); + else if (next >= 'A' && next <= 'F') unit = static_cast(unit | (next - 'A' + 10)); + else return false; + } + return true; + } + + /** One string, whose UTF-16 units go to `out` when given. */ + bool string(std::u16string* out) { + if (at_ == end_ || *at_ != '"') return false; + ++at_; + for (;;) { + if (at_ == end_) return false; + const unsigned char next = *at_; + if (next == '"') { ++at_; return true; } + if (next < 0x20) return false; + if (next != '\\') { + const auto code = decode_utf8(at_, end_); + if (out) append_utf16(*out, code); + continue; + } + ++at_; + if (at_ == end_) return false; + char16_t unit; + switch (*at_++) { + case '"': unit = u'"'; break; + case '\\': unit = u'\\'; break; + case '/': unit = u'/'; break; + case 'b': unit = u'\b'; break; + case 'f': unit = u'\f'; break; + case 'n': unit = u'\n'; break; + case 'r': unit = u'\r'; break; + case 't': unit = u'\t'; break; + case 'u': if (!hex(unit)) return false; break; + default: return false; + } + if (out) out->push_back(unit); + } + } + + bool digits() { + const auto start = at_; + while (at_ != end_ && *at_ >= '0' && *at_ <= '9') ++at_; + return at_ != start; + } + + /** One number, whose value goes to `out` when given. */ + bool number(double* out) { + const auto start = at_; + if (at_ != end_ && *at_ == '-') ++at_; + if (at_ != end_ && *at_ == '0') ++at_; + else if (!digits()) return false; + bool integral = true; + if (at_ != end_ && *at_ == '.') { ++at_; integral = false; if (!digits()) return false; } + if (at_ != end_ && (*at_ == 'e' || *at_ == 'E')) { + ++at_; integral = false; + if (at_ != end_ && (*at_ == '+' || *at_ == '-')) ++at_; + if (!digits()) return false; + } + if (!out) return true; + const std::string text(start, at_); + if (integral && text.size() <= 15) { + double value = 0; + for (const char digit : text) if (digit != '-') value = value * 10 + (digit - '0'); + *out = text[0] == '-' ? -value : value; + } else *out = parse_double(text); + return true; + } + + bool literal(const char* word) { + const auto size = std::strlen(word); + if (static_cast(end_ - at_) < size || std::memcmp(at_, word, size) != 0) return false; + at_ += size; + return true; + } + + /** One value of any nesting depth, validated without recursion. */ + bool skip() { + std::vector open; + for (;;) { + space(); + if (at_ == end_) return false; + const unsigned char next = *at_; + bool scalar = true; + if (next == '{' || next == '[') { + ++at_; space(); + const unsigned char close = next == '{' ? '}' : ']'; + if (at_ != end_ && *at_ == close) ++at_; + else { + open.push_back(close); + scalar = false; + if (close == '}') { + if (!string(nullptr)) return false; + space(); + if (at_ == end_ || *at_++ != ':') return false; + } + } + } else if (next == '"') { if (!string(nullptr)) return false; } + else if (next == '-' || (next >= '0' && next <= '9')) { if (!number(nullptr)) return false; } + else if (!literal("true") && !literal("false") && !literal("null")) return false; + if (!scalar) continue; + // A complete value closes containers until one continues with another member or element. + for (;;) { + if (open.empty()) return true; + space(); + if (at_ == end_) return false; + const unsigned char after = *at_++; + if (after == open.back()) { open.pop_back(); continue; } + if (after != ',') return false; + if (open.back() == '}') { + space(); + if (!string(nullptr)) return false; + space(); + if (at_ == end_ || *at_++ != ':') return false; + } + break; + } + } + } + + const unsigned char* at_; + const unsigned char* end_; +}; + +bool named(napi_env env, napi_value object, const char* name, napi_value& value) { + bool has = false; + return napi_has_named_property(env, object, name, &has) == napi_ok && has && napi_get_named_property(env, object, name, &value) == napi_ok; +} + +bool integer(napi_env env, napi_value value, double minimum, double maximum, double& out) { + return napi_get_value_double(env, value, &out) == napi_ok && std::isfinite(out) && out >= minimum && out <= maximum && std::floor(out) == out; +} + +napi_value undefined(napi_env env) { napi_value result; napi_get_undefined(env, &result); return result; } + +} // namespace + +std::string parse_producer_frame(const char* text, ProducerFrame& frame) { return Reader(text).producer_frame(frame); } + +std::string json_string(const std::string& text) { + std::u16string units; + auto at = reinterpret_cast(text.data()); + const auto end = at + text.size(); + while (at != end) append_utf16(units, decode_utf8(at, end)); + return json_string(units); +} + +std::string error_text(const char* source, const std::string& request_id, const std::string& error) { + return std::string("{\"source\":\"") + source + "\"" + (request_id.empty() ? "" : ",\"requestId\":" + request_id) + + ",\"error\":" + json_string(error) + "}"; +} + +AttachedSink::AttachedSink(dsh_shared_texture_sink_v2* sink, const std::string& rx, uint32_t timeout_ms) + : sink(sink), rx_json(json_string(rx)), timeout_ms(timeout_ms) { + sink->retain(sink->ctx); +} + +void Bridge::attach(dsh_shared_texture_sink_v2* sink, const std::string& rx, uint32_t timeout_ms, std::weak_ptr owner) { + auto attached = std::make_shared(sink, rx, timeout_ms); + { + std::lock_guard lock(mutex_); + attached_.swap(attached); + owner_ = std::move(owner); + } + // `attached` now holds the previous sink, released outside the lock. +} + +void Bridge::set_deliverable(const Deliverable* state) { + std::lock_guard lock(mutex_); + has_deliverable_ = state != nullptr; + deliverable_ = state ? *state : Deliverable{}; +} + +bool Bridge::lease(Lease& lease) { + std::lock_guard lock(mutex_); + if (!attached_) return false; + lease.owner = owner_.lock(); + if (!lease.owner) return false; + lease.attached = attached_; + lease.has_deliverable = has_deliverable_; + lease.deliverable = deliverable_; + return true; +} + +void Bridge::detach(const dsh_shared_texture_sink_v2* sink) { + std::shared_ptr detached; + { + std::lock_guard lock(mutex_); + if (!attached_ || attached_->sink != sink) return; + detached.swap(attached_); + } +} + +napi_value throw_error(napi_env env, const char* text) { + napi_throw_error(env, nullptr, text); + return nullptr; +} + +napi_value attach(napi_env env, const napi_value* args, Bridge& bridge, std::weak_ptr owner) { + size_t length = 0; + if (napi_get_value_string_utf8(env, args[0], nullptr, 0, &length) != napi_ok || length < 1 || length > kMaxRx) + return throw_error(env, "Expected an rx of 1 to 128 printable ASCII characters"); + std::string rx(length, '\0'); + napi_get_value_string_utf8(env, args[0], &rx[0], length + 1, &length); + for (const char character : rx) { + if (character < 0x20 || character > 0x7E) return throw_error(env, "Expected an rx of 1 to 128 printable ASCII characters"); + } + napi_valuetype type; + void* data = nullptr; + if (napi_typeof(env, args[1], &type) != napi_ok || type != napi_external || napi_get_value_external(env, args[1], &data) != napi_ok || !data) + return throw_error(env, "Expected a Desktop shared-texture sink external"); + auto sink = static_cast(data); + if (sink->magic != DSH_SHARED_TEXTURE_SINK_MAGIC || sink->version != DSH_SHARED_TEXTURE_SINK_VERSION) + return throw_error(env, "Unsupported Desktop shared-texture sink ABI"); + double timeout = 0; + if (!integer(env, args[2], 1, kMaxTimeoutMs, timeout)) return throw_error(env, "Expected a presentation timeout of 1 to 30000 ms"); + bridge.attach(sink, rx, static_cast(timeout), std::move(owner)); + return undefined(env); +} + +napi_value set_deliverable(napi_env env, napi_value state, Bridge& bridge) { + napi_valuetype type; + if (napi_typeof(env, state, &type) != napi_ok) return throw_error(env, "Expected a deliverable state or null"); + if (type == napi_null) { bridge.set_deliverable(nullptr); return undefined(env); } + napi_value connection, visible, generation; + Deliverable deliverable; + double connection_id = 0, max_generation = 0; + if (type != napi_object || !named(env, state, "connectionId", connection) || !named(env, state, "visible", visible) + || !named(env, state, "maxGeneration", generation) || !integer(env, connection, 1, kMaxSafeInteger, connection_id) + || napi_get_value_bool(env, visible, &deliverable.visible) != napi_ok || !integer(env, generation, 0, kMaxSafeInteger, max_generation)) + return throw_error(env, "Expected { connectionId, visible, maxGeneration } or null"); + deliverable.connection = static_cast(connection_id); + deliverable.max_generation = static_cast(max_generation); + bridge.set_deliverable(&deliverable); + return undefined(env); +} + +} // namespace desktop_bridge +} // namespace dsh_frame_forwarding diff --git a/packages/experimental/frame-forwarding/native/desktop-bridge.h b/packages/experimental/frame-forwarding/native/desktop-bridge.h new file mode 100644 index 0000000000..1c666ff13f --- /dev/null +++ b/packages/experimental/frame-forwarding/native/desktop-bridge.h @@ -0,0 +1,296 @@ +/** + * Native hand-off of received frames to Desktop's `shared-texture-hop.node` through its `dsh_shared_texture_sink_v2` + * (declared below with the field order and types of Desktop's `shared-texture-sink.h`; a sink of another ABI version + * is refused). While a sink is attached, every frame event of the receiver is presented from the thread that produced + * it, and Desktop's callbacks return the frame's credit, so steady-state frames never reach JavaScript; without a sink, + * frames reach JavaScript as `frame` events. JavaScript attaches the sink with `attachSink(native, rx, sink, timeoutMs)` + * and supplies the presentation gate with `setDeliverable(native, { connectionId, visible, maxGeneration } | null)`. + * + * Per frame, once the receiver still accepts frames of its connection, the frame is marked delivered and then: + * metadata other than a JSON object with a `requestId` string of 1-512 UTF-16 units and `generation` and `revision` + * integers from 0 to 2^53-1 releases the delivery and emits `presentation-error` with source `producer`; a frame of + * another connection than the deliverable state, while it is invisible or absent, or whose generation exceeds + * `maxGeneration` releases the delivery silently; otherwise the frame is presented with the producer fields plus `rx`, + * `connectionId`, `frameId`, `width`, and `height` as metadata. When `present` returns nonzero, the bridge releases the + * delivery and emits `presentation-error` with source `presentation`. When it returns + * `DSH_SHARED_TEXTURE_PRESENT_REJECTED`, Desktop refused only that frame (its presentation limit, invalid frame fields, + * a send timeout), so the sink stays attached and presents later frames; any other nonzero result means the sink lost + * its connection, and the bridge detaches that sink when it is still attached, so later frames reach JavaScript until + * it attaches a sink again. A failed delivery emits `presentation-error`; a released + * settlement releases the delivery; an invalidated settlement emits `presentation-invalidated`, then stops the receiver + * and the frame's connection before releasing the delivery, so the notice is queued before stopping lets the listener + * release the dispatcher, and the producer never regains that texture's credit. `presentation-error` text is + * JSON: `{ "source": "producer" | "presentation", "requestId"?: string, "error": string }`. + * + * Threads and locks: frame events reach the bridge from connection threads that hold no receiver, connection, or + * ledger lock. The bridge lock guards only the attached sink with its immutable attach parameters, and the + * deliverable state, and is never held while calling into the sink or the receiver; Desktop's callbacks may run on the + * hop's reader thread before `present` returns, or on the calling thread, so each request's callback data is complete + * before the call. The bridge retains a sink once per attach and releases it when it is replaced, detached, or the + * bridge is destroyed and no frame being presented still shares it. + * + * Lifetime: the bridge is a member of the receiver and releases its sink reference when the receiver is destroyed. + * Each presented request holds a strong reference to the receiver until its settlement, so callbacks that arrive + * after `close`, after JavaScript drops the receiver, or during environment teardown act on a live receiver: `stop` + * and `release` stay safe after close, and events are discarded once the dispatcher closed. The last reference can + * drop on the hop's reader thread only after the receiver's listener thread was joined (the completion holder keeps a + * reference until then, and the environment cleanup hook joins it during teardown), and that thread joins every + * connection thread, so destroying the receiver there joins no thread. Callbacks run code of this addon, which Node + * keeps loaded for the life of the process. + */ +#ifndef DSH_FRAME_FORWARDING_DESKTOP_BRIDGE_H +#define DSH_FRAME_FORWARDING_DESKTOP_BRIDGE_H + +#include +#include +#include +#include +#include +#include + +extern "C" { +#define DSH_SHARED_TEXTURE_SINK_MAGIC 0x44535453u +#define DSH_SHARED_TEXTURE_SINK_VERSION 2u +/** `present` results: the request left the Host; Desktop refused only this frame; the sink lost its connection. */ +#define DSH_SHARED_TEXTURE_PRESENT_OK 0 +#define DSH_SHARED_TEXTURE_PRESENT_REJECTED 1 +#define DSH_SHARED_TEXTURE_PRESENT_DISCONNECTED 2 +typedef struct dsh_shared_texture_callbacks_v2 { + void* user_data; + void (*on_delivered)(void* user_data, const char* error); + void (*on_settled)(void* user_data, int invalidated); +} dsh_shared_texture_callbacks_v2; +typedef struct dsh_shared_texture_frame_v2 { + uintptr_t handle; + uint32_t width; + uint32_t height; + uint32_t timeout_ms; + uint8_t pixel_format; + const char* metadata_json; + size_t metadata_len; +} dsh_shared_texture_frame_v2; +typedef struct dsh_shared_texture_sink_v2 { + uint32_t magic; + uint32_t version; + void* ctx; + void (*retain)(void* ctx); + void (*release)(void* ctx); + int (*present)(void* ctx, const dsh_shared_texture_frame_v2* frame, const dsh_shared_texture_callbacks_v2* cb, + char* err_buf, size_t err_cap); +} dsh_shared_texture_sink_v2; +} + +namespace dsh_frame_forwarding { +namespace desktop_bridge { + +/** Frames JavaScript lets the bridge present: those of `connection` up to `max_generation` while `visible`. */ +struct Deliverable { + uint64_t connection = 0; + bool visible = false; + uint64_t max_generation = 0; +}; + +/** Validated producer fields of one frame's metadata. */ +struct ProducerFrame { + /** `requestId` as a JSON string literal. */ + std::string request_id; + uint64_t generation = 0, revision = 0; +}; + +/** + * Validate producer metadata as `JSON.parse` followed by the Host's producer-frame schema would. + * @returns Empty when valid, otherwise the reason. + */ +std::string parse_producer_frame(const char* text, ProducerFrame& frame); +/** @returns `text`, read as UTF-8 with invalid sequences replaced, as the JSON string literal `JSON.stringify` writes. */ +std::string json_string(const std::string& text); +/** @returns `presentation-error` event text. `request_id` is a JSON string literal or empty. */ +std::string error_text(const char* source, const std::string& request_id, const std::string& error); + +/** One attach: a sink reference and the attach parameters, which never change; releases the reference when destroyed. */ +struct AttachedSink { + dsh_shared_texture_sink_v2* sink; + /** `rx` as a JSON string literal. */ + std::string rx_json; + uint32_t timeout_ms; + /** Retain `sink`. */ + AttachedSink(dsh_shared_texture_sink_v2* sink, const std::string& rx, uint32_t timeout_ms); + AttachedSink(const AttachedSink&) = delete; + AttachedSink& operator=(const AttachedSink&) = delete; + ~AttachedSink() { if (sink) sink->release(sink->ctx); } +}; + +/** The attached sink, the receiver, and the presentation gate, taken for one frame. */ +struct Lease { + std::shared_ptr attached; + std::shared_ptr owner; + bool has_deliverable = false; + Deliverable deliverable; +}; + +/** The attached sink and presentation gate of one receiver. */ +class Bridge { + public: + Bridge() = default; + Bridge(const Bridge&) = delete; + Bridge& operator=(const Bridge&) = delete; + /** Retain `sink` and attach it, releasing a previously attached one once no frame being presented shares it. */ + void attach(dsh_shared_texture_sink_v2* sink, const std::string& rx, uint32_t timeout_ms, std::weak_ptr owner); + /** Replace the presentation gate; null closes it. */ + void set_deliverable(const Deliverable* state); + /** @returns False when no sink is attached or the receiver is gone; otherwise `lease` shares the attached sink. */ + bool lease(Lease& lease); + /** Detach `sink` when it is still the attached sink; its reference is released once no frame shares it. */ + void detach(const dsh_shared_texture_sink_v2* sink); + + private: + std::mutex mutex_; + std::shared_ptr attached_; + std::weak_ptr owner_; + bool has_deliverable_ = false; + Deliverable deliverable_; +}; + +/** `attachSink(native, rx, sink, timeoutMs)` after the receiver holder is resolved. */ +napi_value attach(napi_env env, const napi_value* args, Bridge& bridge, std::weak_ptr owner); +/** `setDeliverable(native, state)` after the receiver holder is resolved. */ +napi_value set_deliverable(napi_env env, napi_value state, Bridge& bridge); +napi_value throw_error(napi_env env, const char* text); + +/** The receiver's shared owner held by a `native` external; throws and returns null for another value. */ +template std::shared_ptr* holder(napi_env env, napi_value value) { + void* result = nullptr; + if (napi_get_value_external(env, value, &result) != napi_ok || !result) { + napi_throw_type_error(env, nullptr, "Invalid native receiver"); + return nullptr; + } + return static_cast*>(result); +} + +template napi_value attach_sink(napi_env env, napi_callback_info info) { + napi_value args[4]; size_t count = 4; + napi_get_cb_info(env, info, &count, args, nullptr, nullptr); + if (count != 4) return throw_error(env, "Expected receiver, rx, sink and timeout"); + auto owner = holder(env, args[0]); + if (!owner) return nullptr; + return attach(env, args + 1, (*owner).get()->*member, std::weak_ptr(*owner)); +} + +template napi_value set_deliverable(napi_env env, napi_callback_info info) { + napi_value args[2]; size_t count = 2; + napi_get_cb_info(env, info, &count, args, nullptr, nullptr); + if (count != 2) return throw_error(env, "Expected receiver and deliverable state"); + auto owner = holder(env, args[0]); + if (!owner) return nullptr; + return set_deliverable(env, args[1], (*owner).get()->*member); +} + +/** One presented frame: the callback data Desktop passes back until its settlement. */ +template struct Request { + std::shared_ptr receiver; + uint64_t delivery, connection; + std::string request_id, adapters; + /** The receiver connection that delivered the frame. */ + decltype(Event::source) source; +}; + +template void presentation_error(const decltype(Event::source)& source, std::string text) { + // Desktop can answer on its own thread. Charge the frame's connection, never the receiver's current producer. + if (auto connection = source.lock()) { + auto event = new Event; event->type = "presentation-error"; event->text = std::move(text); + connection->emit(event); + } +} + +template void on_delivered(void* data, const char* error) { + if (!error) return; + auto request = static_cast*>(data); + presentation_error(request->source, + error_text("presentation", request->request_id, "Native frame transfer failed (" + request->adapters + "): " + error)); +} + +template void on_settled(void* data, int invalidated) { + std::unique_ptr> request(static_cast*>(data)); + auto& receiver = *request->receiver; + if (invalidated) { + // Stopping lets the listener release the dispatcher, which would drop a notice emitted afterwards. + auto event = new Event; event->connection = request->connection; + event->type = "presentation-invalidated"; event->text = "Desktop invalidated a presented frame"; receiver.emit(event); + // The channel and the frame's connection stop first, so releasing the delivery returns no credit for a texture + // Desktop may still reference. A concurrent stop of the receiver may still be ending that connection. + receiver.stop(); + if (auto connection = request->source.lock()) connection->stop(); + } + receiver.release(request->delivery); +} + +/** + * Present a `frame` event through the attached sink. + * @returns False when the event is not a frame or no sink is attached, so the caller dispatches it to JavaScript; + * true after the bridge took ownership of the event. + */ +template bool take_frame(Receiver& receiver, Bridge& bridge, Event* event) { + if (event->type != "frame") return false; + Lease lease; + if (!bridge.lease(lease)) return false; + std::unique_ptr frame(event); + { + std::lock_guard lock(frame->ledger->mutex); + if (!frame->ledger->accepting_frames) return true; + frame->ledger->frames.at(frame->delivery).delivered = true; + frame->delivered = true; + } + const auto delivery = frame->delivery, connection = frame->connection; + const auto& packet = frame->packet; + ProducerFrame producer; + const auto invalid = parse_producer_frame(packet.text, producer); + if (!invalid.empty()) { + receiver.release(delivery); + presentation_error(frame->source, error_text("producer", {}, "Invalid native frame metadata: " + invalid)); + return true; + } + const auto& gate = lease.deliverable; + if (!lease.has_deliverable || !gate.visible || gate.connection != connection || producer.generation > gate.max_generation) { + receiver.release(delivery); + return true; + } + const auto adapters = "source=" + frame->adapter + ", presentation=" + + (frame->presentation_adapter.empty() ? std::string("IOSurface") : frame->presentation_adapter); + // Desktop presents at most 8192 pixels per side; a larger frame fails without detaching the sink. + if (packet.width > 8192 || packet.height > 8192) { + receiver.release(delivery); + presentation_error(frame->source, error_text("presentation", producer.request_id, + "Native frame transfer failed (" + adapters + "): frame exceeds 8192 pixels per side")); + return true; + } + const auto& attached = *lease.attached; + // At most 3072 bytes of request identifier, 128 of rx, and 200 of names and numbers: within the 4096-byte limit. + const auto metadata = "{\"requestId\":" + producer.request_id + ",\"generation\":" + std::to_string(producer.generation) + + ",\"revision\":" + std::to_string(producer.revision) + ",\"rx\":" + attached.rx_json + ",\"connectionId\":" + + std::to_string(connection) + ",\"frameId\":" + std::to_string(packet.frame_id) + ",\"width\":" + + std::to_string(packet.width) + ",\"height\":" + std::to_string(packet.height) + "}"; + const dsh_shared_texture_frame_v2 texture{frame->resource, packet.width, packet.height, attached.timeout_ms, 0, + metadata.data(), metadata.size()}; + auto request = new Request{std::static_pointer_cast(lease.owner), delivery, connection, producer.request_id, adapters, + frame->source}; + const dsh_shared_texture_callbacks_v2 callbacks{request, on_delivered, on_settled}; + char reason[512] = {}; + const int status = attached.sink->present(attached.sink->ctx, &texture, &callbacks, reason, sizeof(reason)); + if (status == DSH_SHARED_TEXTURE_PRESENT_OK) return true; + delete request; + receiver.release(delivery); + // A rejected frame leaves the sink usable. Any other failure means it lost its connection: the sink is detached, and + // this frame's share of it dropped, before the error is reported. + if (status != DSH_SHARED_TEXTURE_PRESENT_REJECTED) { + bridge.detach(attached.sink); + lease.attached.reset(); + } + presentation_error(frame->source, error_text("presentation", producer.request_id, + "Native frame transfer failed (" + adapters + "): " + (reason[0] ? reason : "Desktop refused the frame"))); + return true; +} + +} // namespace desktop_bridge +} // namespace dsh_frame_forwarding + +#endif // DSH_FRAME_FORWARDING_DESKTOP_BRIDGE_H diff --git a/packages/experimental/frame-forwarding/native/receiver.cc b/packages/experimental/frame-forwarding/native/receiver.cc new file mode 100644 index 0000000000..a982c24298 --- /dev/null +++ b/packages/experimental/frame-forwarding/native/receiver.cc @@ -0,0 +1,1284 @@ +/** + * Frame-forwarding receiver for a Node host process. One receiver is one logical channel: a stable listener and the + * TX credential producers present. It serves one authenticated producer connection at a time; each connection owns + * its frames, allocations, credits, send queue and GPU relay state. After a connection ends, its frames drain before + * the next producer holding the credential receives ready, and credit never crosses connections. Host-local texture + * handles reach JavaScript, which hands them on and releases each delivery. Node-API only. + */ +#include "transport.h" +#include "desktop-bridge.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(__APPLE__) +#include +#else +#define NOMINMAX +#include +#include +#endif +using namespace dsh_frame_forwarding; +namespace { +enum class PresentationPath { iosurface, shared_texture, gpu_copy, cpu_relay }; +PresentationPath resolve_presentation_path(const std::string& producer, const std::string& display, bool keyed_mutex = false) { +#if defined(_WIN32) + if (producer == display && keyed_mutex) return PresentationPath::shared_texture; + return producer == display ? PresentationPath::gpu_copy : PresentationPath::cpu_relay; +#else + (void)producer; (void)display; (void)keyed_mutex; + return PresentationPath::iosurface; +#endif +} +uint32_t allocation_bytes_factor(PresentationPath path) { + switch (path) { + case PresentationPath::iosurface: return 1; + case PresentationPath::shared_texture: return 1; + case PresentationPath::gpu_copy: return 2; + case PresentationPath::cpu_relay: return 1; + } + throw std::logic_error("Unknown native presentation path"); +} +uint64_t source_byte_budget(PresentationPath path, uint32_t frames, uint64_t bytes) { + return path == PresentationPath::cpu_relay ? bytes / (2 * frames + 2) * frames : bytes / allocation_bytes_factor(path); +} +struct FrameLedger; +struct Connection; +struct Event { + std::string type, text, adapter, presentation_adapter; + Packet packet; uintptr_t resource = 0; uint32_t pid = 0; uint64_t delivery = 0, connection = 0; + std::shared_ptr ledger; + /** The connection a frame came from; a frame that cannot be delivered ends it. */ + std::weak_ptr source; + bool delivered = false, source_keyed_mutex = false; + std::chrono::steady_clock::time_point deadline; + // The dispatched item can outlive its connection and the receiver, including during environment teardown. + std::shared_ptr> pending; + bool reserve(const std::shared_ptr>& count, unsigned limit) { + // dispatch_mutex serializes reservations; only destruction can change the count concurrently, downwards. + if (count->load() >= limit) return false; + ++*count; pending = count; return true; + } + ~Event(); +}; +struct GrantWake { + std::mutex mutex; + std::condition_variable ready; + std::deque packets; + bool grants_pending = false, closed = false; + void notify() { + std::lock_guard lock(mutex); + if (closed) return; + grants_pending = true; ready.notify_one(); + } +}; +struct Reservation { + uint64_t id, bytes; + std::atomic granted{false}; + bool sent = false, cancelled = false; + std::weak_ptr wake; +}; +struct ReservationGroup { + std::vector> members; +}; +struct Budget { + uint64_t limit, used = 0; + std::mutex mutex; + std::deque waiting; + explicit Budget(uint64_t bytes) : limit(bytes) {} + void advance() { + while (!waiting.empty()) { + auto& group = waiting.front(); + uint64_t bytes = 0; + for (auto& member : group.members) if (auto next = member.lock()) if (!next->cancelled) bytes += next->bytes; + if (!bytes) { waiting.pop_front(); continue; } + if (bytes > limit - used) break; + for (auto& member : group.members) if (auto next = member.lock()) { + if (next->cancelled) continue; + used += next->bytes; next->granted = true; + if (auto wake = next->wake.lock()) wake->notify(); + } + waiting.pop_front(); + } + } + std::shared_ptr request(uint64_t id, uint64_t bytes, const std::shared_ptr& wake) { + auto result = std::make_shared(); result->id = id; result->bytes = bytes; result->wake = wake; + request_group({result}); return result; + } + void request_group(const std::vector>& members) { + ReservationGroup group; + for (const auto& member : members) group.members.push_back(member); + std::lock_guard lock(mutex); waiting.push_back(std::move(group)); advance(); + } + void release(const std::shared_ptr& reservation) { + std::lock_guard lock(mutex); + if (reservation->cancelled) return; + reservation->cancelled = true; + if (reservation->granted) used -= reservation->bytes; + advance(); + } +}; +#if defined(_WIN32) +template struct RelayStorage { + std::shared_ptr texture; + std::shared_ptr budget; + std::vector> reservations; + ~RelayStorage() { texture.reset(); for (auto& reservation : reservations) budget->release(reservation); } +}; +using RelayTarget = RelayStorage; +using RelayStaging = RelayStorage; +#endif +/** Wakes a disconnected connection waiting for its drain whenever one of its frames is released. */ +struct DrainSignal { + std::mutex mutex; + std::condition_variable changed; + void notify() { std::lock_guard lock(mutex); changed.notify_all(); } +}; +struct HeldFrame { + uintptr_t resource; uint64_t bytes, allocation, source_id; +#if defined(_WIN32) + std::shared_ptr relay; + std::shared_ptr target; +#endif + bool delivered = false; +}; +struct FrameLedger { + std::mutex mutex; + std::map frames; + std::map> allocations; + std::shared_ptr budget; + std::shared_ptr drain; + uint64_t bytes = 0; + std::atomic connected{false}; + std::atomic accepting_frames{true}; + /** No frame of this connection remains: every delivery was released and every undispatched frame discarded. */ + bool empty() { std::lock_guard lock(mutex); return frames.empty(); } + ~FrameLedger() { + for (auto& frame : frames) if (frame.second.resource) release_resource(frame.second.resource); + frames.clear(); + for (auto& allocation : allocations) budget->release(allocation.second); + } + void retire_idle() { + std::lock_guard lock(mutex); + for (auto allocation = allocations.begin(); allocation != allocations.end();) { + bool used = false; + for (auto& frame : frames) if (frame.second.resource && frame.second.allocation == allocation->first) { used = true; break; } + if (used) { ++allocation; continue; } + budget->release(allocation->second); allocation = allocations.erase(allocation); + } + } + bool release(uint64_t id, bool delivered_only = false, uint64_t* source_id = nullptr) { + uintptr_t resource = 0; + bool released = false; + { + std::lock_guard lock(mutex); + auto found = frames.find(id); + if (found != frames.end() && (!delivered_only || found->second.delivered)) { + resource = found->second.resource; + if (resource) { + bytes -= found->second.bytes; + if (source_id) *source_id = found->second.source_id; + } + frames.erase(found); released = true; + } + } + if (!released) return false; + if (resource) release_resource(resource); + if (!connected) retire_idle(); + if (drain) drain->notify(); + return true; + } + uint64_t release_source(uint64_t delivery) { + uintptr_t resource; uint64_t source; + { + std::lock_guard lock(mutex); + auto& frame = frames.at(delivery); resource = frame.resource; source = frame.source_id; + frame.resource = 0; bytes -= frame.bytes; + } + release_resource(resource); return source; + } +}; +Event::~Event() { + // A frame discarded before its callback has no JavaScript owner to return its credit. + if (ledger && !delivered) ledger->release(delivery); + if (pending) --*pending; +} +struct GpuJob { + std::unique_ptr event; + uint64_t allocation = 0; + std::shared_ptr retirement; +#if defined(_WIN32) + std::shared_ptr texture; + std::shared_ptr staging; + std::shared_ptr target; +#endif + bool ready = false; +}; +struct Receiver; +/** + * One producer connection of a channel and every resource it owns. Its thread reads the producer, then drains: the + * connection stays current until each of its frames is released, so its credit and GPU state never reach a successor. + */ +struct Connection : std::enable_shared_from_this { + Receiver& owner; + const uint64_t id; + const uint32_t pid; + std::unique_ptr channel; + uint32_t max_frames; + uint64_t max_bytes; + PresentationPath presentation_path = PresentationPath::iosurface; + uint32_t readback_timeout = 0, allocation_factor = allocation_bytes_factor(presentation_path); + std::string display_adapter, producer_adapter; +#if defined(_WIN32) + std::shared_ptr relay_device; + std::map> relay_textures; + std::vector> relay_targets; + std::vector> relay_staging; + uint64_t pool_bytes = 0; + HANDLE jobs_event = nullptr, retry_timer = nullptr; + bool wait_failed = false; +#endif + std::atomic stopped{false}; + std::shared_ptr> pending_events = std::make_shared>(0); + std::shared_ptr ledger = std::make_shared(); + std::thread thread, writer, copier; + std::mutex jobs_mutex; + std::condition_variable jobs_ready; + std::deque jobs; + bool input_done = false; + std::shared_ptr output = std::make_shared(); + /** Why the connection ended; empty after the producer's goodbye. */ + std::mutex failure_mutex; + std::string failure; + Connection(Receiver& receiver, uint64_t connection, uint32_t producer, std::unique_ptr link); + ~Connection() { +#if defined(_WIN32) + if (jobs_event) CloseHandle(jobs_event); + if (retry_timer) CloseHandle(retry_timer); +#endif + } + void notify_jobs() { + jobs_ready.notify_all(); +#if defined(_WIN32) + if (jobs_event) SetEvent(jobs_event); +#endif + } + void stop() { + { + std::lock_guard lock(output->mutex); + if (stopped) return; + ledger->accepting_frames = false; + stopped = true; + output->closed = true; + // Any thread may stop a connection; run() releases the channel under the same lock. + if (channel) channel->interrupt(); + } + output->ready.notify_all(); notify_jobs(); + } + bool enqueue(const Packet& packet) { + std::lock_guard lock(output->mutex); + if (stopped || !ledger->connected || output->packets.size() >= 256) return false; + output->packets.push_back(packet); output->ready.notify_one(); return true; + } + void write_loop() { + while (!stopped) { + Packet packet; bool have_packet = false, have_grants = false; + { + std::unique_lock lock(output->mutex); + output->ready.wait(lock, [&] { return stopped || output->grants_pending || !output->packets.empty(); }); + if (stopped) break; + have_grants = output->grants_pending; output->grants_pending = false; + if (!output->packets.empty()) { packet = output->packets.front(); output->packets.pop_front(); have_packet = true; } + } + if (have_grants) grants(); + if (have_packet && !stopped && !channel->send(packet)) { stop(); break; } + } + } + bool emit(Event* event); + /** End this connection with a reason; the first reason is kept. */ + void fail_connection(const std::string& text) { + { std::lock_guard lock(failure_mutex); if (failure.empty()) failure = text; } + stop(); + } + /** GPU completion is unknown: resources and budget stay retained and the drain waits, so report it without timing out. */ + void report_blocked(const std::string& text); + void grants() { + std::lock_guard lock(ledger->mutex); + for (auto& allocation : ledger->allocations) { + if (!allocation.second->granted || allocation.second->sent) continue; + Packet packet; packet.kind = allocated; packet.allocation_id = allocation.first; + if (!channel->send(packet)) { stop(); return; } + allocation.second->sent = true; + } + } +#if defined(_WIN32) + std::shared_ptr reserve_relay(uint64_t id, uint64_t bytes) { + auto source = std::make_shared(); source->id = id; source->bytes = bytes; source->wake = output; + std::vector> group{source}; + if (relay_targets.empty()) { + for (uint32_t index = 0; index < max_frames; ++index) { + auto slot = std::make_shared(); slot->budget = ledger->budget; relay_targets.push_back(std::move(slot)); + } + for (uint32_t index = 0; index < 2; ++index) { + auto slot = std::make_shared(); slot->budget = ledger->budget; relay_staging.push_back(std::move(slot)); + } + } + if (bytes > pool_bytes) { + const auto reserve = [&](auto& slots) { + for (auto& slot : slots) { + auto reservation = std::make_shared(); reservation->id = 0; reservation->bytes = bytes - pool_bytes; + slot->reservations.push_back(reservation); group.push_back(std::move(reservation)); + } + }; + reserve(relay_targets); reserve(relay_staging); pool_bytes = bytes; + } + ledger->budget->request_group(group); return source; + } +#endif + bool post(GpuJob&& job) { + { + std::lock_guard lock(jobs_mutex); + if (stopped || jobs.size() >= 256) return false; + try { jobs.push_back(std::move(job)); } + catch (const std::bad_alloc&) { return false; } + } + notify_jobs(); return true; + } + void prepare_frame(GpuJob& job) { + auto& event = *job.event; + std::string diagnostic, adapter; + if (stopped) return; + if (std::chrono::steady_clock::now() >= event.deadline) throw std::runtime_error("Frame-forwarding frame expired in GPU queue"); + const auto& packet = event.packet; + if (!resource_dimensions(event.resource, packet.width, packet.height, packet.stride, event.deadline, diagnostic, adapter, &event.source_keyed_mutex)) throw std::runtime_error(diagnostic); + if (!producer_adapter.empty() && producer_adapter != adapter) throw std::runtime_error("Frame-forwarding texture adapter differs from producer handshake"); + event.adapter = adapter; +#if defined(_WIN32) + switch (presentation_path) { + case PresentationPath::shared_texture: + if (!event.source_keyed_mutex) throw std::runtime_error("Producer declared keyed mutex support but supplied a legacy texture"); + job.ready = true; + break; + case PresentationPath::gpu_copy: { + if (event.source_keyed_mutex) { + job.ready = true; + break; + } + // The pool owns the slot before submission, including failed fence notifications. + auto& slot = relay_textures[packet.allocation_id]; + const auto submitted = relay_begin(event.resource, packet.width, packet.height, display_adapter, event.deadline, stopped, relay_device, slot, diagnostic); + job.texture = slot; + if (!submitted) throw std::runtime_error(diagnostic); + { + std::lock_guard lock(ledger->mutex); + ledger->frames.at(event.delivery).relay = slot; + } + event.resource = relay_handle(slot); + break; + } + case PresentationPath::cpu_relay: throw std::logic_error("Relay frames require independent source preparation"); + case PresentationPath::iosurface: break; + } + event.presentation_adapter = display_adapter; +#endif + } + void deliver_frame(std::unique_ptr event) { + if (stopped) return; + if (std::chrono::steady_clock::now() >= event->deadline) throw std::runtime_error("Frame-forwarding frame expired before delivery"); + emit(event.release()); + } + void process_frame(std::unique_ptr event) { + GpuJob job; job.event = std::move(event); + try { prepare_frame(job); deliver_frame(std::move(job.event)); } + catch (const std::exception& exception) { fail_connection(exception.what()); } + } +#if defined(_WIN32) + bool gpu_idle(std::string& diagnostic) { + bool idle = true; + for (auto& slot : relay_textures) if (!relay_gpu_idle(slot.second, diagnostic)) idle = false; + return idle; + } + void wait_gpu(const std::deque& active, bool retiring) { + if (wait_failed) { std::this_thread::sleep_for(std::chrono::milliseconds(5)); return; } + std::vector waits; + if (!retiring) waits.push_back(jobs_event); + int64_t wait_ns = retiring ? 5000000 : INT64_MAX; + const auto add_event = [&](uintptr_t raw) { + if (raw && waits.size() < MAXIMUM_WAIT_OBJECTS - 1) waits.push_back(reinterpret_cast(raw)); + else wait_ns = std::min(wait_ns, 1000000); + }; + if (retiring) { + for (auto& slot : relay_textures) add_event(relay_completion_event(slot.second)); + } else for (const auto& job : active) { + if (job.ready) continue; + wait_ns = std::min(wait_ns, std::chrono::duration_cast(job.event->deadline - std::chrono::steady_clock::now()).count()); + add_event(relay_completion_event(job.texture)); + } + if (wait_ns != INT64_MAX) { + LARGE_INTEGER due; due.QuadPart = -std::max(1, wait_ns / 100); + if (!SetWaitableTimer(retry_timer, &due, 0, nullptr, nullptr, FALSE)) { + wait_failed = true; fail_connection("Frame-forwarding GPU retry timer failed; retaining unfinished GPU resources"); return; + } + waits.push_back(retry_timer); + } + if (WaitForMultipleObjects(static_cast(waits.size()), waits.data(), FALSE, INFINITE) == WAIT_FAILED) { + wait_failed = true; fail_connection("Frame-forwarding GPU worker wait failed; retaining unfinished GPU resources"); + } + } + bool advance(GpuJob& job) { + if (job.ready) return true; + std::string diagnostic; + const auto ready = relay_advance(job.texture, stopped, job.event->deadline, diagnostic); + if (ready < 0) throw std::runtime_error(diagnostic); + job.ready = ready == 1; return job.ready; + } + void deliver_ready(std::deque& active) { + while (!stopped && !active.empty() && advance(active.front())) { + deliver_frame(std::move(active.front().event)); active.pop_front(); + } + } + template std::shared_ptr available_slot(const std::vector>& slots) { + for (auto& slot : slots) if (slot.use_count() == 1) return slot; + return {}; + } + bool relay_idle(std::string& diagnostic) { + bool idle = true; + for (auto& slot : relay_staging) if (relay_readback_ready(slot->texture, true, diagnostic) <= 0) idle = false; + for (auto& slot : relay_targets) if (!relay_gpu_idle(slot->texture, diagnostic)) idle = false; + return idle; + } + void wait_relay(const GpuJob* reading, const GpuJob* uploading, const std::deque& pending, bool retiring) { + if (wait_failed) { std::this_thread::sleep_for(std::chrono::milliseconds(5)); return; } + std::vector waits; + int64_t wait_ns = retiring ? 5000000 : INT64_MAX; + const auto add = [&](uintptr_t event) { + if (event && waits.size() < MAXIMUM_WAIT_OBJECTS - 1) waits.push_back(reinterpret_cast(event)); + else wait_ns = std::min(wait_ns, 1000000); + }; + const auto deadline = [&](const GpuJob& job) { + wait_ns = std::min(wait_ns, std::chrono::duration_cast(job.event->deadline - std::chrono::steady_clock::now()).count()); + }; + if (retiring) { + for (auto& slot : relay_staging) add(relay_readback_event(slot->texture)); + for (auto& slot : relay_targets) add(relay_completion_event(slot->texture)); + } else { + { + std::lock_guard lock(jobs_mutex); + ResetEvent(jobs_event); + if (stopped || (!jobs.empty() && (jobs.front().retirement || (!reading && available_slot(relay_staging))))) return; + } + waits.push_back(jobs_event); + if (reading) { add(relay_readback_event(reading->staging->texture)); deadline(*reading); } + if (uploading) { add(relay_completion_event(uploading->texture)); deadline(*uploading); } + if (!pending.empty()) { + deadline(pending.front()); + if (!uploading && available_slot(relay_targets)) wait_ns = std::min(wait_ns, 1000000); + } + } + if (wait_ns != INT64_MAX) { + LARGE_INTEGER due; due.QuadPart = -std::max(1, wait_ns / 100); + if (!SetWaitableTimer(retry_timer, &due, 0, nullptr, nullptr, FALSE)) { + wait_failed = true; fail_connection("Frame-forwarding GPU retry timer failed; retaining unfinished GPU resources"); return; + } + waits.push_back(retry_timer); + } + if (WaitForMultipleObjects(static_cast(waits.size()), waits.data(), FALSE, INFINITE) == WAIT_FAILED) { + wait_failed = true; fail_connection("Frame-forwarding GPU worker wait failed; retaining unfinished GPU resources"); + } + } + void relay_loop() { + std::map> sources; + std::unique_ptr reading, uploading; + std::deque pending; + bool retiring = false, stalled_reported = false; + std::chrono::steady_clock::time_point cleanup_deadline; + for (;;) { + if (stopped) { + if (!retiring) { retiring = true; cleanup_deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(readback_timeout); } + std::string diagnostic; + if (!relay_idle(diagnostic)) { + if (!stalled_reported && std::chrono::steady_clock::now() >= cleanup_deadline) { + stalled_reported = true; report_blocked("Frame-forwarding GPU cleanup is stalled; resources and budget remain retained"); + } + wait_relay(reading.get(), uploading.get(), pending, true); continue; + } + reading.reset(); uploading.reset(); pending.clear(); sources.clear(); + std::deque remaining; + { std::lock_guard lock(jobs_mutex); remaining.swap(jobs); } + for (auto& job : remaining) if (job.retirement) ledger->budget->release(job.retirement); + break; + } + try { + std::string diagnostic; + if (uploading && advance(*uploading)) { + deliver_frame(std::move(uploading->event)); uploading.reset(); + } + if (reading) { + if (std::chrono::steady_clock::now() >= reading->event->deadline) throw std::runtime_error("Frame-forwarding source readback timed out"); + const auto complete = relay_readback_ready(reading->staging->texture, false, diagnostic); + if (complete < 0) throw std::runtime_error(diagnostic); + if (complete > 0) { + Packet packet; packet.kind = dsh_frame_forwarding::release; packet.frame_id = ledger->release_source(reading->event->delivery); + if (!enqueue(packet)) throw std::runtime_error("Cannot return frame-forwarding source credit"); + // A staged replaceable frame supersedes older staged replaceable frames; ordered frames stay queued. + if (reading->event->packet.max_frames & frame_replaceable) { + pending.erase(std::remove_if(pending.begin(), pending.end(), + [](const GpuJob& job) { return (job.event->packet.max_frames & frame_replaceable) != 0; }), pending.end()); + } + pending.push_back(std::move(*reading)); reading.reset(); + } + } + if (!uploading && !pending.empty()) { + auto& job = pending.front(); + if (std::chrono::steady_clock::now() >= job.event->deadline) throw std::runtime_error("Frame-forwarding frame expired before upload"); + auto target = available_slot(relay_targets); + if (target) { + const auto& packet = job.event->packet; + const auto submitted = relay_upload(job.staging->texture, packet.width, packet.height, display_adapter, + relay_device, target->texture, job.event->deadline, stopped, diagnostic); + if (submitted < 0) throw std::runtime_error(diagnostic); + if (submitted > 0) { + job.target = target; job.texture = target->texture; job.staging.reset(); + job.event->resource = relay_handle(target->texture); job.event->presentation_adapter = display_adapter; + { std::lock_guard lock(ledger->mutex); ledger->frames.at(job.event->delivery).target = target; } + uploading = std::make_unique(std::move(job)); pending.pop_front(); + } + } + } + GpuJob job; bool found = false; + std::shared_ptr staging; + if (!reading) staging = available_slot(relay_staging); + { + std::lock_guard lock(jobs_mutex); + if (!jobs.empty() && (jobs.front().retirement || staging)) { + job = std::move(jobs.front()); jobs.pop_front(); found = true; + } + } + if (found) { + if (job.retirement) { + sources.erase(job.allocation); + ledger->budget->release(job.retirement); + } + else { + auto& event = *job.event; const auto& packet = event.packet; + if (std::chrono::steady_clock::now() >= event.deadline) throw std::runtime_error("Frame-forwarding frame expired in source queue"); + job.staging = staging; + if (!relay_readback_begin(event.resource, packet.width, packet.height, packet.stride, staging->texture, sources[packet.allocation_id], diagnostic, + event.adapter, &event.source_keyed_mutex, event.deadline)) throw std::runtime_error(diagnostic); + if (producer_adapter != event.adapter) throw std::runtime_error("Frame-forwarding texture adapter differs from producer handshake"); + reading = std::make_unique(std::move(job)); + } + continue; + } + } catch (const std::exception& exception) { fail_connection(exception.what()); continue; } + wait_relay(reading.get(), uploading.get(), pending, false); + } + { std::lock_guard lock(ledger->mutex); relay_staging.clear(); relay_targets.clear(); } + relay_device.reset(); clear_validation_device(); + } +#endif + void copy_loop() { +#if defined(_WIN32) + { + std::unique_lock lock(jobs_mutex); + jobs_ready.wait(lock, [&] { return input_done || !jobs.empty(); }); + } + if (presentation_path == PresentationPath::cpu_relay) { relay_loop(); return; } +#endif + std::deque active; +#if defined(_WIN32) + bool retiring = false, stalled_reported = false; + std::chrono::steady_clock::time_point cleanup_deadline; +#endif + for (;;) { +#if defined(_WIN32) + if (stopped) { + if (!retiring) { retiring = true; cleanup_deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(readback_timeout); } + std::string diagnostic; + if (!gpu_idle(diagnostic)) { + if (!stalled_reported && std::chrono::steady_clock::now() >= cleanup_deadline) { + stalled_reported = true; + report_blocked("Frame-forwarding GPU cleanup is stalled; resources and budget remain retained"); + } + wait_gpu(active, true); continue; + } + // All submitted copies completed or their device was removed before ownership is released. + active.clear(); + } else { + try { + deliver_ready(active); + for (size_t index = 1; !stopped && index < active.size(); ++index) { + // A completed head is delivered before another slot performs Map or upload. + const auto prior_size = active.size(); deliver_ready(active); + if (active.size() != prior_size) break; + advance(active[index]); + } + deliver_ready(active); + } catch (const std::exception& exception) { fail_connection(exception.what()); continue; } + } +#endif + GpuJob job; bool found = false, finished; + { + std::lock_guard lock(jobs_mutex); + if (!jobs.empty()) { job = std::move(jobs.front()); jobs.pop_front(); found = true; } + finished = input_done && jobs.empty(); +#if defined(_WIN32) + if (!found) ResetEvent(jobs_event); +#endif + } + if (found) { + if (job.retirement) { +#if defined(_WIN32) + relay_textures.erase(job.allocation); +#endif + ledger->budget->release(job.retirement); + } else if (!stopped) { + try { + prepare_frame(job); +#if defined(_WIN32) + if (job.texture) active.push_back(std::move(job)); + else +#endif + deliver_frame(std::move(job.event)); + } catch (const std::exception& exception) { fail_connection(exception.what()); } + } + continue; + } + if (finished && active.empty()) break; +#if defined(_WIN32) + wait_gpu(active, false); +#else + std::unique_lock lock(jobs_mutex); + jobs_ready.wait(lock, [&] { return input_done || !jobs.empty(); }); +#endif + } + clear_validation_device(); +#if defined(_WIN32) + relay_textures.clear(); relay_device.reset(); +#endif + } + uint64_t next_delivery(); + void read_loop() { + while (!stopped) { + Received received; + int result = channel->receive(received, 100); + if (result == 0) continue; + if (result < 0) { + if (channel->foreign_packet()) fail_connection("Frame-forwarding producer sent a packet for another connection"); + else if (channel->invalid_resource()) fail_connection("Frame-forwarding producer sent a handle it does not own"); + else if (!stopped) fail_connection("Frame-forwarding producer connection lost"); + break; + } + const auto received_at = std::chrono::steady_clock::now(); + auto& packet = received.packet; + if (packet.marker != magic || !std::memchr(packet.text, 0, sizeof(packet.text))) { + release_resource(received.resource); fail_connection("Frame-forwarding producer sent an invalid packet"); break; + } + if (packet.version != DSH_FRAME_FORWARDING_PROTOCOL_VERSION) { + release_resource(received.resource); + fail_connection("Frame-forwarding protocol mismatch: producer version " + std::to_string(packet.version) + + ", receiver version " + std::to_string(DSH_FRAME_FORWARDING_PROTOCOL_VERSION)); + break; + } + if (packet.kind == allocate && !received.resource) { + bool valid; + { + std::lock_guard lock(ledger->mutex); + uint64_t reserved = 0; for (auto& allocation : ledger->allocations) reserved += allocation.second->bytes / allocation_factor; + valid = !stopped && packet.allocation_id && !ledger->allocations.count(packet.allocation_id) && ledger->allocations.size() < max_frames && + packet.max_bytes && packet.max_bytes <= source_byte_budget(presentation_path, max_frames, max_bytes) && + reserved <= source_byte_budget(presentation_path, max_frames, max_bytes) - packet.max_bytes; +#if defined(_WIN32) + if (presentation_path == PresentationPath::cpu_relay) { + valid = valid && packet.max_bytes <= max_bytes / (2 * max_frames + 2); + if (valid) ledger->allocations.emplace(packet.allocation_id, reserve_relay(packet.allocation_id, packet.max_bytes)); + } else +#endif + if (valid) ledger->allocations.emplace(packet.allocation_id, ledger->budget->request(packet.allocation_id, packet.max_bytes * allocation_factor, output)); + } + if (!valid) { fail_connection("Invalid frame-forwarding allocation request"); break; } + } else if (packet.kind == deallocate && !received.resource) { + bool used = false; + std::shared_ptr reservation; + { + std::lock_guard lock(ledger->mutex); + for (auto& frame : ledger->frames) if (frame.second.resource && frame.second.allocation == packet.allocation_id) used = true; + auto allocation = ledger->allocations.find(packet.allocation_id); + if (!used && allocation != ledger->allocations.end()) { + reservation = allocation->second; ledger->allocations.erase(allocation); + } + } + if (used) { fail_connection("Producer released an in-use frame-forwarding allocation"); break; } + if (reservation) { + GpuJob job{{}, packet.allocation_id, std::move(reservation)}; + if (!post(std::move(job))) { + // Close retires this reservation after the worker has drained its GPU resources. + { std::lock_guard lock(ledger->mutex); ledger->allocations.emplace(packet.allocation_id, std::move(job.retirement)); } + fail_connection("Frame-forwarding GPU job queue rejected allocation retirement"); break; + } + } + if (presentation_path == PresentationPath::iosurface) clear_validation_device(); + } else if (packet.kind == frame) { + if (!received.resource || !packet.frame_id || packet.frame_id > 9007199254740991ULL || + !packet.width || !packet.height || packet.width > 16384 || packet.height > 16384 || +#if defined(__APPLE__) + // IOSurface aligns row pitch; resource_dimensions checks the actual surface stride. + packet.stride < packet.width * 4) { +#else + packet.stride != packet.width * 4) { +#endif + release_resource(received.resource); fail_connection("Invalid frame-forwarding frame fields"); break; + } +#if defined(__APPLE__) + const auto size = resource_bytes(received.resource); +#else + const auto size = static_cast(packet.stride) * packet.height; +#endif + bool accepted; + const auto delivery = next_delivery(); + { + std::lock_guard lock(ledger->mutex); + auto allocation = ledger->allocations.find(packet.allocation_id); + size_t source_count = 0; + for (auto& frame : ledger->frames) if (frame.second.resource) ++source_count; + accepted = allocation != ledger->allocations.end() && allocation->second->granted && size <= allocation->second->bytes / allocation_factor && source_count < max_frames && size <= max_bytes && ledger->bytes <= max_bytes - size && delivery <= 9007199254740991ULL; + for (auto& frame : ledger->frames) if (frame.second.resource && (frame.second.allocation == packet.allocation_id || frame.second.source_id == packet.frame_id)) accepted = false; + if (accepted) { ledger->frames.emplace(delivery, HeldFrame{received.resource, size, packet.allocation_id, packet.frame_id}); ledger->bytes += size; } + } + if (!accepted) { release_resource(received.resource); fail_connection("Frame-forwarding frame budget or identifier violated"); break; } + auto event = std::make_unique(); event->type = "frame"; event->packet = packet; event->resource = received.resource; event->delivery = delivery; + event->ledger = ledger; event->source = weak_from_this(); event->deadline = received_at + std::chrono::milliseconds(readback_timeout); + if (presentation_path == PresentationPath::iosurface) process_frame(std::move(event)); + else { + GpuJob job; job.event = std::move(event); + if (!post(std::move(job))) { fail_connection("Frame-forwarding GPU job queue rejected frame"); break; } + } + } else if (packet.kind == message && !received.resource) { + auto event = new Event; event->type = "message"; event->text = packet.text; if (!emit(event)) break; + } else if (packet.kind == goodbye && !received.resource) break; + else { release_resource(received.resource); fail_connection("Unexpected frame-forwarding message"); break; } + } + } + void run(); +}; +struct CloseWork { napi_deferred deferred = nullptr; napi_ref keep = nullptr; }; +/** Constant-time comparison of a presented TX secret. */ +bool same_secret(const char (&presented)[65], const std::string& expected) { + if (!std::memchr(presented, 0, sizeof(presented)) || std::strlen(presented) != expected.size()) return false; + unsigned char difference = 0; + for (size_t index = 0; index < expected.size(); ++index) difference |= static_cast(presented[index] ^ expected[index]); + return difference == 0; +} +/** + * One logical channel: Idle, Active(N) and Draining(N) while it accepts producers, then Closed. While connection N is + * active, other candidates are refused as busy; while it drains, one authenticated successor waits and others are + * refused. The successor receives ready once N's frames are released. + */ +struct Receiver { + napi_env env = nullptr; + napi_async_cleanup_hook_handle cleanup = nullptr; + // Signals worker completion to the JavaScript thread; its finalizer frees the owning holder. + napi_threadsafe_function done = nullptr; + std::atomic ended{false}; + bool environment_closing = false, closing_handle = false; + bool main_released = false, worker_released = false, dispatcher_closed = false; + std::mutex dispatch_mutex; + std::unique_ptr close_work; + std::unique_ptr listener; + Endpoint endpoint; + uint32_t max_frames = 0; + uint64_t max_bytes = 0; + uint32_t readback_timeout = 0; + std::string display_adapter; + std::shared_ptr budget; + std::shared_ptr drain = std::make_shared(); + std::atomic deliveries{1}; + std::mutex state_mutex; + uint64_t next_connection = 1; + /** The active or draining connection. */ + std::shared_ptr current; + /** An authenticated successor waiting for the current connection to drain. */ + std::unique_ptr waiting; + /** Ended connections whose threads have not been joined, or whose frames are still held after close. */ + std::vector> retired; + std::atomic stopped{false}; + /** A failed dispatch requests a stop without taking state_mutex. */ + std::atomic stopping{false}; + napi_threadsafe_function callback = nullptr; + std::thread worker; + bool closing = false; + desktop_bridge::Bridge desktop_sink; + std::shared_ptr> pending_rejection = std::make_shared>(0); + // The three connection transitions and the GPU worker's drain-blocked warning each occur at most once per + // connection. The listener fails once; invalidated settlements stop the channel and are bounded by held frames. + // These notices share the FIFO, not the producer quota. Successive short connections can accumulate notices + // during a JS stall: the 256-item bound is per connection, not per receiver. + bool emit(Event* raw, Connection* producer = nullptr) { + std::unique_ptr event(raw); + { + std::unique_lock lock(dispatch_mutex); + if (dispatcher_closed || worker_released) return false; + if (producer && !event->reserve(producer->pending_events, 256)) { + lock.unlock(); // Stopping interrupts I/O; it must not hold the dispatcher lock. + producer->fail_connection("Frame-forwarding producer exceeded the pending event limit (256)"); + return false; + } + if (event->type == "rejected" && !event->reserve(pending_rejection, 1)) return true; + const auto result = napi_call_threadsafe_function(callback, event.get(), napi_tsfn_nonblocking); + if (result == napi_ok) { event.release(); return true; } + // napi_closing relinquishes the native thread's TSFN reference. + if (result != napi_closing) napi_release_threadsafe_function(callback, napi_tsfn_release); + worker_released = true; dispatcher_closed = true; + } + // Callers may hold state_mutex; the listener performs the stop this requests. + stopping = true; drain->notify(); return false; + } + void close_dispatcher() { + std::lock_guard lock(dispatch_mutex); + dispatcher_closed = true; + if (!worker_released) { worker_released = true; napi_release_threadsafe_function(callback, napi_tsfn_release); } + if (!main_released) { main_released = true; napi_release_threadsafe_function(callback, napi_tsfn_abort); } + } + /** Close the channel: the listener stops, a waiting successor is refused and the current connection ends. */ + void stop() { + std::shared_ptr active; + std::unique_ptr successor; + { + std::lock_guard lock(state_mutex); + if (stopped.exchange(true)) return; + active = current; successor = std::move(waiting); + if (listener) listener->interrupt(); + } + if (successor) refuse(*successor, reject_closed); + if (active) active->stop(); + drain->notify(); + } + void fail_channel(const std::string& text) { + auto event = new Event; event->type = "failed"; event->text = text; emit(event); stop(); + } + void refuse(Candidate& candidate, const std::string& reason) { + Packet refusal; refusal.kind = goodbye; std::snprintf(refusal.text, sizeof(refusal.text), "%s", reason.c_str()); + candidate.channel->send(refusal); + candidate.channel.reset(); + auto event = new Event; event->type = "rejected"; event->text = reason; emit(event); + } + /** + * @returns The refusal reason, or empty for a producer holding the credential that supports transferable channels and + * names only handles of its own. + */ + std::string authenticate(const Candidate& candidate) const { + const auto& packet = candidate.hello.packet; + if (packet.marker != magic || packet.kind != hello || !std::memchr(packet.text, 0, sizeof(packet.text))) return reject_credential; + if (packet.version != DSH_FRAME_FORWARDING_PROTOCOL_VERSION) + return std::string(reject_protocol) + ": producer version " + std::to_string(packet.version) + + ", receiver version " + std::to_string(DSH_FRAME_FORWARDING_PROTOCOL_VERSION); + if (!same_secret(packet.token, endpoint.token)) return reject_credential; + if (!(packet.max_frames & hello_transferable)) return reject_capability; + if (!(packet.max_frames & hello_producer_local_handles)) return reject_local_handles; + return {}; + } + /** Promote an authenticated candidate to the current connection; the caller holds state_mutex. */ + void start(std::unique_ptr candidate) { + std::shared_ptr connection; + try { + connection = std::make_shared(*this, next_connection++, candidate->hello.pid, std::move(candidate->channel)); + } catch (const std::exception& exception) { + auto event = new Event; event->type = "rejected"; event->text = exception.what(); emit(event); return; + } + const auto& hello_packet = candidate->hello.packet; + connection->producer_adapter = hello_packet.text; + connection->presentation_path = resolve_presentation_path(connection->producer_adapter, display_adapter, (hello_packet.max_frames & hello_keyed_mutex) != 0); + connection->allocation_factor = allocation_bytes_factor(connection->presentation_path); + connection->channel->bind_connection(connection->id); + Packet response; response.kind = ready; response.max_frames = max_frames; + response.max_bytes = source_byte_budget(connection->presentation_path, max_frames, max_bytes); + response.stride = hello_packet.max_frames & hello_capabilities; + // A candidate that vanished while waiting takes no connection. + if (!connection->channel->send(response)) return; + connection->ledger->connected = true; + current = connection; + auto event = new Event; event->type = "connected"; event->pid = connection->pid; event->connection = connection->id; emit(event); + connection->thread = std::thread([raw = connection.get()] { raw->run(); }); + } + void admit(std::unique_ptr candidate) { + if (const auto reason = authenticate(*candidate); !reason.empty()) { refuse(*candidate, reason); return; } + std::lock_guard lock(state_mutex); + if (stopped) refuse(*candidate, reject_closed); + else if (!current) start(std::move(candidate)); + else if (!current->ledger->connected && !waiting) waiting = std::move(candidate); + else refuse(*candidate, reject_busy); + } + /** A waiting successor that disconnected, or spoke before ready, gives up its place; the caller holds state_mutex. */ + void probe_waiting() { + if (!waiting) return; + Received early; + const auto result = waiting->channel->receive(early, 0); + if (result == 0) return; + if (result == 1) { release_resource(early.resource); refuse(*waiting, reject_credential); } + waiting.reset(); + } + void join_retired() { + std::vector> ended_connections; + { std::lock_guard lock(state_mutex); ended_connections = retired; } + for (auto& connection : ended_connections) if (connection->thread.joinable()) connection->thread.join(); + std::lock_guard lock(state_mutex); + retired.erase(std::remove_if(retired.begin(), retired.end(), [](const std::shared_ptr& connection) { + return !connection->thread.joinable() && connection->ledger->empty(); + }), retired.end()); + } + void listen_loop() { + try { + while (!stopped && !stopping) { + join_retired(); + { std::lock_guard lock(state_mutex); probe_waiting(); } + auto candidate = std::make_unique(); + const auto result = listener->accept(*candidate, 100); + if (result < 0) { if (!stopped && !stopping) fail_channel("Frame-forwarding channel listener failed"); break; } + if (result == 1) admit(std::move(candidate)); + } + } catch (const std::exception& exception) { fail_channel(exception.what()); } + stop(); + std::shared_ptr active; + { + std::lock_guard lock(state_mutex); + // Dropping the listener withdraws the endpoint, so the TX credential no longer connects. + listener.reset(); + active = current; + } + if (active && active->thread.joinable()) active->thread.join(); + join_retired(); + { + std::lock_guard lock(dispatch_mutex); + if (!worker_released) { worker_released = true; napi_release_threadsafe_function(callback, napi_tsfn_release); } + } + ended = true; + // A closing environment finishes through its async cleanup hook instead. + napi_call_threadsafe_function(done, nullptr, napi_tsfn_nonblocking); + } + /** Release one delivery of whichever connection owns it; credit returns only to that connection while it is connected. */ + bool release(uint64_t delivery) { + std::vector> owners; + { + std::lock_guard lock(state_mutex); + if (current) owners.push_back(current); + owners.insert(owners.end(), retired.begin(), retired.end()); + } + for (auto& connection : owners) { + uint64_t source_id = 0; + if (!connection->ledger->release(delivery, true, &source_id)) continue; + connection->notify_jobs(); + if (source_id) { + Packet packet; packet.kind = dsh_frame_forwarding::release; packet.frame_id = source_id; + if (connection->ledger->connected && !connection->enqueue(packet)) connection->stop(); + } + return true; + } + return false; + } + /** Queue control JSON for one connection; false when that connection is not the current, connected one. */ + bool send(uint64_t connection_id, const Packet& packet) { + std::lock_guard lock(state_mutex); + return current && current->id == connection_id && current->ledger->connected && current->enqueue(packet); + } +}; +Connection::Connection(Receiver& receiver, uint64_t connection, uint32_t producer, std::unique_ptr link) + : owner(receiver), id(connection), pid(producer), channel(std::move(link)), max_frames(receiver.max_frames), + max_bytes(receiver.max_bytes), readback_timeout(receiver.readback_timeout), display_adapter(receiver.display_adapter) { + ledger->budget = receiver.budget; ledger->drain = receiver.drain; +#if defined(_WIN32) + jobs_event = CreateEventW(nullptr, TRUE, FALSE, nullptr); + retry_timer = reinterpret_cast(create_gpu_retry_timer()); + if (!jobs_event || !retry_timer) { + if (jobs_event) CloseHandle(jobs_event); + if (retry_timer) CloseHandle(retry_timer); + throw std::runtime_error("Cannot create frame-forwarding GPU worker wake event or retry timer"); + } +#endif +} +bool Connection::emit(Event* event) { + event->connection = id; + if (desktop_bridge::take_frame(owner, owner.desktop_sink, event)) return true; + // Only frames destined for JS use a slot; a Desktop frame can instead produce a presentation error. + const bool producer_event = event->type == "message" || event->type == "presentation-error" || event->type == "frame"; + return owner.emit(event, producer_event ? this : nullptr); +} +void Connection::report_blocked(const std::string& text) { + auto event = new Event; event->type = "drain-blocked"; event->text = text; emit(event); +} +uint64_t Connection::next_delivery() { return owner.deliveries.fetch_add(1); } +void Connection::run() { + try { + writer = std::thread([this] { write_loop(); }); + copier = std::thread([this] { copy_loop(); }); + read_loop(); + } catch (const std::exception& exception) { fail_connection(exception.what()); } + stop(); + { std::lock_guard lock(jobs_mutex); input_done = true; } + notify_jobs(); + if (copier.joinable()) copier.join(); + if (writer.joinable()) writer.join(); + clear_validation_device(); + ledger->connected = false; + // Releasing the channel closes the producer's connection port or pipe instance. + { std::lock_guard lock(output->mutex); channel.reset(); } + ledger->retire_idle(); + { + auto event = new Event; event->type = "disconnected"; + { std::lock_guard lock(failure_mutex); event->text = failure; } + emit(event); + } + { + std::unique_lock lock(owner.drain->mutex); + owner.drain->changed.wait(lock, [&] { return owner.stopped.load() || owner.stopping.load() || ledger->empty(); }); + } + const bool drained = ledger->empty(); + if (drained) { auto event = new Event; event->type = "drained"; emit(event); } + std::lock_guard lock(owner.state_mutex); + if (owner.current.get() == this) { owner.retired.push_back(owner.current); owner.current.reset(); } + if (drained && !owner.stopped && owner.waiting) owner.start(std::move(owner.waiting)); +} +void receiver_done_finalized(napi_env, void* data, void*) { + auto holder = static_cast*>(data); + if ((*holder)->cleanup) napi_remove_async_cleanup_hook((*holder)->cleanup); + delete holder; +} +void settle_close(Receiver* self) { + if (!self->close_work) return; + if (!self->environment_closing) { + napi_handle_scope scope; + if (napi_open_handle_scope(self->env, &scope) == napi_ok) { + napi_value result; napi_get_undefined(self->env, &result); + napi_resolve_deferred(self->env, self->close_work->deferred, result); + napi_close_handle_scope(self->env, scope); + } + } + napi_delete_reference(self->env, self->close_work->keep); + self->close_work.reset(); +} +void receiver_finish_on_main(Receiver* self) { + if (!self->ended || self->closing_handle) return; + self->closing_handle = true; + // The reader joins both I/O helpers and drains submitted GPU work before setting ended. + if (self->worker.joinable()) self->worker.join(); + settle_close(self); + { + std::lock_guard lock(self->dispatch_mutex); + if (!self->main_released) { self->main_released = true; napi_release_threadsafe_function(self->callback, napi_tsfn_release); } + } + napi_release_threadsafe_function(self->done, napi_tsfn_release); +} +void receiver_abandon_setup(Receiver* self, std::shared_ptr* holder) { + self->stop(); self->ended = true; self->environment_closing = true; self->closing_handle = true; + if (self->callback) self->close_dispatcher(); + if (self->done) napi_release_threadsafe_function(self->done, napi_tsfn_abort); + else delete holder; +} +napi_value string(napi_env env, const std::string& value) { napi_value result; napi_create_string_utf8(env, value.data(), value.size(), &result); return result; } +napi_value number(napi_env env, double value) { napi_value result; napi_create_double(env, value, &result); return result; } +void property(napi_env env, napi_value object, const char* name, napi_value value) { napi_set_named_property(env, object, name, value); } +/** End the connection of a frame that cannot be delivered; the frame's ledger entry is released with the event. */ +void undeliverable(const Event& event, const char* text) { + if (auto connection = event.source.lock()) connection->fail_connection(text); +} +void dispatch(napi_env env, napi_value callback, void*, void* data) { + std::unique_ptr event(static_cast(data)); + if (!env || !callback) return; + // A frame of a stopped connection is released undelivered; one that outlived its deadline ends its connection. + if (event->type == "frame" && !event->ledger->accepting_frames) return; + if (event->type == "frame" && std::chrono::steady_clock::now() >= event->deadline) { + undeliverable(*event, "Frame-forwarding frame expired in the JavaScript delivery queue"); return; + } + napi_value object; napi_create_object(env, &object); + property(env, object, "type", string(env, event->type)); + if (event->connection) property(env, object, "connectionId", number(env, static_cast(event->connection))); + if (event->type == "frame") { + property(env, object, "frameId", number(env, static_cast(event->packet.frame_id))); + property(env, object, "deliveryId", number(env, static_cast(event->delivery))); + property(env, object, "width", number(env, event->packet.width)); property(env, object, "height", number(env, event->packet.height)); + property(env, object, "stride", number(env, event->packet.stride)); property(env, object, "metadata", string(env, event->packet.text)); + property(env, object, "transport", string(env, "shared-texture")); + napi_value source_keyed_mutex; + napi_get_boolean(env, event->source_keyed_mutex, &source_keyed_mutex); + property(env, object, "sourceKeyedMutex", source_keyed_mutex); + napi_value buffer; + if (napi_create_buffer_copy(env, sizeof(event->resource), &event->resource, nullptr, &buffer) != napi_ok) { + bool pending = false; + napi_is_exception_pending(env, &pending); + if (pending) { napi_value exception; napi_get_and_clear_last_exception(env, &exception); } + undeliverable(*event, "Cannot allocate frame-forwarding handle buffer"); return; + } + property(env, object, "handle", buffer); + napi_value presentation; + if (event->presentation_adapter.empty()) napi_get_null(env, &presentation); + else presentation = string(env, event->presentation_adapter); + property(env, object, "presentationAdapterId", presentation); + property(env, object, "adapterId", string(env, event->adapter)); + std::lock_guard lock(event->ledger->mutex); + if (!event->ledger->accepting_frames) return; + if (std::chrono::steady_clock::now() >= event->deadline) { + undeliverable(*event, "Frame-forwarding frame expired during JavaScript delivery"); return; + } + event->ledger->frames.at(event->delivery).delivered = true; + event->delivered = true; + } else if (event->type == "connected") property(env, object, "pid", number(env, event->pid)); + else if (!event->text.empty() || event->type == "message") property(env, object, "text", string(env, event->text)); + napi_value global, result; napi_get_global(env, &global); napi_call_function(env, global, callback, 1, &object, &result); +} +napi_value fail(napi_env env, const char* text) { napi_throw_error(env, nullptr, text); return nullptr; } +Receiver* receiver(napi_env env, napi_value value) { + void* result = nullptr; + if (napi_get_value_external(env, value, &result) != napi_ok || !result) { napi_throw_type_error(env, nullptr, "Invalid native receiver"); return nullptr; } + return static_cast*>(result)->get(); +} +bool uint_value(napi_env env, napi_value value, uint64_t& output) { + double number = 0; + if (napi_get_value_double(env, value, &number) != napi_ok || !std::isfinite(number) || number < 1 || number > 9007199254740991.0 || std::floor(number) != number) return false; + output = static_cast(number); return true; +} +std::string token() { + unsigned char random[32]; +#if defined(__APPLE__) + arc4random_buf(random, sizeof(random)); +#else + if (BCryptGenRandom(nullptr, random, sizeof(random), BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0) throw std::runtime_error("Cannot generate render authentication secret"); +#endif + const char* hex = "0123456789abcdef"; std::string result; + for (auto byte : random) { result += hex[byte >> 4]; result += hex[byte & 15]; } return result; +} +napi_value create(napi_env env, napi_callback_info info) { + napi_value args[6]; size_t count = 6; napi_get_cb_info(env, info, &count, args, nullptr, nullptr); + uint64_t max_frames, max_bytes, timeout; napi_valuetype callback_type; char adapter[32]{}; size_t adapter_size; + if (count != 6 || !uint_value(env, args[0], max_frames) || max_frames > 1024 || !uint_value(env, args[1], max_bytes) || + !uint_value(env, args[5], timeout) || timeout > UINT32_MAX || + napi_get_value_string_utf8(env, args[4], adapter, sizeof(adapter), &adapter_size) != napi_ok || adapter_size >= sizeof(adapter) - 1 || + napi_typeof(env, args[2], &callback_type) != napi_ok || callback_type != napi_function) return fail(env, "Invalid native receiver options"); +#if defined(_WIN32) + if (!adapter_size) return fail(env, "Frame forwarding unavailable: Windows requires a display adapter"); +#endif + std::shared_ptr value; + // Owned by the completion function once it exists; freed by its finalizer. + std::shared_ptr* done_holder = nullptr; + try { + value = std::make_shared(); value->env = env; + value->max_frames = static_cast(max_frames); value->max_bytes = max_bytes; + value->display_adapter = adapter; value->readback_timeout = static_cast(timeout); + void* budget_pointer = nullptr; + if (napi_get_value_external(env, args[3], &budget_pointer) != napi_ok || !budget_pointer) return fail(env, "Invalid frame-forwarding budget"); + value->budget = *static_cast*>(budget_pointer); + if (max_bytes > value->budget->limit) return fail(env, "Channel budget exceeds shared frame-forwarding budget"); + value->endpoint.pid = process_id(); value->endpoint.token = token(); +#if defined(__APPLE__) + value->endpoint.name = "ai.deepseek.render." + token(); +#else + value->endpoint.name = "\\\\.\\pipe\\dsh-render-" + token(); +#endif + value->listener = listen(value->endpoint, value->readback_timeout); + // The TX credential: producers present its secret; it names the receiver process, never a producer. + auto tx = std::string("1|") + std::to_string(value->endpoint.pid) + "|" + value->endpoint.token + "|" + value->endpoint.name; + auto name = string(env, "DSH frame-forwarding receiver"); + if (napi_create_threadsafe_function(env, args[2], nullptr, name, 0, 2, nullptr, nullptr, nullptr, dispatch, &value->callback) != napi_ok) + return fail(env, "Cannot create frame-forwarding event dispatcher"); + done_holder = new std::shared_ptr(value); + auto done_name = string(env, "DSH frame-forwarding receiver completion"); + if (napi_create_threadsafe_function(env, nullptr, nullptr, done_name, 0, 1, done_holder, receiver_done_finalized, value.get(), + [](napi_env, napi_value, void* context, void*) { receiver_finish_on_main(static_cast(context)); }, &value->done) != napi_ok) { + receiver_abandon_setup(value.get(), done_holder); return fail(env, "Cannot create native receiver completion handle"); + } + if (napi_add_async_cleanup_hook(env, [](napi_async_cleanup_hook_handle, void* data) { + auto self = static_cast(data); self->environment_closing = true; + self->stop(); self->close_dispatcher(); + // Node closes the completion function during teardown, so wait for the worker here instead of relying on its signal. + if (self->worker.joinable()) self->worker.join(); + receiver_finish_on_main(self); + }, value.get(), &value->cleanup) != napi_ok) { + receiver_abandon_setup(value.get(), done_holder); return fail(env, "Cannot register native receiver cleanup"); + } + napi_value external, result; + auto raw = value.get(); + auto holder = std::make_unique>(value); + if (napi_create_external(env, holder.get(), [](napi_env, void* data, void*) { + std::unique_ptr> holder(static_cast*>(data)); + (*holder)->stop(); (*holder)->close_dispatcher(); + }, nullptr, &external) != napi_ok) { + receiver_abandon_setup(raw, done_holder); return fail(env, "Cannot create native receiver owner"); + } + holder.release(); + napi_create_object(env, &result); property(env, result, "native", external); property(env, result, "tx", string(env, tx)); + raw->worker = std::thread([raw] { raw->listen_loop(); }); + return result; + } catch (const std::exception& exception) { + if (value && value->callback) receiver_abandon_setup(value.get(), done_holder); + return fail(env, exception.what()); + } +} +napi_value send(napi_env env, napi_callback_info info) { + napi_value args[3]; size_t count = 3; napi_get_cb_info(env, info, &count, args, nullptr, nullptr); + if (count != 3) return fail(env, "Expected receiver, connection ID and control JSON"); + auto value = receiver(env, args[0]); uint64_t connection; if (!value) return nullptr; + if (!uint_value(env, args[1], connection)) return fail(env, "Invalid frame-forwarding connection ID"); + Packet packet; packet.kind = message; size_t length; + if (napi_get_value_string_utf8(env, args[2], nullptr, 0, &length) != napi_ok || length >= sizeof(packet.text)) return fail(env, "Control message exceeds frame-forwarding limit"); + napi_get_value_string_utf8(env, args[2], packet.text, sizeof(packet.text), &length); + if (!value->send(connection, packet)) return fail(env, "Frame-forwarding connection is not active"); + napi_value result; napi_get_undefined(env, &result); return result; +} +napi_value release(napi_env env, napi_callback_info info) { + napi_value args[2]; size_t count = 2; napi_get_cb_info(env, info, &count, args, nullptr, nullptr); + if (count != 2) return fail(env, "Expected receiver and delivery ID"); + auto value = receiver(env, args[0]); uint64_t id; if (!value) return nullptr; + if (!uint_value(env, args[1], id)) return fail(env, "Invalid delivery ID"); + napi_value result; napi_get_boolean(env, value->release(id), &result); return result; +} +napi_value close(napi_env env, napi_callback_info info) { + napi_value args[1]; size_t count = 1; napi_get_cb_info(env, info, &count, args, nullptr, nullptr); + if (count != 1) return fail(env, "Expected receiver"); + auto value = receiver(env, args[0]); if (!value) return nullptr; + if (value->closing) return fail(env, "Native receiver close already requested"); + auto work = std::make_unique(); napi_value promise; + if (napi_create_promise(env, &work->deferred, &promise) != napi_ok || + napi_create_reference(env, args[0], 1, &work->keep) != napi_ok) + return fail(env, "Cannot retain native receiver close operation"); + value->close_work = std::move(work); value->closing = true; value->stop(); + if (value->closing_handle) settle_close(value); + else receiver_finish_on_main(value); + return promise; +} +napi_value create_budget(napi_env env, napi_callback_info info) { + napi_value args[1]; size_t count = 1; napi_get_cb_info(env, info, &count, args, nullptr, nullptr); + uint64_t bytes; + if (count != 1 || !uint_value(env, args[0], bytes)) return fail(env, "Invalid shared frame-forwarding byte budget"); + auto budget = new std::shared_ptr(std::make_shared(bytes)); + napi_value result; + napi_create_external(env, budget, [](napi_env, void* data, void*) { delete static_cast*>(data); }, nullptr, &result); + return result; +} +/** Inspect an Electron-owned handle without selecting another GPU. */ +napi_value get_adapter(napi_env env, napi_callback_info info) { + napi_value args[1]; size_t count = 1; napi_get_cb_info(env, info, &count, args, nullptr, nullptr); + void* data = nullptr; size_t size = 0; + if (count != 1 || napi_get_buffer_info(env, args[0], &data, &size) != napi_ok || size != sizeof(uintptr_t)) + return fail(env, "Expected an eight-byte native texture handle"); + uintptr_t handle; std::memcpy(&handle, data, size); + return string(env, resource_adapter(handle)); +} +napi_value initialize(napi_env env, napi_value exports) { + const napi_property_descriptor methods[] = { + {"createBudget", nullptr, create_budget, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"getAdapter", nullptr, get_adapter, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"create", nullptr, create, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"send", nullptr, send, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"release", nullptr, release, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"attachSink", nullptr, desktop_bridge::attach_sink, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"setDeliverable", nullptr, desktop_bridge::set_deliverable, nullptr, nullptr, nullptr, napi_default, nullptr}, + {"close", nullptr, close, nullptr, nullptr, nullptr, napi_default, nullptr} + }; + napi_define_properties(env, exports, sizeof(methods) / sizeof(methods[0]), methods); + return exports; +} +} +NAPI_MODULE(NODE_GYP_MODULE_NAME, initialize) diff --git a/packages/experimental/frame-forwarding/native/relay-transport.inc b/packages/experimental/frame-forwarding/native/relay-transport.inc new file mode 100644 index 0000000000..e77469506e --- /dev/null +++ b/packages/experimental/frame-forwarding/native/relay-transport.inc @@ -0,0 +1,321 @@ +// Windows receiver-worker resources; submitted GPU copies outlive cancellation until quiescent. +class SourceAccess { + ComPtr mutex; + bool locked = false; + public: + ~SourceAccess() { if (locked) mutex->ReleaseSync(0); } + bool acquire(ID3D11Texture2D* texture, std::chrono::steady_clock::time_point deadline, + std::string& diagnostic) { + D3D11_TEXTURE2D_DESC description{}; texture->GetDesc(&description); + if (!(description.MiscFlags & D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX)) return true; + auto result = texture->QueryInterface(IID_PPV_ARGS(&mutex)); + if (FAILED(result)) return gpu_failure(diagnostic, "Cannot access producer keyed mutex", result); + const auto remaining = std::chrono::duration_cast(deadline - std::chrono::steady_clock::now()).count(); + if (remaining <= 0) return gpu_failure(diagnostic, "Producer keyed mutex acquisition timed out", WAIT_TIMEOUT); + result = mutex->AcquireSync(0, static_cast(std::min(remaining, MAXDWORD - 1))); + if (result != S_OK) return gpu_failure(diagnostic, "Producer keyed mutex acquisition failed or timed out", result); + locked = true; return true; + } + bool release(std::string& diagnostic) { + if (!locked) return true; + const auto result = mutex->ReleaseSync(0); locked = false; + return result == S_OK || gpu_failure(diagnostic, "Cannot release producer keyed mutex", result); + } +}; +struct RelayDevice { + ComPtr device; + ComPtr context; +}; +struct RelaySource { + ComPtr device; + ComPtr texture; + HANDLE handle = nullptr; + uint32_t width = 0, height = 0; + ~RelaySource() { if (handle) CloseHandle(handle); } +}; +struct RelayReadback { + ComPtr device; + ComPtr context; + ComPtr source, staging; + std::unique_ptr completion; + std::shared_ptr image; + uint32_t width = 0, height = 0; +}; +enum class RelayStage { waiting_target, pending_target, ready }; +struct RelayTexture { + std::shared_ptr display; + ComPtr source, target; + ComPtr target_mutex; + bool target_locked = false; + std::unique_ptr target_completion; + RelayStage stage = RelayStage::ready; + bool retry_pending = false; + HANDLE handle = nullptr; + uint32_t width = 0, height = 0; + ~RelayTexture() { + if (target_locked) { + target_mutex->ReleaseSync(0); + } + if (handle) CloseHandle(handle); + } +}; +bool relay_prepare_sync(ID3D11Device1* device, ID3D11DeviceContext* context, + std::unique_ptr& completion, std::string& diagnostic) { + if (completion) return true; + auto sync = std::make_unique(); + D3D11_QUERY_DESC description{D3D11_QUERY_EVENT, 0}; + auto result = device->CreateQuery(&description, &sync->query); + if (FAILED(result)) return gpu_failure(diagnostic, "Cannot create relay completion query", result); + ComPtr modern; + if (SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&modern))) && SUCCEEDED(context->QueryInterface(IID_PPV_ARGS(&sync->signaling)))) { + result = modern->CreateFence(0, D3D11_FENCE_FLAG_NONE, IID_PPV_ARGS(&sync->fence)); + if (FAILED(result) && result != E_NOTIMPL && result != DXGI_ERROR_UNSUPPORTED) + return gpu_failure(diagnostic, "Cannot create relay completion fence", result); + } + if (sync->fence) { + sync->event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (!sync->event) return gpu_failure(diagnostic, "Cannot create relay completion event", HRESULT_FROM_WIN32(GetLastError())); + } + completion = std::move(sync); return true; +} +bool relay_active(const std::atomic& stopped, + std::chrono::steady_clock::time_point deadline, std::string& diagnostic) { + if (stopped) { diagnostic = "Native texture relay interrupted"; return false; } + if (std::chrono::steady_clock::now() >= deadline) { diagnostic = "Native texture relay timed out"; return false; } + return true; +} +uintptr_t relay_handle(const std::shared_ptr& texture) { return reinterpret_cast(texture->handle); } +int relay_advance(const std::shared_ptr& slot, const std::atomic& stopped, + std::chrono::steady_clock::time_point deadline, std::string& diagnostic) { + if (!relay_active(stopped, deadline, diagnostic)) return -1; + if (slot->stage == RelayStage::waiting_target) { + if (!slot->target_locked) { + const auto acquired = slot->target_mutex->AcquireSync(0, 0); + if (acquired == WAIT_TIMEOUT) { slot->retry_pending = true; return 0; } + if (acquired != S_OK) { gpu_failure(diagnostic, "Cannot acquire relay target keyed mutex", acquired); return -1; } + slot->target_locked = true; + } + if (!relay_active(stopped, deadline, diagnostic)) return -1; + SourceAccess source_access; + if (!source_access.acquire(slot->source.Get(), deadline, diagnostic)) return -1; + slot->stage = RelayStage::pending_target; slot->retry_pending = false; + slot->display->context->CopyResource(slot->target.Get(), slot->source.Get()); + if (!finish_gpu_submission(slot->display->context.Get(), *slot->target_completion, diagnostic)) return -1; + if (!source_access.release(diagnostic)) return -1; + } + if (slot->stage == RelayStage::pending_target) { + const auto ready = poll_gpu_submission(slot->display->device.Get(), slot->display->context.Get(), *slot->target_completion, false, diagnostic); + if (ready != 1) return ready == 0 ? 0 : -1; + const auto released = slot->target_mutex->ReleaseSync(0); + if (released != S_OK) { gpu_failure(diagnostic, "Cannot release relay target keyed mutex", released); return -1; } + slot->target_locked = false; + slot->stage = RelayStage::ready; + } + return 1; +} +uintptr_t relay_completion_event(const std::shared_ptr& slot) { + if (!slot) return 0; + if (slot->target_completion && slot->target_completion->pending && slot->target_completion->event_armed) return reinterpret_cast(slot->target_completion->event); + return 0; +} +bool relay_gpu_idle(const std::shared_ptr& slot, std::string& diagnostic) { + if (!slot) return true; + return !slot->target_completion || poll_gpu_submission(slot->display->device.Get(), slot->display->context.Get(), *slot->target_completion, true, diagnostic) > 0; +} + +bool relay_target(uint32_t width, uint32_t height, + const std::string& adapter, std::chrono::steady_clock::time_point deadline, const std::atomic& stopped, + std::shared_ptr& display, std::shared_ptr& slot, std::string& diagnostic) { + if (!relay_active(stopped, deadline, diagnostic)) return false; + if (stopped || adapter.empty()) { diagnostic = "Native texture relay requires both active adapters"; return false; } + if (!display) { + auto owner = std::make_shared(); + ComPtr factory; ComPtr selected; + HRESULT result = CreateDXGIFactory1(IID_PPV_ARGS(&factory)); + if (FAILED(result)) { gpu_failure(diagnostic, "Cannot enumerate relay display adapters", result); return false; } + for (UINT index = 0;; ++index) { + ComPtr candidate; + result = factory->EnumAdapters1(index, &candidate); + if (result == DXGI_ERROR_NOT_FOUND) break; + if (FAILED(result)) { gpu_failure(diagnostic, "Cannot enumerate relay display adapters", result); return false; } + DXGI_ADAPTER_DESC1 description{}; + if (SUCCEEDED(candidate->GetDesc1(&description)) && adapter_id(description.AdapterLuid) == adapter) { selected = candidate; break; } + } + if (!selected) { diagnostic = "Relay display adapter is unavailable"; return false; } + ComPtr device; + result = D3D11CreateDevice(selected.Get(), D3D_DRIVER_TYPE_UNKNOWN, nullptr, D3D11_CREATE_DEVICE_BGRA_SUPPORT, + nullptr, 0, D3D11_SDK_VERSION, &device, nullptr, &owner->context); + if (FAILED(result) || FAILED(result = device.As(&owner->device))) { gpu_failure(diagnostic, "Cannot create relay display device", result); return false; } + display = std::move(owner); + } + if (!slot) { + slot = std::make_shared(); + slot->display = display; + slot->width = width; slot->height = height; + D3D11_TEXTURE2D_DESC description{}; + description.Width = width; description.Height = height; description.MipLevels = 1; description.ArraySize = 1; + description.Format = DXGI_FORMAT_B8G8R8A8_UNORM; description.SampleDesc.Count = 1; + HRESULT result; + description.Usage = D3D11_USAGE_DEFAULT; description.CPUAccessFlags = 0; + description.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET; + description.MiscFlags = D3D11_RESOURCE_MISC_SHARED_NTHANDLE | D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX; + result = display->device->CreateTexture2D(&description, nullptr, &slot->target); + if (FAILED(result)) { gpu_failure(diagnostic, "Cannot allocate relay display texture", result); return false; } + result = slot->target.As(&slot->target_mutex); + if (FAILED(result)) { gpu_failure(diagnostic, "Cannot access relay target keyed mutex", result); return false; } + ComPtr shared; + result = slot->target.As(&shared); + if (SUCCEEDED(result)) result = shared->CreateSharedHandle(nullptr, DXGI_SHARED_RESOURCE_READ | DXGI_SHARED_RESOURCE_WRITE, nullptr, &slot->handle); + if (FAILED(result)) { gpu_failure(diagnostic, "Cannot share relay display texture", result); return false; } + if (!relay_prepare_sync(display->device.Get(), display->context.Get(), slot->target_completion, diagnostic)) return false; + } + if (slot->width != width || slot->height != height) { diagnostic = "Relay allocation changed without retirement"; return false; } + return true; +} + +bool relay_begin(uintptr_t resource, uint32_t width, uint32_t height, + const std::string& adapter, std::chrono::steady_clock::time_point deadline, const std::atomic& stopped, + std::shared_ptr& display, std::shared_ptr& slot, std::string& diagnostic) { + if (!relay_target(width, height, adapter, deadline, stopped, display, slot, diagnostic)) return false; + ComPtr source; + auto result = slot->display->device->OpenSharedResource1(reinterpret_cast(resource), IID_PPV_ARGS(&source)); + if (FAILED(result)) { gpu_failure(diagnostic, "Cannot open current relay source", result); return false; } + slot->source = source; + if (!relay_active(stopped, deadline, diagnostic)) return false; + slot->retry_pending = false; + slot->stage = RelayStage::waiting_target; return true; +} + +bool relay_readback_begin(uintptr_t resource, uint32_t width, uint32_t height, uint32_t stride, + std::shared_ptr& slot, std::shared_ptr& imported, + std::string& diagnostic, std::string& adapter, bool* keyed_mutex, + std::chrono::steady_clock::time_point deadline) { + ComPtr source; + using CompareHandles = BOOL (WINAPI*)(HANDLE, HANDLE); + static const auto compare_handles = reinterpret_cast( + GetProcAddress(GetModuleHandleW(L"KernelBase.dll"), "CompareObjectHandles")); + const bool reused = imported && imported->width == width && imported->height == height && + stride == width * 4 && compare_handles && compare_handles(imported->handle, reinterpret_cast(resource)); + if (reused) { + source = imported->texture; adapter = device_adapter(imported->device.Get()); + D3D11_TEXTURE2D_DESC description{}; source->GetDesc(&description); + if (keyed_mutex) *keyed_mutex = (description.MiscFlags & D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX) != 0; + } + if (!reused && !open_frame(resource, width, height, stride, diagnostic, adapter, keyed_mutex, source)) { + if (source) { std::string ignored; source_ready(source.Get(), deadline, ignored); } + return false; + } + if (!slot || slot->width != width || slot->height != height) { + auto next = std::make_shared(); + next->device = reused ? imported->device : validation_device; next->width = width; next->height = height; + next->device->GetImmediateContext(&next->context); + D3D11_TEXTURE2D_DESC description{}; + description.Width = width; description.Height = height; description.MipLevels = 1; description.ArraySize = 1; + description.Format = DXGI_FORMAT_B8G8R8A8_UNORM; description.SampleDesc.Count = 1; + description.Usage = D3D11_USAGE_STAGING; description.CPUAccessFlags = D3D11_CPU_ACCESS_READ; + auto result = next->device->CreateTexture2D(&description, nullptr, &next->staging); + if (FAILED(result)) return gpu_failure(diagnostic, "Cannot allocate relay source staging", result); + if (!relay_prepare_sync(next->device.Get(), next->context.Get(), next->completion, diagnostic)) return false; + slot = std::move(next); + } + if (!reused && compare_handles) { + auto next = std::make_shared(); + if (!DuplicateHandle(GetCurrentProcess(), reinterpret_cast(resource), GetCurrentProcess(), + &next->handle, 0, FALSE, DUPLICATE_SAME_ACCESS)) + return gpu_failure(diagnostic, "Cannot retain relay source handle", HRESULT_FROM_WIN32(GetLastError())); + next->texture = source; next->device = slot->device; + next->width = width; next->height = height; imported = std::move(next); + } + slot->source = std::move(source); + SourceAccess source_access; + if (!source_access.acquire(slot->source.Get(), deadline, diagnostic)) return false; + slot->context->CopyResource(slot->staging.Get(), slot->source.Get()); + if (!finish_gpu_submission(slot->context.Get(), *slot->completion, diagnostic)) return false; + return source_access.release(diagnostic); +} +int relay_readback_ready(const std::shared_ptr& slot, bool retiring, std::string& diagnostic) { + if (!slot) return 1; + const auto result = poll_gpu_submission(slot->device.Get(), slot->context.Get(), *slot->completion, retiring, diagnostic); + if (result > 0) { + slot->source.Reset(); + if (slot->image) { + const auto released = slot->image->target_mutex->ReleaseSync(0); + if (released != S_OK && !retiring) { gpu_failure(diagnostic, "Cannot release native readback image", released); return -1; } + slot->image->target_locked = false; slot->image.reset(); + } + } + return result == 2 && !retiring ? -1 : result; +} +uintptr_t relay_readback_event(const std::shared_ptr& slot) { + return slot && slot->completion->pending && slot->completion->event_armed ? reinterpret_cast(slot->completion->event) : 0; +} +int relay_upload(const std::shared_ptr& source, uint32_t width, uint32_t height, + const std::string& adapter, std::shared_ptr& display, std::shared_ptr& target, + std::chrono::steady_clock::time_point deadline, const std::atomic& stopped, std::string& diagnostic) { + if (target && (target->width != width || target->height != height)) { + if (!target->target_locked) { + const auto acquired = target->target_mutex->AcquireSync(0, 0); + if (acquired == WAIT_TIMEOUT) return 0; + if (acquired != S_OK) { gpu_failure(diagnostic, "Cannot retire relay target keyed mutex", acquired); return -1; } + target->target_locked = true; + } + target.reset(); + } + if (!relay_target(width, height, adapter, deadline, stopped, display, target, diagnostic)) return -1; + if (!target->target_locked) { + const auto acquired = target->target_mutex->AcquireSync(0, 0); + if (acquired == WAIT_TIMEOUT) { target->retry_pending = true; return 0; } + if (acquired != S_OK) { gpu_failure(diagnostic, "Cannot acquire relay target keyed mutex", acquired); return -1; } + target->target_locked = true; + } + D3D11_MAPPED_SUBRESOURCE mapped{}; + const auto result = source->context->Map(source->staging.Get(), 0, D3D11_MAP_READ, D3D11_MAP_FLAG_DO_NOT_WAIT, &mapped); + if (result == DXGI_ERROR_WAS_STILL_DRAWING) { target->retry_pending = true; return 0; } + if (FAILED(result)) { gpu_failure(diagnostic, "Cannot map staged relay", result); return -1; } + struct Unmap { RelayReadback* source; ~Unmap() { source->context->Unmap(source->staging.Get(), 0); } } unmap{source.get()}; + if (!relay_active(stopped, deadline, diagnostic)) return -1; + target->stage = RelayStage::pending_target; target->retry_pending = false; + target->display->context->UpdateSubresource(target->target.Get(), 0, nullptr, mapped.pData, mapped.RowPitch, 0); + return finish_gpu_submission(target->display->context.Get(), *target->target_completion, diagnostic) ? 1 : -1; +} + +void* relay_output_device(const std::shared_ptr& texture) { return texture->display->device.Get(); } +void relay_forget_source(const std::shared_ptr& texture) { texture->source.Reset(); } +bool relay_copy_output(const std::shared_ptr& texture, void* destination, std::string& diagnostic) { + const auto result = texture->target_mutex->AcquireSync(0, 0); + if (result != S_OK) return gpu_failure(diagnostic, "Cannot acquire native presentation image", result); + texture->target_locked = true; texture->stage = RelayStage::pending_target; + texture->display->context->CopyResource(static_cast(destination), texture->target.Get()); + return finish_gpu_submission(texture->display->context.Get(), *texture->target_completion, diagnostic); +} +bool relay_readback_image(const std::shared_ptr& texture, std::shared_ptr& staging, std::string& diagnostic) { + auto next = std::make_shared(); + next->device = texture->display->device; next->context = texture->display->context; + next->width = texture->width; next->height = texture->height; + D3D11_TEXTURE2D_DESC description{}; texture->target->GetDesc(&description); + description.Usage = D3D11_USAGE_STAGING; description.CPUAccessFlags = D3D11_CPU_ACCESS_READ; + description.BindFlags = 0; description.MiscFlags = 0; + auto result = next->device->CreateTexture2D(&description, nullptr, &next->staging); + if (FAILED(result)) return gpu_failure(diagnostic, "Cannot allocate native presentation readback", result); + if (!relay_prepare_sync(next->device.Get(), next->context.Get(), next->completion, diagnostic)) return false; + staging = next; + result = texture->target_mutex->AcquireSync(0, 0); + if (result != S_OK) return gpu_failure(diagnostic, "Cannot acquire native readback image", result); + texture->target_locked = true; next->image = texture; + next->context->CopyResource(next->staging.Get(), texture->target.Get()); + return finish_gpu_submission(next->context.Get(), *next->completion, diagnostic); +} +int relay_with_pixels(const std::shared_ptr& staging, + const std::function& consume, std::string& diagnostic) { + D3D11_MAPPED_SUBRESOURCE mapped{}; + const auto result = staging->context->Map(staging->staging.Get(), 0, D3D11_MAP_READ, D3D11_MAP_FLAG_DO_NOT_WAIT, &mapped); + if (result == DXGI_ERROR_WAS_STILL_DRAWING) return 0; + if (FAILED(result)) { gpu_failure(diagnostic, "Cannot map native presentation readback", result); return -1; } + struct Unmap { RelayReadback* source; ~Unmap() { source->context->Unmap(source->staging.Get(), 0); } } unmap{staging.get()}; + return consume(static_cast(mapped.pData), mapped.RowPitch) ? 1 : -1; +} +/** Acquire and release key 0 of a keyed-mutex texture within the deadline; a texture without a keyed mutex is ready. */ +bool source_ready(ID3D11Texture2D* texture, std::chrono::steady_clock::time_point deadline, std::string& diagnostic) { + SourceAccess access; + return access.acquire(texture, deadline, diagnostic) && access.release(diagnostic); +} diff --git a/packages/experimental/frame-forwarding/native/transport.cc b/packages/experimental/frame-forwarding/native/transport.cc new file mode 100644 index 0000000000..565b46d8d1 --- /dev/null +++ b/packages/experimental/frame-forwarding/native/transport.cc @@ -0,0 +1,764 @@ +#include "transport.h" +#include +#include +#include +#include +#include +#include +#include +#if defined(__APPLE__) +#include +#include +#include +#include +#include +#include +#include +#else +#define NOMINMAX +#include +#include +#include +#include +#include +#endif +namespace dsh_frame_forwarding { +Endpoint parse_endpoint(const std::string& value) { + auto a = value.find('|'), b = value.find('|', a + 1), c = value.find('|', b + 1); + if (a == std::string::npos || b == std::string::npos || c == std::string::npos || value.substr(0, a) != "1") + throw std::runtime_error("Unsupported frame-forwarding endpoint"); + const auto pid_text = value.substr(a + 1, b - a - 1); + const char* invalid = "Invalid frame-forwarding endpoint"; + if (pid_text.empty() || !std::all_of(pid_text.begin(), pid_text.end(), [](char c) { return c >= '0' && c <= '9'; })) + throw std::runtime_error(invalid); + size_t used = 0; + unsigned long long pid; + try { pid = std::stoull(pid_text, &used); } + catch (const std::exception&) { throw std::runtime_error(invalid); } + if (used != pid_text.size() || !pid || pid > UINT32_MAX) throw std::runtime_error(invalid); + Endpoint result{static_cast(pid), value.substr(b + 1, c - b - 1), value.substr(c + 1)}; + if (result.token.size() != 64 || result.name.empty() || result.name.size() > 200) throw std::runtime_error(invalid); + return result; +} +uint64_t parse_connection(const char (&token)[65]) { + if (!std::memchr(token, 0, sizeof(token)) || !token[0] || token[0] == '0' || std::strlen(token) > 16) return 0; + uint64_t value = 0; + for (const char* digit = token; *digit; ++digit) { + if (*digit < '0' || *digit > '9') return 0; + value = value * 10 + static_cast(*digit - '0'); + } + return value <= 9007199254740991ULL ? value : 0; +} +void Channel::bind_connection(uint64_t id) { + connection_ = id; + std::snprintf(connection_text_, sizeof(connection_text_), "%llu", static_cast(id)); +} +int Channel::receive(Received& out, uint32_t timeout_ms) { + const auto result = receive_packet(out, timeout_ms); + if (result != 1 || !connection_ || std::strncmp(out.packet.token, connection_text_, sizeof(out.packet.token)) == 0) return result; + release_resource(out.resource); out.resource = 0; foreign_ = true; interrupt(); return -1; +} +bool Channel::send(const Packet& packet, uintptr_t resource) { + if (!connection_) return send_packet(packet, resource); + Packet stamped = packet; + std::memcpy(stamped.token, connection_text_, sizeof(stamped.token)); + return send_packet(stamped, resource); +} +namespace { +/** Bytes of the marker, version, and kind that every protocol version's packet begins with. */ +constexpr size_t wire_prefix = 3 * sizeof(uint32_t); +/** Write the header of `packet` and return its text size; the text follows the header on the wire. */ +uint32_t encode_header(const Packet& packet, WireHeader& wire) { + wire = WireHeader{}; + wire.marker = packet.marker; wire.version = packet.version; wire.kind = packet.kind; + wire.width = packet.width; wire.height = packet.height; wire.stride = packet.stride; wire.max_frames = packet.max_frames; + wire.frame_id = packet.frame_id; wire.allocation_id = packet.allocation_id; wire.max_bytes = packet.max_bytes; wire.resource = packet.resource; + std::memcpy(wire.token, packet.token, sizeof(wire.token)); + // An unterminated text is sent whole, so the receiver sees it unterminated and refuses the packet. + const auto* nul = static_cast(std::memchr(packet.text, 0, sizeof(packet.text))); + wire.text_size = nul ? static_cast(nul - packet.text) : DSH_FRAME_FORWARDING_TEXT_CAPACITY; + return wire.text_size; +} +/** + * Decode one received message of `size` bytes, a header followed by its text, which Mach pads to 4 bytes. + * @returns False for a malformed message. A hello of another protocol version yields only its marker, version, and + * kind, so the receiver refuses it by version whatever its layout. + */ +bool decode_packet(const char* data, size_t size, bool padded, Packet& out) { + if (size < wire_prefix) return false; + uint32_t prefix[3]; + std::memcpy(prefix, data, sizeof(prefix)); + if (prefix[0] == magic && prefix[1] != DSH_FRAME_FORWARDING_PROTOCOL_VERSION && prefix[2] == hello) { + out.marker = prefix[0]; out.version = prefix[1]; out.kind = prefix[2]; + out.width = out.height = out.stride = out.max_frames = 0; + out.frame_id = out.allocation_id = out.max_bytes = out.resource = 0; + std::memset(out.token, 0, sizeof(out.token)); + out.text[0] = '\0'; + return true; + } + if (size < sizeof(WireHeader)) return false; + WireHeader wire; + std::memcpy(&wire, data, sizeof(wire)); + if (wire.text_size > DSH_FRAME_FORWARDING_TEXT_CAPACITY) return false; + const size_t text = padded ? (wire.text_size + 3u) & ~3u : wire.text_size; + if (size != sizeof(WireHeader) + text) return false; + out.marker = wire.marker; out.version = wire.version; out.kind = wire.kind; + out.width = wire.width; out.height = wire.height; out.stride = wire.stride; out.max_frames = wire.max_frames; + out.frame_id = wire.frame_id; out.allocation_id = wire.allocation_id; out.max_bytes = wire.max_bytes; out.resource = wire.resource; + std::memcpy(out.token, wire.token, sizeof(out.token)); + std::memcpy(out.text, data + sizeof(WireHeader), wire.text_size); + if (wire.text_size < DSH_FRAME_FORWARDING_TEXT_CAPACITY) out.text[wire.text_size] = '\0'; + return true; +} +} // namespace +#if defined(__APPLE__) +struct MachMessage { + mach_msg_header_t header; + mach_msg_body_t body; + mach_msg_port_descriptor_t port; + WireHeader wire; + /** WireHeader::text_size bytes, then zeros up to a multiple of 4; the kernel writes the trailer after them. */ + char text[DSH_FRAME_FORWARDING_TEXT_CAPACITY]; + mach_msg_audit_trailer_t trailer; +}; +static_assert(offsetof(MachMessage, text) % 4 == 0, "Mach message sizes are multiples of 4 bytes"); +static_assert(offsetof(MachMessage, trailer) >= sizeof(mach_no_senders_notification_t) - sizeof(mach_msg_format_0_trailer_t), + "no-senders notification fits before the audit trailer"); +/** + * Receive one protocol message and decode it into `packet`: 1 data, 0 timeout, -1 failure, -2 a message of another + * layout, one larger than `msg`, or one carrying a port right the protocol never sends (destroyed), -3 a kernel + * no-senders notice on a watched connection port. + * + * Only a send right may arrive in the single port descriptor. Our descriptors carry the connection port and the + * IOSurface as send rights, and no message sends a receive or send-once right, or a reply right in its header; such a + * right would outlive its message, because the success path only deallocates a send right. + * + * When `watch_no_senders` is true, only a genuine kernel `MACH_NOTIFY_NO_SENDERS` notification (non-complex, no reply + * port, delivered via the notification's send-once right, and carrying the kernel audit token pid 0) returns -3. Every + * other unexpected or rejected message is destroyed with `mach_msg_destroy` before returning -2, so a forged + * notification carrying a reply right or descriptor cannot leave any right in the process. + */ +int receive_mach(mach_port_t port, bool watch_no_senders, uint32_t timeout, MachMessage& msg, uint32_t& pid, Packet& packet) { + std::memset(&msg.header, 0, sizeof(msg.header)); + const auto result = mach_msg(&msg.header, MACH_RCV_MSG | MACH_RCV_TIMEOUT | + MACH_RCV_TRAILER_TYPE(MACH_MSG_TRAILER_FORMAT_0) | MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_AUDIT), + 0, sizeof(msg), port, timeout, MACH_PORT_NULL); + if (result == MACH_RCV_TIMED_OUT) return 0; + // Without MACH_RCV_LARGE the kernel has already destroyed the oversized message; the port keeps working. + if (result == MACH_RCV_TOO_LARGE) return -2; + if (result != KERN_SUCCESS) return -1; + const size_t size = msg.header.msgh_size; + const size_t trailer_offset = (size + 3u) & ~size_t{3}; + if (size < sizeof(mach_msg_header_t) || trailer_offset > offsetof(MachMessage, trailer)) { + mach_msg_destroy(&msg.header); return -2; + } + const auto* trailer = reinterpret_cast( + reinterpret_cast(&msg) + trailer_offset); + if (trailer->msgh_trailer_size < sizeof(mach_msg_audit_trailer_t)) { + mach_msg_destroy(&msg.header); return -2; + } + const pid_t sender_pid = audit_token_to_pid(trailer->msgh_audit); + // Neither protocol packets nor kernel notifications may carry a reply right in the header. + if (msg.header.msgh_remote_port != MACH_PORT_NULL || MACH_MSGH_BITS_REMOTE(msg.header.msgh_bits) != 0) { + mach_msg_destroy(&msg.header); return -2; + } + if (watch_no_senders && msg.header.msgh_id == MACH_NOTIFY_NO_SENDERS) { + // Only the kernel holds the notification send-once right and audit pid 0; a peer with a send right cannot forge it. + const bool valid_notice = !(msg.header.msgh_bits & MACH_MSGH_BITS_COMPLEX) + && MACH_MSGH_BITS_LOCAL(msg.header.msgh_bits) == MACH_MSG_TYPE_PORT_SEND_ONCE + && sender_pid == 0 + && size >= sizeof(mach_no_senders_notification_t) - sizeof(mach_msg_format_0_trailer_t); + mach_msg_destroy(&msg.header); + return valid_notice ? -3 : -2; + } + if (sender_pid <= 0 || size < offsetof(MachMessage, wire) || size > offsetof(MachMessage, trailer) + || !(msg.header.msgh_bits & MACH_MSGH_BITS_COMPLEX) + || msg.body.msgh_descriptor_count != 1 || msg.port.type != MACH_MSG_PORT_DESCRIPTOR + || (msg.port.name && msg.port.disposition != MACH_MSG_TYPE_PORT_SEND) + || !decode_packet(reinterpret_cast(&msg.wire), size - offsetof(MachMessage, wire), true, packet)) { + mach_msg_destroy(&msg.header); return -2; + } + pid = static_cast(sender_pid); + return 1; +} +mach_port_t allocate_receive_port() { + mach_port_t port = MACH_PORT_NULL; + if (mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &port) != KERN_SUCCESS) + throw std::runtime_error("Cannot allocate frame-forwarding Mach port"); + return port; +} +mach_port_t allocate_listener_port() { + mach_port_t port = allocate_receive_port(); + if (mach_port_insert_right(mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND) != KERN_SUCCESS) { + mach_port_destroy(mach_task_self(), port); + throw std::runtime_error("Cannot allocate frame-forwarding Mach port"); + } + return port; +} +void destroy_port(mach_port_t port) { + if (!port) return; + mach_port_destroy(mach_task_self(), port); +} +/** Drop any send rights a timed-out `MAKE_SEND` hand-off left on our own receive port. */ +void drop_local_sends(mach_port_t port) { + mach_port_urefs_t refs = 0; + if (mach_port_get_refs(mach_task_self(), port, MACH_PORT_RIGHT_SEND, &refs) == KERN_SUCCESS && refs > 0) + mach_port_mod_refs(mach_task_self(), port, MACH_PORT_RIGHT_SEND, -static_cast(refs)); +} +/** + * One producer connection. The producer's hello carries the single send right to its receive port; the receiver + * answers on it with ready, carrying the single send right to its connection port. Each side watches its own receive + * port with `MACH_NOTIFY_NO_SENDERS`, so peer exit or disconnect wakes the reader without creating dead-name + * notification references on `remote_`; a receive that times out also reads `remote_`'s type, which covers a candidate + * that armed no notice and a peer that vanished before its notice was requested. + */ +class MachChannel final : public Channel { + mach_port_t local_ = MACH_PORT_NULL, remote_ = MACH_PORT_NULL; + bool server_; + /** The process this connection's packets must come from: the receiver for a producer, the candidate for a receiver. */ + uint32_t source_pid_; + std::atomic stopped_{false}; + std::atomic peer_{0}; + /** True once `local_`'s single send right reached the peer and `MACH_NOTIFY_NO_SENDERS` is armed on `local_`. */ + std::atomic senders_watched_{false}; + std::mutex writes_; + /** Request `MACH_NOTIFY_NO_SENDERS` once the peer owns the only send right to `local_` (`mscount` >= 1). */ + void watch_no_senders() { + mach_port_t previous = MACH_PORT_NULL; + const auto result = mach_port_request_notification( + mach_task_self(), local_, MACH_NOTIFY_NO_SENDERS, 1, local_, MACH_MSG_TYPE_MAKE_SEND_ONCE, &previous); + if (previous) mach_port_deallocate(mach_task_self(), previous); + if (result == KERN_SUCCESS) senders_watched_.store(true, std::memory_order_release); + else stopped_ = true; + } + public: + /** Producer side: discover the listener; ready later replaces it with the connection port. */ + explicit MachChannel(const Endpoint& endpoint) : server_(false), source_pid_(endpoint.pid) { + local_ = allocate_receive_port(); + if (bootstrap_look_up(bootstrap_port, const_cast(endpoint.name.c_str()), &remote_) != KERN_SUCCESS) { + destroy_port(local_); throw std::runtime_error("Cannot discover frame-forwarding Mach endpoint"); + } + } + /** Receiver side: adopt the candidate's reply port and open a connection port for it. */ + MachChannel(mach_port_t reply, uint32_t pid) : remote_(reply), server_(true), source_pid_(pid) { + try { local_ = allocate_receive_port(); } catch (...) { mach_port_deallocate(mach_task_self(), reply); throw; } + peer_ = pid; + } + ~MachChannel() override { + if (remote_) mach_port_deallocate(mach_task_self(), remote_); + destroy_port(local_); + } + uint32_t peer_pid() const override { return peer_; } + void interrupt() override { stopped_ = true; } + protected: + bool send_packet(const Packet& packet, uintptr_t resource) override { + std::lock_guard lock(writes_); + if (stopped_ || !remote_) return false; + MachMessage msg; + std::memset(&msg.header, 0, sizeof(msg.header)); + std::memset(&msg.body, 0, sizeof(msg.body)); + std::memset(&msg.port, 0, sizeof(msg.port)); + msg.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0) | MACH_MSGH_BITS_COMPLEX; + msg.header.msgh_remote_port = remote_; + msg.header.msgh_id = magic; + msg.body.msgh_descriptor_count = 1; + msg.port.type = MACH_MSG_PORT_DESCRIPTOR; + msg.port.disposition = MACH_MSG_TYPE_COPY_SEND; + mach_port_t surface_port = MACH_PORT_NULL; + const bool hands_local = (!server_ && packet.kind == hello) || (server_ && packet.kind == ready); + if (hands_local) { + msg.port.name = local_; + msg.port.disposition = MACH_MSG_TYPE_MAKE_SEND; + } else if (resource) { + msg.port.name = surface_port = IOSurfaceCreateMachPort(reinterpret_cast(resource)); + } + const auto text_size = encode_header(packet, msg.wire); + const uint32_t aligned_text = (text_size + 3u) & ~3u; + std::memcpy(msg.text, packet.text, text_size); + std::memset(msg.text + text_size, 0, aligned_text - text_size); + msg.header.msgh_size = static_cast(offsetof(MachMessage, text) + aligned_text); + const auto result = mach_msg(&msg.header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, msg.header.msgh_size, 0, MACH_PORT_NULL, 1000, MACH_PORT_NULL); + if ((result & ~MACH_MSG_MASK) == MACH_SEND_TIMED_OUT) { + // A timed-out send returns the copied or created rights in `msg`, separately owned from our own ports. + mach_msg_destroy(&msg.header); + if (hands_local) drop_local_sends(local_); + } + if (surface_port) mach_port_deallocate(mach_task_self(), surface_port); + if (result == KERN_SUCCESS && hands_local) watch_no_senders(); + return result == KERN_SUCCESS && !stopped_; + } + int receive_packet(Received& out, uint32_t timeout) override { + if (stopped_) return -1; + MachMessage msg; uint32_t pid = 0; + const auto result = receive_mach(local_, senders_watched_.load(std::memory_order_acquire), timeout, msg, pid, out.packet); + if (result == 0) { + // A peer that vanished between the hand-off and the no-senders request leaves a send count of zero, which the + // kernel answers with no notice ever; a timed-out receive is where its dead port then shows up. Queued packets + // are read first, so a goodbye that arrived before the peer exited still ends the connection without a reason. + mach_port_type_t type = 0; + if (remote_ && (mach_port_type(mach_task_self(), remote_, &type) != KERN_SUCCESS || (type & MACH_PORT_TYPE_DEAD_NAME))) { + stopped_ = true; + return -1; + } + return stopped_ ? -1 : 0; + } + if (result == -2) return stopped_ ? -1 : 0; + if (result < 0) return -1; + out.pid = pid; + if (pid != source_pid_) { mach_msg_destroy(&msg.header); return -1; } + if (!server_ && out.packet.kind == ready && msg.port.name) { + // The connection port replaces the listener for every later packet. + mach_port_deallocate(mach_task_self(), remote_); remote_ = msg.port.name; msg.port.name = MACH_PORT_NULL; + } else if (out.packet.kind == frame && msg.port.name) { + out.resource = reinterpret_cast(IOSurfaceLookupFromMachPort(msg.port.name)); + } + if (msg.port.name) mach_port_deallocate(mach_task_self(), msg.port.name); + return 1; + } +}; +class MachListener final : public Listener { + mach_port_t port_ = MACH_PORT_NULL; + std::string name_; + std::atomic stopped_{false}; + public: + explicit MachListener(const Endpoint& endpoint) : name_(endpoint.name) { + port_ = allocate_listener_port(); + if (bootstrap_register(bootstrap_port, const_cast(name_.c_str()), port_) != KERN_SUCCESS) { + destroy_port(port_); throw std::runtime_error("Cannot register frame-forwarding Mach endpoint"); + } + } + ~MachListener() override { + const auto ignored = bootstrap_register(bootstrap_port, const_cast(name_.c_str()), MACH_PORT_NULL); (void)ignored; + destroy_port(port_); + } + void interrupt() override { stopped_ = true; } + int accept(Candidate& candidate, uint32_t timeout) override { + if (stopped_) return -1; + MachMessage msg; uint32_t pid = 0; + candidate.hello = Received{}; + const auto result = receive_mach(port_, false, timeout, msg, pid, candidate.hello.packet); + if (result == 0 || result <= -2) return stopped_ ? -1 : 0; + if (result < 0) return -1; + if (candidate.hello.packet.kind != hello || !msg.port.name || msg.port.disposition != MACH_MSG_TYPE_PORT_SEND) { mach_msg_destroy(&msg.header); return 0; } + const auto reply = msg.port.name; + candidate.hello.pid = pid; + candidate.channel = std::make_unique(reply, pid); + return 1; + } +}; +std::unique_ptr listen(Endpoint& endpoint, uint32_t) { return std::make_unique(endpoint); } +std::unique_ptr connect_channel(const Endpoint& endpoint, const std::function& cancelled) { + if (cancelled && cancelled()) throw std::runtime_error("Frame-forwarding connection cancelled or timed out"); + return std::make_unique(endpoint); +} +uint32_t process_id() { return getpid(); } +void clear_validation_device() {} +std::string resource_adapter(uintptr_t) { return "IOSurface"; } +std::string device_adapter(void*) { return "IOSurface"; } +void release_resource(uintptr_t resource) { if (resource) CFRelease(reinterpret_cast(resource)); } +uint64_t resource_bytes(uintptr_t resource) { return IOSurfaceGetAllocSize(reinterpret_cast(resource)); } +bool resource_dimensions(uintptr_t resource, uint32_t width, uint32_t height, uint32_t stride, + std::chrono::steady_clock::time_point, std::string& diagnostic, std::string& adapter, bool* keyed_mutex) { + if (keyed_mutex) *keyed_mutex = false; + diagnostic = "IOSurface format or dimensions differ"; adapter = "IOSurface"; + auto surface = reinterpret_cast(resource); + return surface && IOSurfaceGetWidth(surface) == width && IOSurfaceGetHeight(surface) == height && + IOSurfaceGetBytesPerRow(surface) == stride && IOSurfaceGetBytesPerElement(surface) == 4 && IOSurfaceGetPixelFormat(surface) == 0x42475241; +} +#else +using Microsoft::WRL::ComPtr; +HANDLE create_deadline_timer() { + // The SDK also compiles with Windows 8 target headers, which omit this flag. + constexpr DWORD high_resolution_timer = 0x00000002; + auto timer = CreateWaitableTimerExW(nullptr, nullptr, high_resolution_timer, TIMER_MODIFY_STATE | SYNCHRONIZE); + if (!timer && GetLastError() == ERROR_INVALID_PARAMETER) + timer = CreateWaitableTimerExW(nullptr, nullptr, 0, TIMER_MODIFY_STATE | SYNCHRONIZE); + return timer; +} +struct ReadbackSync { + ComPtr fence; + ComPtr signaling; + ComPtr query; + HANDLE event = nullptr; + uint64_t value = 0; + bool pending = false, fence_submitted = false, event_armed = false; + ~ReadbackSync() { if (event) CloseHandle(event); } +}; +bool gpu_failure(std::string& diagnostic, const char* operation, HRESULT result) { + std::ostringstream text; text << operation << " HRESULT=0x" << std::hex << static_cast(result); + diagnostic = text.str(); return false; +} +bool finish_gpu_submission(ID3D11DeviceContext* context, ReadbackSync& sync, std::string& diagnostic) { + // The query remains valid when fence submission or notification fails after a copy. + context->End(sync.query.Get()); + sync.pending = true; sync.fence_submitted = false; sync.event_armed = false; + HRESULT result = S_OK; + const char* operation = "Cannot signal GPU completion"; + if (sync.fence) { + result = sync.signaling->Signal(sync.fence.Get(), ++sync.value); + if (SUCCEEDED(result)) { + sync.fence_submitted = true; + operation = "Cannot arm GPU completion event"; + result = sync.fence->SetEventOnCompletion(sync.value, sync.event); + sync.event_armed = SUCCEEDED(result); + } + } + context->Flush(); + return SUCCEEDED(result) || gpu_failure(diagnostic, operation, result); +} +// Pending=0, completed=1, device removed=2; other errors retain ownership. +int poll_gpu_submission(ID3D11Device* device, ID3D11DeviceContext* context, + ReadbackSync& sync, bool retiring, std::string& diagnostic) { + if (!sync.pending) return 1; + if (retiring && FAILED(device->GetDeviceRemovedReason())) { sync.pending = false; return 2; } + if (sync.fence_submitted) { + const auto completed = sync.fence->GetCompletedValue(); + if (completed == UINT64_MAX) { sync.pending = false; gpu_failure(diagnostic, "GPU device removed", DXGI_ERROR_DEVICE_REMOVED); return 2; } + if (completed >= sync.value) { sync.pending = false; return 1; } + return 0; + } + const auto result = context->GetData(sync.query.Get(), nullptr, 0, D3D11_ASYNC_GETDATA_DONOTFLUSH); + if (result == S_OK) { sync.pending = false; return 1; } + if (FAILED(device->GetDeviceRemovedReason())) { sync.pending = false; gpu_failure(diagnostic, "GPU device removed", DXGI_ERROR_DEVICE_REMOVED); return 2; } + if (result == S_FALSE) return 0; + gpu_failure(diagnostic, "Cannot query GPU completion", result); return -1; +} +uintptr_t create_gpu_retry_timer() { return reinterpret_cast(create_deadline_timer()); } +thread_local ID3D11Device1* validation_device = nullptr; +void clear_validation_device() { + if (validation_device) { validation_device->Release(); validation_device = nullptr; } +} +std::string adapter_id(LUID luid) { + std::ostringstream id; id << std::hex << static_cast(luid.HighPart) << ':' << luid.LowPart; + return id.str(); +} +std::string device_adapter(void* device) { + if (!device) return {}; + ComPtr dxgi; ComPtr adapter; DXGI_ADAPTER_DESC desc{}; + if (FAILED(static_cast(device)->QueryInterface(IID_PPV_ARGS(&dxgi))) || + FAILED(dxgi->GetAdapter(&adapter)) || FAILED(adapter->GetDesc(&desc))) return {}; + return adapter_id(desc.AdapterLuid); +} +std::string resource_adapter(uintptr_t resource) { + ComPtr factory; LUID luid{}; + if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) || + FAILED(factory->GetSharedResourceAdapterLuid(reinterpret_cast(resource), &luid))) return {}; + return adapter_id(luid); +} +/** Overlapped I/O wait shared by pipe channels and the listener: 1 completed, 0 timed out, -1 stopped or failed. */ +int wait_pipe(HANDLE pipe, OVERLAPPED& operation, HANDLE stop, HANDLE deadline, DWORD timeout, DWORD& count) { + HANDLE events[] = {operation.hEvent, stop, deadline}; + const bool timed = timeout != 0 && timeout != INFINITE; + if (timed) { + LARGE_INTEGER due; due.QuadPart = -static_cast(timeout) * 10000; + if (!SetWaitableTimer(deadline, &due, 0, nullptr, nullptr, FALSE)) { + CancelIoEx(pipe, &operation); + return GetOverlappedResult(pipe, &operation, &count, TRUE) ? 1 : -1; + } + } + // A millisecond pipe poll must not round up to the system's coarse clock tick. + auto result = WaitForMultipleObjects(timed ? 3 : 2, events, FALSE, timed ? INFINITE : timeout); + if (timed) { + CancelWaitableTimer(deadline); + if (result == WAIT_OBJECT_0 + 2) result = WAIT_TIMEOUT; + } + if (result != WAIT_OBJECT_0) { + CancelIoEx(pipe, &operation); + const bool completed = GetOverlappedResult(pipe, &operation, &count, TRUE) != FALSE; + // Completion can race the deadline; preserve a successfully received message. + if (result == WAIT_TIMEOUT && completed) return 1; + return result == WAIT_TIMEOUT ? 0 : -1; + } + return GetOverlappedResult(pipe, &operation, &count, FALSE) ? 1 : -1; +} +/** One pipe message: a header, then its text; only sizeof(WireHeader) + header.text_size bytes are sent. */ +struct WireMessage { + WireHeader header; + char text[DSH_FRAME_FORWARDING_TEXT_CAPACITY]; +}; +static_assert(sizeof(WireMessage) == sizeof(WireHeader) + DSH_FRAME_FORWARDING_TEXT_CAPACITY, "WireMessage layout"); +/** + * One connected pipe instance: the producer's client handle, or one instance the listener accepted. A producer sends + * its own handle values, and the receiving instance duplicates each one from the producer's process. + */ +class PipeChannel final : public Channel { + HANDLE pipe_ = INVALID_HANDLE_VALUE, stop_ = nullptr, deadline_ = nullptr; + /** Manual-reset completion events of the single reader and of writes, which writes_ serializes. */ + HANDLE read_event_ = nullptr, write_event_ = nullptr; + /** The producer process a receiving instance duplicates handles from; null on the producer side. */ + HANDLE producer_ = nullptr; + std::atomic peer_{0}; + std::mutex writes_; + /** Message buffers of the single reader and of writes; each stays untouched until its overlapped I/O completes. */ + WireMessage read_buffer_, write_buffer_; + void open_events() { + stop_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); + deadline_ = create_deadline_timer(); + read_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); + write_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (!stop_ || !deadline_ || !read_event_ || !write_event_) throw std::runtime_error("Cannot create frame-forwarding I/O wait events"); + } + void close_handles() { + if (pipe_ != INVALID_HANDLE_VALUE) CloseHandle(pipe_); + if (stop_) CloseHandle(stop_); + if (deadline_) CloseHandle(deadline_); + if (read_event_) CloseHandle(read_event_); + if (write_event_) CloseHandle(write_event_); + if (producer_) CloseHandle(producer_); + pipe_ = INVALID_HANDLE_VALUE; stop_ = nullptr; deadline_ = nullptr; read_event_ = nullptr; write_event_ = nullptr; producer_ = nullptr; + } + public: + /** Producer side: connect to the receiver's pipe and check its process identity. */ + PipeChannel(const Endpoint& endpoint, const std::function& cancelled) { + try { + open_events(); + using Clock = std::chrono::steady_clock; + const auto deadline = Clock::now() + std::chrono::seconds(10); + Clock::time_point missing_until{}; + for (;;) { + if (cancelled && cancelled()) throw std::runtime_error("Frame-forwarding connection cancelled or timed out"); + const auto left = std::chrono::ceil(deadline - Clock::now()).count(); + if (!cancelled && left <= 0) break; + if (WaitNamedPipeA(endpoint.name.c_str(), cancelled ? 100 : static_cast(left))) { + pipe_ = CreateFileA(endpoint.name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr); + if (pipe_ != INVALID_HANDLE_VALUE) break; + } + const auto error = GetLastError(); + // A successful wait does not reserve an instance: another client can open it first. + if (error == ERROR_PIPE_BUSY || error == ERROR_SEM_TIMEOUT) { missing_until = {}; continue; } + if (error != ERROR_FILE_NOT_FOUND) break; + // Between closing the last candidate and opening its replacement, both calls can see no pipe. + // Allow half a second of continuous absence, not a full connection timeout for a withdrawn endpoint. + const auto now = Clock::now(); + if (missing_until == Clock::time_point{}) missing_until = now + std::chrono::milliseconds(500); + if (now >= missing_until) break; + Sleep(10); // WaitNamedPipe returns immediately when the name is absent. + } + if (pipe_ == INVALID_HANDLE_VALUE) { + if (cancelled && cancelled()) throw std::runtime_error("Frame-forwarding connection cancelled or timed out"); + throw std::runtime_error("Frame-forwarding receiver unavailable"); + } + DWORD mode = PIPE_READMODE_MESSAGE; SetNamedPipeHandleState(pipe_, &mode, nullptr, nullptr); + ULONG pid = 0; + if (!GetNamedPipeServerProcessId(pipe_, &pid) || pid != endpoint.pid) throw std::runtime_error("Frame-forwarding receiver identity mismatch"); + peer_ = pid; + } catch (...) { close_handles(); throw; } + } + /** Receiver side: adopt an instance whose client connected, with that client's process for handle duplication. */ + PipeChannel(HANDLE pipe, uint32_t pid, HANDLE producer) : pipe_(pipe), producer_(producer) { + try { open_events(); } catch (...) { close_handles(); throw; } + peer_ = pid; + } + ~PipeChannel() override { interrupt(); close_handles(); } + uint32_t peer_pid() const override { return peer_; } + void interrupt() override { if (stop_) SetEvent(stop_); if (pipe_ != INVALID_HANDLE_VALUE) CancelIoEx(pipe_, nullptr); } + protected: + /** The sender keeps a sent handle open until the receiver releases its frame, so the receiver can duplicate it. */ + bool send_packet(const Packet& packet, uintptr_t resource) override { + std::lock_guard lock(writes_); + if (WaitForSingleObject(stop_, 0) == WAIT_OBJECT_0) return false; + const auto text_size = encode_header(packet, write_buffer_.header); + write_buffer_.header.resource = static_cast(resource); + std::memcpy(write_buffer_.text, packet.text, text_size); + const DWORD size = static_cast(sizeof(WireHeader) + text_size); + ResetEvent(write_event_); + OVERLAPPED operation{}; operation.hEvent = write_event_; DWORD count = 0; + bool ok = WriteFile(pipe_, &write_buffer_, size, &count, &operation) != FALSE; + if (!ok && GetLastError() == ERROR_IO_PENDING) ok = wait_pipe(pipe_, operation, stop_, deadline_, INFINITE, count) == 1; + return ok && count == size; + } + int receive_packet(Received& out, uint32_t timeout) override { + if (WaitForSingleObject(stop_, 0) == WAIT_OBJECT_0) return -1; + ResetEvent(read_event_); + OVERLAPPED operation{}; operation.hEvent = read_event_; DWORD count = 0; + int result = ReadFile(pipe_, &read_buffer_, sizeof(read_buffer_), &count, &operation) != FALSE ? 1 : -1; + if (result < 0 && GetLastError() == ERROR_IO_PENDING) result = wait_pipe(pipe_, operation, stop_, deadline_, timeout, count); + if (result == 0) return WaitForSingleObject(stop_, 0) == WAIT_OBJECT_0 ? -1 : 0; + if (result < 0 || !decode_packet(reinterpret_cast(&read_buffer_), count, false, out.packet)) return -1; + out.pid = peer_; out.resource = 0; + // Only a receiving instance takes handles, and only from the producer's own handle table. + if (producer_ && out.packet.resource) { + HANDLE local = nullptr; + if (!DuplicateHandle(producer_, reinterpret_cast(static_cast(out.packet.resource)), GetCurrentProcess(), &local, 0, FALSE, + DUPLICATE_SAME_ACCESS)) { + // An exited producer took its handles with it; a live one named a handle it does not own. + if (WaitForSingleObject(producer_, 0) != WAIT_OBJECT_0) invalid_resource_ = true; + interrupt(); return -1; + } + out.resource = reinterpret_cast(local); + } + return 1; + } +}; +/** Per-user pipe security; remote clients are rejected by the pipe mode. */ +std::string user_pipe_sddl() { + HANDLE token = nullptr; DWORD size = 0; + if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) throw std::runtime_error("Cannot inspect receiver identity"); + GetTokenInformation(token, TokenUser, nullptr, 0, &size); + std::vector data(size); + bool ok = GetTokenInformation(token, TokenUser, data.data(), size, &size) != FALSE; + CloseHandle(token); + LPSTR sid = nullptr; + if (!ok || !ConvertSidToStringSidA(reinterpret_cast(data.data())->User.Sid, &sid)) throw std::runtime_error("Cannot encode receiver identity"); + std::string sddl = std::string("D:P(A;;GA;;;") + sid + ")"; LocalFree(sid); + return sddl; +} +/** + * Pipe instances of one channel name. One instance waits for a client at a time; an instance whose client connected + * becomes a candidate after its hello arrives within the handshake deadline. The active connection, a waiting + * successor and a candidate being refused each hold an instance. + */ +class PipeListener final : public Listener { + std::string name_, sddl_; + uint32_t handshake_ms_; + HANDLE stop_ = nullptr, deadline_ = nullptr, instance_ = INVALID_HANDLE_VALUE; + OVERLAPPED connect_{}; + bool first_ = true, connecting_ = false; + static constexpr DWORD instances = 4; + /** Longest hello wait between checks for a stop request. */ + static constexpr long long handshake_slice_ms = 50; + void open_instance() { + PSECURITY_DESCRIPTOR descriptor = nullptr; + if (!ConvertStringSecurityDescriptorToSecurityDescriptorA(sddl_.c_str(), SDDL_REVISION_1, &descriptor, nullptr)) throw std::runtime_error("Cannot restrict frame-forwarding pipe"); + SECURITY_ATTRIBUTES security{sizeof(security), descriptor, FALSE}; + const DWORD open_mode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | (first_ ? FILE_FLAG_FIRST_PIPE_INSTANCE : 0); + instance_ = CreateNamedPipeA(name_.c_str(), open_mode, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, + instances, sizeof(WireMessage) * 4, sizeof(WireMessage) * 4, 0, &security); + LocalFree(descriptor); + if (instance_ == INVALID_HANDLE_VALUE) throw std::runtime_error("Cannot open private frame-forwarding pipe"); + first_ = false; + } + void close_handles() { + if (instance_ != INVALID_HANDLE_VALUE) { + CancelIoEx(instance_, nullptr); + // A pending connect writes connect_ when it completes, so the cancelled operation finishes before its release. + DWORD count = 0; + if (connecting_) { GetOverlappedResult(instance_, &connect_, &count, TRUE); connecting_ = false; } + CloseHandle(instance_); instance_ = INVALID_HANDLE_VALUE; + } + if (connect_.hEvent) { CloseHandle(connect_.hEvent); connect_.hEvent = nullptr; } + if (stop_) { CloseHandle(stop_); stop_ = nullptr; } + if (deadline_) { CloseHandle(deadline_); deadline_ = nullptr; } + } + public: + PipeListener(const Endpoint& endpoint, uint32_t handshake_ms) : name_(endpoint.name), handshake_ms_(handshake_ms) { + try { + sddl_ = user_pipe_sddl(); + stop_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); + deadline_ = create_deadline_timer(); + connect_.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (!stop_ || !deadline_ || !connect_.hEvent) throw std::runtime_error("Cannot create frame-forwarding I/O wait events"); + open_instance(); + } catch (...) { close_handles(); throw; } + } + ~PipeListener() override { close_handles(); } + void interrupt() override { SetEvent(stop_); if (instance_ != INVALID_HANDLE_VALUE) CancelIoEx(instance_, nullptr); } + int accept(Candidate& candidate, uint32_t timeout) override { + if (WaitForSingleObject(stop_, 0) == WAIT_OBJECT_0) return -1; + if (instance_ == INVALID_HANDLE_VALUE) open_instance(); + DWORD count = 0; + if (!connecting_) { + ResetEvent(connect_.hEvent); + const bool connected = ConnectNamedPipe(instance_, &connect_) != FALSE; + const auto error = GetLastError(); + if (!connected && error == ERROR_IO_PENDING) connecting_ = true; + else if (!connected && error != ERROR_PIPE_CONNECTED) { CloseHandle(instance_); instance_ = INVALID_HANDLE_VALUE; return 0; } + } + if (connecting_) { + HANDLE events[] = {connect_.hEvent, stop_}; + const auto waited = WaitForMultipleObjects(2, events, FALSE, timeout); + if (waited == WAIT_TIMEOUT) return 0; + if (waited != WAIT_OBJECT_0) return -1; + connecting_ = false; + if (!GetOverlappedResult(instance_, &connect_, &count, FALSE)) { CloseHandle(instance_); instance_ = INVALID_HANDLE_VALUE; return 0; } + } + // The connected instance belongs to its candidate; the next accept opens another one. + HANDLE pipe = instance_; instance_ = INVALID_HANDLE_VALUE; + ULONG pid = 0; + if (!GetNamedPipeClientProcessId(pipe, &pid)) { CloseHandle(pipe); return 0; } + HANDLE producer = OpenProcess(PROCESS_DUP_HANDLE | SYNCHRONIZE, FALSE, pid); + if (!producer) { CloseHandle(pipe); return 0; } + auto channel = std::make_unique(pipe, static_cast(pid), producer); + Received hello; + // interrupt() no longer reaches the instance this channel now owns, so the hello wait checks for a stop between slices. + const auto handshake_end = std::chrono::steady_clock::now() + std::chrono::milliseconds(handshake_ms_); + int received = 0; + do { + if (WaitForSingleObject(stop_, 0) == WAIT_OBJECT_0) return -1; + const auto left = std::chrono::duration_cast(handshake_end - std::chrono::steady_clock::now()).count(); + received = channel->receive(hello, static_cast(std::clamp(left, 0, handshake_slice_ms))); + } while (received == 0 && std::chrono::steady_clock::now() < handshake_end); + if (received != 1 || hello.resource) { release_resource(hello.resource); return 0; } + candidate.hello = hello; candidate.channel = std::move(channel); + return 1; + } +}; +std::unique_ptr listen(Endpoint& endpoint, uint32_t handshake_ms) { return std::make_unique(endpoint, handshake_ms); } +std::unique_ptr connect_channel(const Endpoint& endpoint, const std::function& cancelled) { return std::make_unique(endpoint, cancelled); } +uint32_t process_id() { return GetCurrentProcessId(); } +void release_resource(uintptr_t resource) { if (resource) CloseHandle(reinterpret_cast(resource)); } +uint64_t resource_bytes(uintptr_t) { return 0; } +bool source_ready(ID3D11Texture2D* texture, std::chrono::steady_clock::time_point deadline, std::string& diagnostic); +/** + * Open a producer frame on the validation device of its adapter and check its description. The texture stays open + * in `texture`, also when the description is invalid. While the producer renders, a keyed-mutex frame released + * without taking key 0, or opened a second time, stays charged to this process's GPU memory after release; callers + * take key 0 on this open and never open the frame again. + */ +bool open_frame(uintptr_t resource, uint32_t width, uint32_t height, uint32_t stride, std::string& diagnostic, + std::string& adapter, bool* keyed_mutex, ComPtr& texture) { + const auto failed = [&](const char* operation, HRESULT result) { + std::ostringstream text; text << operation << " HRESULT=0x" << std::hex << static_cast(result); + if (!adapter.empty()) text << " adapter=" << adapter; + diagnostic = text.str(); return false; + }; + adapter = resource_adapter(resource); + if (adapter.empty()) return failed("Cannot identify shared texture adapter", E_INVALIDARG); + if (validation_device && device_adapter(validation_device) != adapter) clear_validation_device(); + if (!validation_device) { + ComPtr factory; ComPtr selected; + auto result = CreateDXGIFactory1(IID_PPV_ARGS(&factory)); + if (FAILED(result)) return failed("Cannot enumerate shared texture adapters", result); + for (UINT index = 0; ; ++index) { + ComPtr candidate; + result = factory->EnumAdapters1(index, &candidate); + if (result == DXGI_ERROR_NOT_FOUND) break; + if (FAILED(result)) return failed("Cannot enumerate shared texture adapters", result); + DXGI_ADAPTER_DESC1 desc{}; + if (SUCCEEDED(candidate->GetDesc1(&desc)) && adapter_id(desc.AdapterLuid) == adapter) { selected = candidate; break; } + } + if (!selected) return failed("Shared texture adapter is unavailable", DXGI_ERROR_NOT_FOUND); + ComPtr device; ComPtr device1; + result = D3D11CreateDevice(selected.Get(), D3D_DRIVER_TYPE_UNKNOWN, nullptr, D3D11_CREATE_DEVICE_BGRA_SUPPORT, nullptr, 0, D3D11_SDK_VERSION, &device, nullptr, nullptr); + if (FAILED(result)) return failed("D3D11 hardware receiver unavailable", result); + result = device.As(&device1); + if (FAILED(result)) return failed("D3D11.1 receiver unavailable", result); + validation_device = device1.Detach(); + } + auto result = validation_device->OpenSharedResource1(reinterpret_cast(resource), IID_PPV_ARGS(&texture)); + if (FAILED(result)) return failed("Shared texture is incompatible with receiver GPU", result); + D3D11_TEXTURE2D_DESC desc{}; texture->GetDesc(&desc); + if (keyed_mutex) *keyed_mutex = (desc.MiscFlags & D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX) != 0; + const bool valid = desc.Width == width && desc.Height == height && desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM && + stride == width * 4 && desc.MipLevels == 1 && desc.ArraySize == 1 && desc.SampleDesc.Count == 1 && (desc.MiscFlags & D3D11_RESOURCE_MISC_SHARED_NTHANDLE); + if (!valid) diagnostic = "Shared D3D11 texture format, dimensions or sharing flags differ; adapter=" + adapter; + return valid; +} +bool resource_dimensions(uintptr_t resource, uint32_t width, uint32_t height, uint32_t stride, + std::chrono::steady_clock::time_point deadline, std::string& diagnostic, std::string& adapter, bool* keyed_mutex) { + ComPtr texture; + bool valid = open_frame(resource, width, height, stride, diagnostic, adapter, keyed_mutex, texture); + if (!texture) return false; + std::string synchronization; + if (!source_ready(texture.Get(), deadline, synchronization) && valid) { diagnostic = synchronization; valid = false; } + texture.Reset(); + // This context submits no GPU work; Flush retires released validation textures. + ComPtr reclamation; + validation_device->GetImmediateContext(&reclamation); + reclamation->Flush(); + return valid; +} +#include "relay-transport.inc" +#endif +uintptr_t receive_resource(Received& received) { auto resource = received.resource; received.resource = 0; return resource; } +} diff --git a/packages/experimental/frame-forwarding/native/transport.h b/packages/experimental/frame-forwarding/native/transport.h new file mode 100644 index 0000000000..ff22242b54 --- /dev/null +++ b/packages/experimental/frame-forwarding/native/transport.h @@ -0,0 +1,160 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#define DSH_FRAME_FORWARDING_PROTOCOL_VERSION 2 +#define DSH_FRAME_FORWARDING_TEXT_CAPACITY 16384 +namespace dsh_frame_forwarding { +constexpr uint32_t magic = 0x44535231; +enum Kind : uint32_t { hello = 1, ready, frame, release, message, goodbye, allocate, allocated, deallocate }; +/** hello.max_frames carries optional capabilities; zero is the legacy producer. */ +constexpr uint32_t hello_keyed_mutex = 1; +/** + * The producer holds a transferable TX credential and requires the connection identifier in ready.token. Receivers + * refuse producers without it, so a producer that relied on PID binding never connects. + */ +constexpr uint32_t hello_transferable = 2; +/** + * Every handle a producer names belongs to the producer: on Windows frame.resource is a handle value in the producer's + * process, which the receiver duplicates from that process. Receivers refuse producers without it, and ready.stride + * echoes the hello capabilities the receiver accepted, so producers refuse receivers that would read the value as a + * handle of their own. + */ +constexpr uint32_t hello_producer_local_handles = 4; +/** The hello capabilities a receiver of these sources accepts and echoes in ready.stride. */ +constexpr uint32_t hello_capabilities = hello_keyed_mutex | hello_transferable | hello_producer_local_handles; +/** + * frame.max_frames carries per-frame flags; zero is an ordered frame. A replaceable frame may be dropped before + * presentation once a newer replaceable frame of the same view is ready; receivers that ignore the flag present it. + */ +constexpr uint32_t frame_replaceable = 1; +/** goodbye.text of a candidate the receiver refuses before it receives a connection identifier. */ +constexpr const char* reject_busy = "channel-busy"; +constexpr const char* reject_capability = "transferable-tx-required"; +constexpr const char* reject_local_handles = "producer-local-handles-required"; +constexpr const char* reject_credential = "invalid-credential"; +constexpr const char* reject_closed = "channel-closed"; +/** Prefix of a refusal that names the producer's and the receiver's protocol versions. */ +constexpr const char* reject_protocol = "protocol-mismatch"; +struct Packet { + uint32_t marker = magic, version = DSH_FRAME_FORWARDING_PROTOCOL_VERSION, kind = 0; + uint32_t width = 0, height = 0, stride = 0, max_frames = 0; + uint64_t frame_id = 0, allocation_id = 0, max_bytes = 0, resource = 0; + /** hello: the TX secret. After the handshake: the decimal connection identifier. */ + char token[65] = {}; + char text[DSH_FRAME_FORWARDING_TEXT_CAPACITY] = {}; +}; +/** + * Wire form of a Packet: this header, then text_size bytes of text. text_size counts the text before its terminating + * NUL, or is DSH_FRAME_FORWARDING_TEXT_CAPACITY for a text without one, which is sent whole and stays unterminated so + * the receiver refuses it. Mach messages pad the text with zeros to a multiple of 4 bytes. Protocol 1 sent the whole + * Packet; only the marker, version, and kind of its hello are read, so that hello is refused as another version. + */ +struct WireHeader { + uint32_t marker = magic, version = DSH_FRAME_FORWARDING_PROTOCOL_VERSION, kind = 0; + uint32_t width = 0, height = 0, stride = 0, max_frames = 0; + uint32_t text_size = 0; + uint64_t frame_id = 0, allocation_id = 0, max_bytes = 0, resource = 0; + char token[65] = {}; + char reserved[7] = {}; +}; +static_assert(sizeof(WireHeader) == 136, "WireHeader layout"); +struct Received { Packet packet; uint32_t pid = 0; uintptr_t resource = 0; }; +/** + * One physical producer connection. receive returns 1 data, 0 timeout, -1 closed/error. After bind_connection, every + * sent packet carries the connection identifier and a received packet without it closes the channel. + */ +class Channel { + public: + virtual ~Channel() = default; + int receive(Received& out, uint32_t timeout_ms); + bool send(const Packet& packet, uintptr_t resource = 0); + void bind_connection(uint64_t id); + uint64_t connection() const { return connection_; } + /** The last receive closed because a packet named another connection. */ + bool foreign_packet() const { return foreign_; } + /** The last receive closed because a packet named a handle its live sender does not own. */ + bool invalid_resource() const { return invalid_resource_; } + virtual void interrupt() = 0; + virtual uint32_t peer_pid() const = 0; + protected: + virtual int receive_packet(Received&, uint32_t timeout_ms) = 0; + virtual bool send_packet(const Packet&, uintptr_t resource) = 0; + bool invalid_resource_ = false; + private: + uint64_t connection_ = 0; + char connection_text_[65] = {}; + bool foreign_ = false; +}; +/** A producer whose hello reached the listener; its channel answers it before acceptance or refusal. */ +struct Candidate { Received hello; std::unique_ptr channel; }; +/** The stable endpoint of one logical channel. Each producer connection gets a channel of its own. */ +class Listener { + public: + virtual ~Listener() = default; + /** 1 candidate, 0 timeout, -1 stopped or failed. Malformed or silent connections are dropped without affecting others. */ + virtual int accept(Candidate& candidate, uint32_t timeout_ms) = 0; + virtual void interrupt() = 0; +}; +struct Endpoint { uint32_t pid; std::string token, name; }; +Endpoint parse_endpoint(const std::string& value); +/** Publish the endpoint name. handshake_ms bounds how long a connected client may withhold its hello. */ +std::unique_ptr listen(Endpoint& endpoint, uint32_t handshake_ms); +std::unique_ptr connect_channel(const Endpoint& endpoint, const std::function& cancelled = {}); +/** Parse a decimal connection identifier from a token; 0 when it is not one. */ +uint64_t parse_connection(const char (&token)[65]); +uint32_t process_id(); +uintptr_t receive_resource(Received& received); +void release_resource(uintptr_t resource); +void clear_validation_device(); +uint64_t resource_bytes(uintptr_t resource); +/** + * Validate a producer frame's format and dimensions and report its adapter. On Windows a keyed-mutex texture is also + * made ready: key 0 is acquired within the deadline and released, before Chromium's unbounded key-0 acquisition. + */ +bool resource_dimensions(uintptr_t resource, uint32_t width, uint32_t height, uint32_t stride, + std::chrono::steady_clock::time_point deadline, std::string& diagnostic, std::string& adapter, bool* keyed_mutex = nullptr); +/** Adapter owning a shared resource, or an empty string when it cannot be identified. */ +std::string resource_adapter(uintptr_t resource); +/** Adapter owning the producer's graphics device. */ +std::string device_adapter(void* device); +#if defined(_WIN32) +struct RelayDevice; +struct RelayTexture; +struct RelayReadback; +struct RelaySource; +uintptr_t relay_handle(const std::shared_ptr& texture); +bool relay_begin(uintptr_t resource, uint32_t width, uint32_t height, + const std::string& adapter, std::chrono::steady_clock::time_point deadline, const std::atomic& stopped, + std::shared_ptr& display, std::shared_ptr& slot, std::string& diagnostic); +int relay_advance(const std::shared_ptr& slot, const std::atomic& stopped, + std::chrono::steady_clock::time_point deadline, std::string& diagnostic); +uintptr_t relay_completion_event(const std::shared_ptr& slot); +/** True only after every submitted copy completes or its device is removed. */ +bool relay_gpu_idle(const std::shared_ptr& slot, std::string& diagnostic); +/** Validate each frame and copy under key 0; reuse the allocation's import only for the same NT object and dimensions. */ +bool relay_readback_begin(uintptr_t resource, uint32_t width, uint32_t height, uint32_t stride, + std::shared_ptr& slot, std::shared_ptr& imported, + std::string& diagnostic, std::string& adapter, bool* keyed_mutex, + std::chrono::steady_clock::time_point deadline); +int relay_readback_ready(const std::shared_ptr& slot, bool retiring, std::string& diagnostic); +uintptr_t relay_readback_event(const std::shared_ptr& slot); +int relay_upload(const std::shared_ptr& source, uint32_t width, uint32_t height, + const std::string& adapter, std::shared_ptr& display, std::shared_ptr& target, + std::chrono::steady_clock::time_point deadline, const std::atomic& stopped, std::string& diagnostic); +uintptr_t create_gpu_retry_timer(); +/** Borrowed device; the relay image retains its lifetime. */ +void* relay_output_device(const std::shared_ptr& texture); +void relay_forget_source(const std::shared_ptr& texture); +/** Copy the retained image and signal its existing completion fence. */ +bool relay_copy_output(const std::shared_ptr& texture, void* destination, std::string& diagnostic); +bool relay_readback_image(const std::shared_ptr& texture, std::shared_ptr& staging, std::string& diagnostic); +int relay_with_pixels(const std::shared_ptr& staging, + const std::function& consume, std::string& diagnostic); +#endif +} diff --git a/packages/experimental/frame-forwarding/package.json b/packages/experimental/frame-forwarding/package.json new file mode 100644 index 0000000000..8ffbef1470 --- /dev/null +++ b/packages/experimental/frame-forwarding/package.json @@ -0,0 +1,84 @@ +{ + "name": "@deepseek-ai/dsh-frame-forwarding", + "description": "Experimental native frame forwarding: transferable channels whose producer processes present frames through Desktop shared textures", + "version": "0.2.3-alpha.2", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/experimental/frame-forwarding" + }, + "license": "MIT", + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./client": { + "types": "./lib/types/client/index.d.ts", + "default": "./lib/client.js" + }, + "./types": { + "types": "./lib/types/types.d.ts" + }, + "./typert": { + "types": "./lib/typert.host.d.ts", + "default": "./lib/typert.host.js" + }, + "./remote": { + "types": "./lib/typert.remote-client.d.ts", + "default": "./lib/typert.remote-client.js" + }, + "./locale/*.json": "./locale/*.json", + "./package.json": "./package.json", + "./src/*": "./src/*" + }, + "files": [ + "locale/*.json", + "lib/index.js", + "lib/client.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "lib/typert.host.js", + "lib/typert.host.d.ts", + "lib/typert.remote-client.js", + "lib/typert.remote-client.d.ts", + "lib/typert.remote-client.d.ts.map", + "src" + ], + "scripts": { + "bundle": "tsdown" + }, + "dsh": { + "client": { + "inject": [ + "@deepseek-ai/dsh-api-remotes", + "@deepseek-ai/dsh-shared-texture" + ], + "platform": "web" + } + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~" + }, + "dependencies": { + "@deepseek-ai/schemastery": "workspace:~", + "@deepseek-ai/dsh-brand": "workspace:*", + "@deepseek-ai/dsh-typert-protocol": "workspace:*", + "@deepseek-ai/dsh-util-values": "workspace:*", + "zod": "4.6.6" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-api-remotes": "workspace:*", + "@deepseek-ai/dsh-shared-texture": "workspace:*", + "@deepseek-ai/libreoffice-kit": "0.2.3", + "node-api-headers": "1.9.0" + } +} diff --git a/packages/experimental/frame-forwarding/src/client/api.ts b/packages/experimental/frame-forwarding/src/client/api.ts new file mode 100644 index 0000000000..74e48fc0bf --- /dev/null +++ b/packages/experimental/frame-forwarding/src/client/api.ts @@ -0,0 +1,138 @@ +/** + * Public renderer-side frame-forwarding types. This module imports no Desktop module, so the package's published + * declarations expose frame forwarding only. + */ +import type { + FrameChannelState, FrameConnectionId, FrameFailureSource, FrameForwardingEvent, FrameForwardingFrameMetadata, FrameForwardingViewport, + FrameRxId, FrameViewportResult, +} from '../types.ts' +import type { FrameDiscardedError } from './errors.ts' +import type { FrameRx } from './rx.ts' + +/** + * One forwarded frame lent to a consumer callback until the callback returns or its returned promise settles. Frame + * forwarding then closes `image`, which returns its resources to the Host; a Desktop shared texture returns to the + * producer only after Desktop reports every Electron reference gone, which follows completion of the GPU work submitted + * with `image`. Draw, upload, or copy `image` within that period; a retained `image` or clone keeps its resources in use + * until it is closed. How `image` is backed and its pixel `format` depend on the Host, so read pixels only through + * `drawImage`, or through `copyTo` with an explicit `format`. + */ +export interface FrameForwardingFrame { + readonly image: VideoFrame + readonly metadata: FrameForwardingFrameMetadata +} + +/** A delivered texture and its single release, owned by the receive channel that received it. */ +export interface FrameForwardingFrameLease { + readonly frame: VideoFrame + readonly metadata: FrameForwardingFrameMetadata + release(): void +} + +/** + * The document's fullscreen state as one receive channel sees it. `active`: an element of the document is fullscreen. + * `holder`: this channel requested the fullscreen element; with `active: false`, the fullscreen it held just ended. + * While another element is fullscreen, the channel's view is covered. + */ +export interface FrameFullscreenState { + readonly active: boolean + readonly holder: boolean +} + +/** Content coordinate at the mount's top-left corner and CSS pixels per content unit; scale is in (0, 64]. */ +export interface FrameContentView { + readonly x: number + readonly y: number + readonly scale: number +} + +/** Immutable content rectangle covered by every frame of one viewport generation; extents are in (0, 2^24]. */ +export interface FrameContentWindow { + readonly x: number + readonly y: number + readonly width: number + readonly height: number +} + +/** + * What one receive channel learns besides frames: its latest Host state, a frame failure of one connection, a + * renderer-side failure that ends the channel's frame routing (including termination of the Client's channel-event + * stream and Client disposal), fullscreen state, or mounted presentation state. + * FrameRx.onEvent replays state, viewport, fullscreen, and submitted generation on subscription. + */ +export type FrameRxEvent = + | { readonly kind: 'state'; readonly channel: FrameChannelState } + /** Latest viewport version, published before its Host request is sent. */ + | { readonly kind: 'viewport'; readonly viewport: FrameForwardingViewport } + | { + readonly kind: 'error' + readonly connectionId: FrameConnectionId + readonly source: FrameFailureSource + readonly requestId?: string + readonly error: string + } + | { readonly kind: 'failure'; readonly error: string } + | ({ readonly kind: 'fullscreen' } & FrameFullscreenState) + /** Latest generation written to the video track; submission does not establish scanout. */ + | { readonly kind: 'content'; readonly submittedGeneration: number | undefined } + +/** The frame and event callbacks of one attached receive channel. */ +export interface FrameChannelReceiver { + readonly onFrame: (lease: FrameForwardingFrameLease) => void + readonly onEvent: (event: FrameRxEvent) => void +} + +/** Channel-scoped frame transport over the textures the Host forwards and the Host's `frameForwarding` Remote. */ +export interface FrameForwardingBridge { + /** Send a viewport to the Host, which keeps it for the channel and applies it to the current connection. */ + setViewport(rx: FrameRxId, viewport: FrameForwardingViewport): Promise + /** + * Attach one receiver and synchronously replay its known channel and active fullscreen states. + * @param rx - Channel receiving frames and events across producer connections. + * @param receiver - Owns each delivered lease. A throwing frame callback loses its lease and registration. + * @returns Detach this registration immediately and await its fullscreen exit. Delivered leases stay with their holders. + */ + attach(rx: FrameRxId, receiver: FrameChannelReceiver): () => Promise + /** Apply one item of the Host's event stream; a snapshot replaces every known state. Ignored after `fail`. */ + apply(event: FrameForwardingEvent): void + /** + * Make `element` the document's fullscreen element on behalf of a channel. Chromium grants fullscreen only while the + * document handles a user gesture, so call it before the gesture's handler awaits anything. + * @param rx - Channel that holds fullscreen until it ends. + * @param element - Element to show fullscreen. + * @returns Completion of the entry; rejects when another channel holds fullscreen or the document refuses it. + */ + requestFullscreen(rx: FrameRxId, element: Element): Promise + /** + * Leave the fullscreen a channel holds; an entry still pending completes first. + * @param rx - Channel that requested fullscreen. + * @returns Completion of the exit; resolves at once when the channel holds no fullscreen. + */ + exitFullscreen(rx: FrameRxId): Promise + /** + * Report failure to every known channel; later subscriptions receive the failure at once. Afterwards the bridge + * forgets every channel state, releases arriving textures, ignores Host events, and rejects viewports. Repeated + * calls and calls after `dispose` do nothing. + * @param message - Failure text every channel receives. + */ + fail(message: string): void + /** Stop texture delivery and fullscreen observation for every channel, and leave the fullscreen a channel holds. */ + dispose(): void +} + +/** Renderer-side frame forwarding; consumers connect to channels their Host plugin opened. */ +export interface FrameForwardingClient { + /** + * Connect the renderer to a Host-opened channel; the returned receive channel serves every producer connection the + * channel has, and the Host's per-channel frame limit bounds every frame it holds. + * @param rx - Channel the consumer's Host plugin opened. + * @returns The receive channel, which the consumer closes. + */ + connect(rx: FrameRxId): FrameRx + /** + * Classify a rejected frame wait. Consumers in other Client bundles cannot import this package's error class. + * @param error - Rejection of a channel operation such as `ready` or `setViewport`. + * @returns The lifecycle event that made the frame unnecessary, or undefined for a transport, producer, or consumer failure. + */ + discardReason(error: unknown): FrameDiscardedError['reason'] | undefined +} diff --git a/packages/experimental/frame-forwarding/src/client/content.ts b/packages/experimental/frame-forwarding/src/client/content.ts new file mode 100644 index 0000000000..3e30249816 --- /dev/null +++ b/packages/experimental/frame-forwarding/src/client/content.ts @@ -0,0 +1,46 @@ +/** Content-coordinate validation and generation mapping shared by the mounted browser presenters. */ +import type { FrameContentView, FrameContentWindow } from './api.ts' + +/** A complete document snapshot: current and previous distinct windows, each at its latest submitted generation, in ascending order. */ +export interface ContentState { + readonly view: FrameContentView + readonly windows: readonly (FrameContentWindow & { readonly generation: number })[] +} + +/** Content coordinates and extents are bounded before they cross the geometry IPC. */ +const MAX_CONTENT_COORDINATE = 2 ** 24 + +function coordinate(value: number): boolean { + return Number.isFinite(value) && Math.abs(value) <= MAX_CONTENT_COORDINATE +} + +/** Validate a view without changing state or sending geometry. + * @param view - Content origin and CSS pixels per content unit. + * @throws TypeError for non-finite or out-of-range coordinates or a scale outside (0, 64]. + */ +export function validateView(view: FrameContentView): void { + if (!coordinate(view.x) || !coordinate(view.y) || !Number.isFinite(view.scale) || view.scale <= 0 || view.scale > 64) { + throw new TypeError('Frame content view requires coordinates within ±2^24 and scale in (0, 64].') + } +} + +/** Validate a render window without changing state or sending a viewport. + * @param window - Rectangle in the view's content units. + * @throws TypeError for non-finite or out-of-range coordinates or extents, or non-positive extents. + */ +export function validateWindow(window: FrameContentWindow): void { + if (!coordinate(window.x) || !coordinate(window.y) || !coordinate(window.width) || !coordinate(window.height) + || window.width <= 0 || window.height <= 0) { + throw new TypeError('Frame content window requires coordinates within ±2^24 and extents in (0, 2^24].') + } +} + +/** Map a frame's own window using the latest view, without clipping its content. + * @param window - The immutable window bound to the frame's generation. + * @param view - Latest content origin and scale. + * @returns Mount-local CSS rectangle; placement clipping is applied separately. + */ +export function contentFrame(window: FrameContentWindow, view: FrameContentView): FrameContentWindow { + return { x: (window.x - view.x) * view.scale, y: (window.y - view.y) * view.scale, + width: window.width * view.scale, height: window.height * view.scale } +} diff --git a/packages/experimental/frame-forwarding/src/client/element-mount.ts b/packages/experimental/frame-forwarding/src/client/element-mount.ts new file mode 100644 index 0000000000..f1db73553c --- /dev/null +++ b/packages/experimental/frame-forwarding/src/client/element-mount.ts @@ -0,0 +1,179 @@ +import type { FrameForwardingViewport } from '../types.ts' +import type { FrameForwardingFrame, FrameFullscreenState, FrameRxEvent } from './api.ts' +import type { ContentState } from './content.ts' +import { FrameDiscardedError, FrameFailureError } from './errors.ts' +import { createMediaPresenter, type MediaPresenter } from './presenters.ts' + +interface MountOwner { + fullscreen(): FrameFullscreenState + content(): ContentState | undefined + viewport(value: Omit, completion: Promise): Promise + report(event: FrameRxEvent): void + failure(error: Error): void +} + +/** Mount-owned display resources, observed through FrameRx's existing stream and fullscreen state. */ +export interface ElementMount { + present(frame: FrameForwardingFrame): void | Promise + dirty(): void + /** Push the current content snapshot synchronously, before submitting its viewport. */ + pushContent(): void + /** Queue a window change behind the in-flight viewport. + * @returns The latest-only acknowledgement shared by unsent requests; rejects when this display ends. + */ + requestViewport(): Promise + dispose(): void +} + +/** Mount a channel without taking ownership of the channel itself. + * @param element - Container for the video. + * @param owner - Channel-owned viewport, state and error callbacks. + * @returns A display whose disposal cancels observers, stops the media track. + */ +export function mountElement(element: HTMLElement, owner: MountOwner): ElementMount { + const document = element.ownerDocument + const view = document.defaultView + if (view === null) throw new FrameFailureError('presentation', 'The frame mount needs a live document.') + if (element.hasAttribute('data-dsh-frame-mount')) throw new Error('Native element already has a frame consumer.') + let disposed = false + let raf: number | undefined + let intersecting = false + let media: MediaPresenter | undefined + let viewportKey: string | undefined + let viewportPending: ReturnType> | undefined + let requestedViewport: ReturnType> | undefined + let latestViewport: Parameters[0] | undefined + const position = element.style.getPropertyValue('position') + const isolation = element.style.getPropertyValue('isolation') + const positionPriority = element.style.getPropertyPriority('position') + const isolationPriority = element.style.getPropertyPriority('isolation') + const computedPosition = getComputedStyle(element).position + const changePosition = computedPosition === 'static' || computedPosition === '' + const dirty = (): void => { + if (!disposed && raf === undefined) raf = view.requestAnimationFrame(flush) + } + const resize = new ResizeObserver(dirty) + const intersection = new IntersectionObserver((entries) => { + for (const entry of entries) if (entry.target === element) intersecting = entry.isIntersecting + dirty() + }) + // IntersectionObserver tracks geometry but not CSS visibility. Observe the mount's ancestor + // chain for tab hiding and producer trimming, including a docked tab reparented into a float. + let chain: Element[] = [] + const visibilityObserver = new MutationObserver((records) => { + if (records.some(record => record.type === 'attributes' + || [...record.removedNodes].some(node => chain.includes(node as Element)))) dirty() + }) + const shownInLayout = (): boolean => { + const next: Element[] = [] + let shown = true + for (let node: Element | null = element; node !== null; node = node.parentElement) { + next.push(node) + const style = getComputedStyle(node) + shown &&= style.display !== 'none' && style.visibility !== 'hidden' && style.visibility !== 'collapse' + } + if (next.length !== chain.length || next.some((node, index) => node !== chain[index])) { + visibilityObserver.disconnect() + for (const node of next) visibilityObserver.observe(node, { + attributeFilter: ['class', 'style', 'hidden'], childList: true, + }) + chain = next + } + return shown + } + const restore = (property: string, value: string, priority: string): void => { + if (value === '') element.style.removeProperty(property) + else element.style.setProperty(property, value, priority) + } + const dispose = (): void => { + if (disposed) return + disposed = true + const ended = new FrameDiscardedError('producer-changed') + requestedViewport?.reject(ended) + requestedViewport = undefined + viewportPending?.reject(ended) + if (raf !== undefined) view.cancelAnimationFrame(raf) + resize.disconnect() + intersection.disconnect() + visibilityObserver.disconnect() + document.removeEventListener('visibilitychange', visibilityChanged) + view.removeEventListener('resize', dirty) + media?.dispose() + media = undefined + element.removeAttribute('data-dsh-frame-mount') + if (changePosition) restore('position', position, positionPriority) + restore('isolation', isolation, isolationPriority) + owner.report({ kind: 'content', submittedGeneration: undefined }) + } + const fail = (error: unknown): void => { + if (disposed) return + try { dispose() } catch (cleanupError) { console.error('Frame mount cleanup failed', cleanupError) } + owner.failure(error instanceof Error ? error : new FrameFailureError('presentation', String(error))) + } + const sendViewport = (): boolean => { + if (disposed || viewportPending !== undefined || latestViewport === undefined) return false + const viewport = latestViewport + const key = JSON.stringify(viewport) + if (viewportKey === key && requestedViewport === undefined) return false + const completion = requestedViewport ?? Promise.withResolvers() + requestedViewport = undefined + viewportKey = key + viewportPending = completion + void completion.promise.catch((error: unknown) => { + // Producer handoff retains the viewport in Host and is not a mount failure. + if (!(error instanceof FrameDiscardedError && error.reason === 'producer-changed')) fail(error) + }).finally(() => { + viewportPending = undefined + if (disposed) return + if (requestedViewport !== undefined || document.visibilityState === 'hidden') sendViewport() + else if (JSON.stringify(latestViewport) !== viewportKey) dirty() + }) + try { void owner.viewport(viewport, completion.promise).then(completion.resolve, completion.reject) } + catch (error) { completion.reject(error) } + return true + } + const pushContent = (): void => { media?.setContent(owner.content()) } + const requestViewport = (): Promise => { + if (disposed) return Promise.reject(new FrameDiscardedError('producer-changed')) + const completion = requestedViewport ??= Promise.withResolvers() + try { synchronize() } catch (error) { completion.reject(error); fail(error) } + return completion.promise + } + const synchronize = (): void => { + // The display exists before the first viewport goes out, so a frame answering that viewport has somewhere to go. + media ??= createMediaPresenter(element, fail, (submittedGeneration) => { owner.report({ kind: 'content', submittedGeneration }) }) + const rect = element.getBoundingClientRect() + const deviceScaleFactor = view.devicePixelRatio + const fullscreen = owner.fullscreen() + const shown = shownInLayout() + const visible = shown && element.isConnected && intersecting && document.visibilityState === 'visible' + && (!fullscreen.active || fullscreen.holder) && rect.width > 0 && rect.height > 0 + latestViewport = { width: Math.max(1, Math.round(rect.width * deviceScaleFactor)), + height: Math.max(1, Math.round(rect.height * deviceScaleFactor)), deviceScaleFactor, visible } + if (!sendViewport()) pushContent() + } + const visibilityChanged = (): void => { + if (disposed) return + if (document.visibilityState !== 'hidden') { dirty(); return } + // Hidden documents may suspend rAF; the final invisible update must still let the producer trim its surfaces. + try { synchronize() } catch (error) { fail(error) } + } + function flush(): void { + raf = undefined + if (disposed) return + try { + synchronize() + } catch (error) { fail(error) } + } + try { + element.setAttribute('data-dsh-frame-mount', 'video') + if (changePosition) element.style.position = 'relative' + element.style.isolation = 'isolate' + resize.observe(element) + intersection.observe(element) + document.addEventListener('visibilitychange', visibilityChanged) + view.addEventListener('resize', dirty) + dirty() + } catch (error) { dispose(); throw error } + return { present: frame => media?.present(frame), dirty, pushContent, requestViewport, dispose } +} diff --git a/packages/experimental/frame-forwarding/src/client/errors.ts b/packages/experimental/frame-forwarding/src/client/errors.ts new file mode 100644 index 0000000000..4f5b48404b --- /dev/null +++ b/packages/experimental/frame-forwarding/src/client/errors.ts @@ -0,0 +1,28 @@ +/** Expected frame cancellations and located frame failures of a receive channel. */ +import type { FrameFailureSource } from '../types.ts' + +/** Expected frame cancellation, distinct from a failed rendering transport. */ +export class FrameDiscardedError extends Error { + /** + * @param reason - Lifecycle event making the frame unnecessary: cancellation, the receive channel + * closing, the producer connection the request was bound to ending, or Desktop losing the channel's frames. + */ + constructor(readonly reason: 'cancelled' | 'closed' | 'producer-changed' | 'lost') { + super(reason === 'closed' ? 'Native channel closed.' + : reason === 'producer-changed' ? 'Native producer changed.' : reason === 'lost' ? 'Native channel lost.' + : 'Native frame wait cancelled.') + this.name = 'FrameDiscardedError' + } +} + +/** A frame that failed in its producer or in Desktop's presentation. */ +export class FrameFailureError extends Error { + /** + * @param source - Where the frame failed. + * @param message - The Host's description of the failure. + */ + constructor(readonly source: FrameFailureSource, message: string) { + super(message) + this.name = 'FrameFailureError' + } +} diff --git a/packages/experimental/frame-forwarding/src/client/index.ts b/packages/experimental/frame-forwarding/src/client/index.ts new file mode 100644 index 0000000000..98a256720e --- /dev/null +++ b/packages/experimental/frame-forwarding/src/client/index.ts @@ -0,0 +1,19 @@ +/** Frame-forwarding Client entry: the generated Remote contribution and the renderer-side service. */ +import type { Context } from '@deepseek-ai/cordis' +import remote from '@deepseek-ai/dsh-frame-forwarding/remote' +import { mountFrameForwarding } from './mount.ts' + +export { inject } from './mount.ts' +export type { FrameContentView, FrameContentWindow, FrameRxEvent } from './api.ts' +export type { + FrameDiscardedError, FrameFailureError, FrameForwardingClient, FrameForwardingFrame, FrameFullscreenState, + FrameRx, +} from './mount.ts' + +/** Mount the generated `frameForwarding` Remote contribution and provide the renderer-side service. + * @param ctx - Desktop Client plugin scope. + * @returns Disposer withdrawing the service before its Remote contribution. + */ +export function apply(ctx: Context): Promise<() => Promise> { + return mountFrameForwarding(ctx, remote) +} diff --git a/packages/experimental/frame-forwarding/src/client/mount.ts b/packages/experimental/frame-forwarding/src/client/mount.ts new file mode 100644 index 0000000000..1d0e111db5 --- /dev/null +++ b/packages/experimental/frame-forwarding/src/client/mount.ts @@ -0,0 +1,48 @@ +/** + * Frame-forwarding Client plugin: mounts the generated `frameForwarding` Remote contribution and provides the + * renderer-side `frameForwarding` service to consumers. The entry module supplies the contribution, so specs mount a + * fake one. When `ctx.sharedTexture` is absent, the service is not provided. + */ +import type { Context } from '@deepseek-ai/cordis' +import type { TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol' +import type {} from '@deepseek-ai/dsh-api-remotes/client' +import type {} from '@deepseek-ai/dsh-shared-texture/client' +import type { FrameForwardingClient } from './api.ts' +import { FrameForwardingClientService } from './service.ts' + +export type { FrameForwardingClient, FrameForwardingFrame, FrameFullscreenState } from './api.ts' +export type { FrameRx } from './rx.ts' +export type { FrameDiscardedError, FrameFailureError } from './errors.ts' + +/** The Remote transport is the only Client dependency. */ +export const inject = ['remote'] + +/** Provide the renderer-side service while `ctx.sharedTexture` is provided. */ +function register(ctx: Context): void { + ctx.provide('frameForwarding', new FrameForwardingClientService(ctx, ctx.sharedTexture)) +} + +/** + * Mount the frame-forwarding Remote contribution and provide the Client service. + * @param ctx - Client plugin scope. + * @param contribution - Generated `frameForwarding` Remote contribution. + * @returns Disposer withdrawing the service before its Remote contribution. + */ +export async function mountFrameForwarding(ctx: Context, contribution: TypertRemoteContribution): Promise<() => Promise> { + const unmountRemote = await ctx.remote.$mount(contribution) + const service = ctx.inject(['sharedTexture', 'remote.frameForwarding'], register) + if (ctx.get('sharedTexture') !== undefined) { + try { await service } catch (error) { await service.dispose(); await unmountRemote(); throw error } + } + return async () => { await service.dispose(); await unmountRemote() } +} + +declare module '@deepseek-ai/cordis' { + interface Context { + /** + * Renderer-side frame forwarding; provided only in a document that displays the Host's frames, the Desktop + * document, so consumers test for the service rather than for Desktop. + */ + frameForwarding: FrameForwardingClient + } +} diff --git a/packages/experimental/frame-forwarding/src/client/presenters.ts b/packages/experimental/frame-forwarding/src/client/presenters.ts new file mode 100644 index 0000000000..da338fc670 --- /dev/null +++ b/packages/experimental/frame-forwarding/src/client/presenters.ts @@ -0,0 +1,77 @@ +/** Video presentation. Every write retains the borrowed frame until completion; teardown stops owned media tracks. */ +import type { FrameForwardingFrame } from './api.ts' +import type { ContentState } from './content.ts' +import { contentFrame } from './content.ts' +import { FrameFailureError } from './errors.ts' + +/** One mounted media backend's resources. */ +export interface MediaPresenter { + present(frame: FrameForwardingFrame): void | Promise + setContent(content: ContentState | undefined): void + dispose(): void +} + +interface VideoTrackGenerator extends MediaStreamTrack { readonly writable: WritableStream } + +/** Create a Chromium video display inside the placeholder. + * @param element - Container; its positioned descendants remain above the media. + * @param failure - Receives media playback failure while this backend is active. + * @param submitted - Reports the generation accepted by the video track. + * @returns Owned media display, released on backend switch or unmount. + */ +export function createMediaPresenter( + element: HTMLElement, failure: (error: Error) => void, + submitted: (generation: number) => void, +): MediaPresenter { + const video = element.ownerDocument.createElement('video') + Object.assign(video.style, { position: 'absolute', left: '0', top: '0', width: '100%', height: '100%', objectFit: 'fill', pointerEvents: 'none' }) + video.setAttribute('aria-hidden', 'true') + const container = element.ownerDocument.createElement('div') + Object.assign(container.style, { position: 'absolute', inset: '0', overflow: 'hidden', borderRadius: 'inherit', pointerEvents: 'none', zIndex: '-1' }) + container.setAttribute('aria-hidden', 'true') + const Generator = (globalThis as { MediaStreamTrackGenerator?: new (options: { kind: 'video' }) => VideoTrackGenerator }).MediaStreamTrackGenerator + if (Generator === undefined) throw new FrameFailureError('presentation', 'Video presentation requires MediaStreamTrackGenerator.') + const track = new Generator({ kind: 'video' }) + const writer = track.writable.getWriter() + let disposed = false + video.autoplay = true + video.muted = true + video.playsInline = true + const dispose = (): void => { + if (disposed) return + disposed = true + track.stop() + video.pause() + video.srcObject = null + container.remove() + void writer.abort().catch((error: unknown) => { console.error('Frame video writer teardown failed', error) }) + } + try { + video.srcObject = new MediaStream([track]) + container.append(video); element.prepend(container) + void video.play().catch((error: unknown) => { + if (!disposed) failure(new FrameFailureError('presentation', error instanceof Error ? error.message : String(error))) + }) + } catch (error) { dispose(); throw error } + return { + setContent(content) { + const window = content?.windows.at(-1) + const frame = window === undefined || content === undefined ? undefined : contentFrame(window, content.view) + video.style.width = frame === undefined ? '100%' : `${frame.width}px` + video.style.height = frame === undefined ? '100%' : `${frame.height}px` + video.style.transform = frame === undefined ? '' : `translate(${frame.x}px, ${frame.y}px)` + }, + async present({ image, metadata }) { + // The generator consumes its input. A clone leaves the lease's original close with FrameRx. + const copy = image.clone() + try { + await writer.write(copy) + if (!disposed) submitted(metadata.generation) + } catch (error) { + // Disposal cancels outstanding writes. + if (!disposed) throw error + } finally { copy.close() } + }, + dispose, + } +} diff --git a/packages/experimental/frame-forwarding/src/client/rx.ts b/packages/experimental/frame-forwarding/src/client/rx.ts new file mode 100644 index 0000000000..37b3dfb734 --- /dev/null +++ b/packages/experimental/frame-forwarding/src/client/rx.ts @@ -0,0 +1,616 @@ +/** + * Renderer half of one receive channel: viewport ordering, the newest-first stream, + * readiness after producer switches, every frame's release, and the channel's fullscreen. + */ +import { assertNever } from '@deepseek-ai/dsh-util-values' +import { validateView, validateWindow } from './content.ts' +import type { ContentState } from './content.ts' +import { mountElement } from './element-mount.ts' +import type { ElementMount } from './element-mount.ts' +import { FrameDiscardedError, FrameFailureError } from './errors.ts' +import type { FrameChannelCloseCause, FrameChannelState, FrameConnectionId, FrameForwardingViewport, FrameRxId } from '../types.ts' +import type { + FrameContentView, FrameContentWindow, FrameForwardingBridge, FrameForwardingFrame, FrameForwardingFrameLease, + FrameFullscreenState, FrameRxEvent, +} from './api.ts' + +interface FrameStream { + readonly present: (frame: FrameForwardingFrame) => void | Promise + readonly failure: (error: Error) => void +} +interface ReadyWaiter { + resolve(connectionId: FrameConnectionId): void + reject(error: Error): void +} + +function sameWindow(left: FrameContentWindow | undefined, right: FrameContentWindow): boolean { + return left !== undefined && left.x === right.x && left.y === right.y && left.width === right.width && left.height === right.height +} + +function errorOf(error: unknown): Error { + return error instanceof Error ? error : new Error(String(error)) +} + +/** + * Renderer ownership of one Host-opened channel across its producer connections. Every frame it holds is an + * unreleased Host delivery, so the Host's per-channel frame limit bounds it; a frame is released once its consumer + * callback settles or as soon as nothing waits for it. + */ +export class FrameRx { + private readonly detach: () => Promise + private failure: Error | undefined + private channel: FrameChannelState | undefined + /** Highest connection this channel reported; frames of later connections wait until their state arrives. */ + private knownConnection = 0 + private readonly readyWaiters = new Set() + /** Frames of a connection whose connected state has not arrived yet; the Host's frame limit bounds them. */ + private readonly unconfirmed: FrameForwardingFrameLease[] = [] + private closing: Promise | undefined + private viewportVersion = 0 + private viewportState: FrameForwardingViewport | undefined + private viewportReady: Promise = Promise.resolve() + private contentView: FrameContentView | undefined + private contentWindow: FrameContentWindow | undefined + private contentWindows: ContentState['windows'] = [] + private contentRequest: Promise | undefined + private submittedGeneration: number | undefined + private mountStop: ((error?: Error) => void) | undefined + private mounted: ElementMount | undefined + private synchronizeMount: (() => void) | undefined + private stream: FrameStream | undefined + private streamPending: FrameForwardingFrameLease | undefined + private streamDrain: Promise | undefined + private fullscreenState: FrameFullscreenState = { active: false, holder: false } + private readonly eventListeners = new Set<(event: FrameRxEvent) => void>() + private readonly eventTasks: (() => void)[] = [] + private deliveringEvents = false + private eventsEnded = false + private readonly end = Promise.withResolvers() + /** + * Settles once, never rejecting, when this receive channel stops routing frames: with the Host's close cause, with + * `failed` after a renderer-side failure, including termination of the Client's channel-event stream, or with + * `closed` after {@link close}. A consumer learns from it that a `lost` channel + * needs replacing. + */ + readonly closed: Promise = this.end.promise + + /** + * @param rx - Host-issued channel identity. + * @param bridge - Renderer-scoped frame transport. + */ + constructor(readonly rx: FrameRxId, private readonly bridge: FrameForwardingBridge) { + this.detach = bridge.attach(rx, { + onFrame: (lease) => { this.arrive(lease) }, + onEvent: (event) => { this.channelEvent(event) }, + }) + } + + /** The connected producer connection, or undefined while the channel has none. */ + get connectionId(): FrameConnectionId | undefined { + return this.channel?.state === 'connected' ? this.channel.connectionId : undefined + } + + /** + * Invalidate frames of older versions, then send a new viewport; the Host keeps it for later connections. + * @param viewport - Strictly newer viewport version; rejected while mount owns the viewport. + * @returns Completion once the connected producer acknowledged it or, without one, once the Host kept it. Rejects + * with {@link FrameDiscardedError} `producer-changed` when the connection that received it ended first, or + * `closed` when this receive channel closed before sending it; with an Error naming the version the Host kept when + * this version does not exceed it, as on a channel connected again after a renderer reload; or with the Host's + * error when the producer refuses it or does not acknowledge it in time. Later viewports are still sent. + */ + setViewport(viewport: FrameForwardingViewport): Promise { + this.assertOpen() + if (this.mountStop !== undefined) throw new Error('Native viewport is managed by mount.') + return this.updateViewport(viewport).then(() => {}) + } + + /** Latest viewport submitted by mount or setViewport; its version is the generation to request from the producer. */ + get viewport(): FrameForwardingViewport | undefined { return this.viewportState } + + /** + * Set the latest content origin and scale; geometry flushes coalesce changes. Undefined restores fill mode. + * @param view - Content coordinates within ±2^24 and CSS pixels per unit in (0, 64]. + * @throws TypeError for non-finite or out-of-range values; Error outside a mount. Invalid values send nothing. + */ + setContentView(view: FrameContentView | undefined): void { + if (this.mountStop === undefined) throw new Error('Frame content requires mount.') + if (view !== undefined) validateView(view) + this.contentView = view === undefined ? undefined : { ...view } + this.mounted?.dirty() + } + + /** + * Bind a render window to a new viewport generation. Call only after the preceding paint resolves; this method + * serializes viewport updates, not paints. Unsent requests coalesce to the latest window. An in-flight mount + * viewport completes first; the returned viewport includes this window (or the latest coalesced request). + * The window snapshot reaches the mounted presenter before its viewport reaches Host. + * @param window - Content rectangle; coordinates within ±2^24, extents in (0, 2^24]. + * @returns The acknowledged viewport to use as paint generation, or the current acknowledged viewport for an + * unchanged window. Rejections match mount viewport updates; a draining display rejects with producer-changed. + * @throws TypeError for invalid numeric values, synchronously without messages; Error outside a mount. + */ + setContentWindow(window: FrameContentWindow): Promise { + if (this.mountStop === undefined) throw new Error('Frame content requires mount.') + validateWindow(window) + if (sameWindow(this.contentWindow, window) && this.contentRequest !== undefined) return this.contentRequest + const desired = this.contentWindow = { ...window } + if (this.mounted === undefined) return Promise.reject(new FrameDiscardedError('producer-changed')) + const request = this.mounted.requestViewport() + if (this.contentWindow === desired) this.contentRequest = request + return request + } + + private contentSnapshot(): ContentState | undefined { + return this.contentView === undefined || this.contentWindows.length === 0 ? undefined + : { view: this.contentView, windows: this.contentWindows } + } + + private mountViewport( + value: Omit, completion: Promise, + ): Promise { + this.contentRequest = completion + return this.automaticViewport(value, (viewport) => { + if (this.contentWindow !== undefined) { + const current = this.contentWindows.at(-1) + // A viewport-only version replaces current; only a different content rectangle advances previous. + const previous = sameWindow(current, this.contentWindow) ? this.contentWindows.at(-2) : current + this.contentWindows = [...previous === undefined ? [] : [previous], { ...this.contentWindow, generation: viewport.version }] + } + this.mounted?.pushContent() + }) + } + + private automaticViewport( + value: Omit, beforeSend?: (viewport: FrameForwardingViewport) => void, + ): Promise { + return this.updateViewport({ ...value, version: this.viewportVersion + 1 }, beforeSend ?? (() => {})) + } + + /** Document frames older than the submitted generation are stale, so the display never moves back. */ + private acceptsGeneration(generation: number): boolean { + const content = this.contentSnapshot() + if (content === undefined) return generation === this.viewportVersion + return (this.submittedGeneration === undefined || generation >= this.submittedGeneration) + && content.windows.some(window => window.generation === generation) + } + + private updateViewport( + initial: FrameForwardingViewport, automatic?: (viewport: FrameForwardingViewport) => void, + ): Promise { + if (initial.version <= this.viewportVersion) throw new Error('Native viewport version must increase.') + const publish = (viewport: FrameForwardingViewport): void => { + this.viewportVersion = viewport.version + this.viewportState = viewport + automatic?.(viewport) + this.discardPending(true) + this.deliverEvent({ kind: 'viewport', viewport }, false, false) + } + const sent = this.viewportReady.then(async () => { + // A newer consumer of the same channel may own its viewport once this one closed. + this.assertOpen() + let viewport = initial + let result = await this.bridge.setViewport(this.rx, viewport) + // A new renderer can mount before its first snapshot, or while the producer still acknowledges an older viewport. + if (!result.applied && result.reason === 'stale-viewport' && automatic !== undefined && this.viewportState === initial) { + this.assertOpen() + viewport = { ...initial, version: result.currentVersion + 1 } + publish(viewport) + result = await this.bridge.setViewport(this.rx, viewport) + } + if (!result.applied && result.reason === 'stale-viewport') throw new Error(`Native viewport version must increase past ${result.currentVersion}.`) + if (!result.applied && result.reason === 'producer-changed') throw new FrameDiscardedError('producer-changed') + return viewport + }) + // Viewports reach the Host in order; a rejection fails only its own call, and the Host keeps the channel open. + this.viewportReady = sent.then(() => {}, () => {}) + publish(initial) + return sent + } + + /** + * Wait until a producer is connected and has acknowledged this channel's latest viewport. + * @param signal - Cancels the wait. + * @returns The ready connection. Rejects with {@link FrameDiscardedError} on cancellation or close, or with the + * channel's failure. + */ + ready(signal?: AbortSignal): Promise { + this.assertOpen() + const current = this.readyConnection() + if (current !== undefined) return Promise.resolve(current) + if (signal?.aborted === true) return Promise.reject(new FrameDiscardedError('cancelled')) + return new Promise((resolve, reject) => { + const abort = (): void => { + this.readyWaiters.delete(waiter) + reject(new FrameDiscardedError('cancelled')) + } + const waiter: ReadyWaiter = { + resolve: (connectionId) => { signal?.removeEventListener('abort', abort); resolve(connectionId) }, + reject: (error) => { signal?.removeEventListener('abort', abort); reject(error) }, + } + this.readyWaiters.add(waiter) + signal?.addEventListener('abort', abort, { once: true }) + }) + } + + /** + * Present the channel's continuous frames newest first across producer switches: while `present` runs, only the + * newest arrived frame waits, and a newer arrival releases the waiting one unpresented. Depending on the Host, a + * continuous frame may be lossily encoded. + * @param present - Draws one frame; the frame is released after `present` returns or its promise settles. + * @param failure - Receives frame failures of the connected producer, the channel's failure or closure, or an error + * `present` raised; the stream stays subscribed. + * @returns Unsubscribe; it releases the waiting frame, and a frame being presented stays valid until `present` settles. + * @throws When a mount or stream already owns consumption. + */ + consume(present: (frame: FrameForwardingFrame) => void | Promise, failure: (error: Error) => void): () => void { + this.assertOpen() + if (this.stream !== undefined) { + throw new Error('Native channel already has a frame consumer.') + } + return this.startStream(present, failure) + } + + private startStream(present: FrameStream['present'], failure: FrameStream['failure']): () => void { + const stream: FrameStream = { present, failure } + this.stream = stream + return () => { + if (this.stream !== stream) return + this.stream = undefined + this.streamPending?.release() + this.streamPending = undefined + } + } + + /** + * Display this channel in a video element. + * Producer draining clears the mounted display; a new connection recreates it, including snapshot-only handoffs. + * Individual frame failures reach onEvent without ending the mount. + * Mounted display and continuous consumption are mutually exclusive. + * @param element - The video container. + * @param failure - Receives a failure after mount resources are stopped, including channel closure or loss. + * @returns Idempotent unmount. It releases the display and queues an invisible viewport for the open channel. + */ + mount(element: HTMLElement, failure: (error: Error) => void): () => void { + this.assertOpen() + if (this.stream !== undefined) { + throw new Error('Native channel already has a frame consumer.') + } + if (element.hasAttribute('data-dsh-frame-mount')) throw new Error('Native element already has a frame consumer.') + let display: ElementMount | undefined + const stopStream = this.startStream(frame => display?.present(frame), (error) => { stop(error) }) + const stop = (error?: Error): boolean => { + if (this.mountStop !== stop) return false + this.mountStop = undefined + this.mounted = undefined + this.synchronizeMount = undefined + this.contentView = undefined + this.contentWindow = undefined + this.contentWindows = [] + this.contentRequest = undefined + stopStream() + if (display === undefined) element.removeAttribute('data-dsh-frame-mount') + try { display?.dispose() } catch (cleanupError) { console.error('Frame mount cleanup failed', cleanupError) } + if (error !== undefined) { + try { failure(error) } catch (listenerError) { console.error('Native frame failure listener failed', listenerError) } + } + return true + } + this.mountStop = stop + let draining = this.channel?.state === 'draining' + let mountedConnection = this.connectionId + const synchronize = (): void => { + const connection = this.connectionId + const changed = connection !== undefined && mountedConnection !== undefined && connection !== mountedConnection + if (this.channel?.state === 'draining' || changed) { + draining = this.channel?.state === 'draining' + // Detach synchronously: a hidden document may never run another rAF, and pending video writes hold drain credit. + const previous = display + display = undefined + this.mounted = undefined + this.contentRequest = undefined + previous?.dispose() + // Reserve the element across the producer handoff. + element.setAttribute('data-dsh-frame-mount', 'pending') + } else if (this.channel?.state === 'connected') draining = false + if (connection !== undefined) mountedConnection = connection + if (draining || display !== undefined) return + element.removeAttribute('data-dsh-frame-mount') + display = mountElement(element, { + fullscreen: () => this.fullscreenState, + content: () => this.contentSnapshot(), + viewport: (viewport, completion) => this.mountViewport(viewport, completion), + report: (event) => { this.channelEvent(event) }, failure: (error) => { stop(error) }, + }) + this.mounted = display + } + this.synchronizeMount = () => { + try { synchronize() } catch (error) { stop(errorOf(error)) } + } + try { synchronize() } catch (error) { stop(); throw error } + return () => { + const viewport = this.viewportState + if (!stop()) return + // Disposal may notify a consumer that closes the channel or submits a newer viewport. + if (viewport?.visible && !this.eventsEnded && this.viewportState === viewport) { + void this.automaticViewport({ ...viewport, visible: false }).catch((error: unknown) => { + if (!(error instanceof FrameDiscardedError && (error.reason === 'producer-changed' || error.reason === 'closed'))) { + console.error('Frame unmount viewport failed', error) + } + }) + } + } + } + + /** The document's latest fullscreen state as this channel sees it. */ + get fullscreen(): FrameFullscreenState { return this.fullscreenState } + + /** + * Show `element` fullscreen for this channel; while it is fullscreen, every other receive channel of the document + * reports itself covered. Chromium grants fullscreen only while the document handles a user gesture, so call this + * before the gesture's handler awaits anything. + * @param element - The consumer's view, typically its root element. + * @returns Completion of the entry. Rejects when the channel is closed or failed, when another channel holds + * fullscreen, or when the document refuses fullscreen. + */ + async requestFullscreen(element: Element): Promise { + this.assertOpen() + await this.bridge.requestFullscreen(this.rx, element) + } + + /** + * Leave the fullscreen this channel holds; {@link close} does so too. + * @returns Completion of the exit; resolves at once when this channel holds no fullscreen. + */ + exitFullscreen(): Promise { + return this.bridge.exitFullscreen(this.rx) + } + + /** + * Observe every channel event in arrival order. Subscription first replays the known channel state, latest viewport, + * fullscreen state and latest generation submitted to the video track, in that order. + * Listener exceptions are contained. Local close, Host closure or loss, termination of the Client's channel-event + * stream, and Client disposal deliver one final closed-state or failure event; subscriptions after termination + * receive nothing. Reentrant subscriptions replay after the event currently being delivered. + * @param listener - Receives channel state, frame errors, routing failure, fullscreen and content events. + * @returns Idempotent disposer; removing one subscription does not affect another, even with the same listener. + */ + onEvent(listener: (event: FrameRxEvent) => void): () => void { + return this.subscribeEvents(listener, true) + } + + /** + * Observe changes of {@link fullscreen}: an active state without `holder` means another element covers this + * channel's view, so the consumer sends an invisible viewport until it ends; `holder` with `active: false` means the + * fullscreen this channel held ended, for example on Escape. + * @param listener - Receives each new state; unlike onEvent, this subscription does not replay the current state. + * @returns Disposer for this listener. + */ + onFullscreen(listener: (state: FrameFullscreenState) => void): () => void { + return this.subscribeEvents((event) => { + if (event.kind !== 'fullscreen') return + try { listener({ active: event.active, holder: event.holder }) } catch (error) { + console.error('Native fullscreen listener failed', error) + } + }, false) + } + + /** + * Stop this channel's consumers and frame routing, and leave the fullscreen it holds; the Host plugin that opened + * the channel owns its lifetime. + * @returns Completion after routing stopped and every lent frame's callback settled and its frame was released; + * repeated calls share that completion. + */ + close(): Promise { + if (this.closing === undefined) { + const completion = Promise.withResolvers() + this.closing = completion.promise + void this.closeChannel().then(() => { completion.resolve(undefined) }, completion.reject) + } + return this.closing + } + + private async closeChannel(): Promise { + const notify = !this.eventsEnded + this.eventsEnded = true + const detached = this.detach() + this.mountStop?.(new FrameDiscardedError('closed')) + this.stream = undefined + this.discardPending() + this.rejectReady(new FrameDiscardedError('closed')) + this.end.resolve('closed') + if (notify) { + const channel = { state: 'closed', cause: 'closed', reason: 'Native channel closed.' } as const + this.channel = channel + this.deliverEvent({ kind: 'state', channel }, false, true) + } + await Promise.all([detached, this.streamDrain]) + } + + private async drainStream(): Promise { + if (this.streamDrain !== undefined) return + const completion = Promise.withResolvers() + this.streamDrain = completion.promise + try { + while (this.stream !== undefined && this.streamPending !== undefined) { + const stream = this.stream + const lease = this.streamPending + this.streamPending = undefined + if (!this.acceptsGeneration(lease.metadata.generation)) { lease.release(); continue } + try { + try { await stream.present({ image: lease.frame, metadata: lease.metadata }) } finally { lease.release() } + } catch (error) { this.reportStreamFailure(errorOf(error), stream) } + } + } finally { + this.streamDrain = undefined + completion.resolve() + } + } + + private reportStreamFailure(error: Error, stream = this.stream): void { + try { stream?.failure(error) } catch (listenerError) { console.error('Native frame failure listener failed', listenerError) } + } + + private assertOpen(): void { + if (this.closing !== undefined) throw new FrameDiscardedError('closed') + if (this.failure !== undefined) throw this.failure + } + + /** The connected producer once it acknowledged the latest viewport this channel sent. */ + private readyConnection(): FrameConnectionId | undefined { + const channel = this.channel + if (channel?.state !== 'connected') return undefined + return this.viewportVersion === 0 || channel.viewportVersion === this.viewportVersion ? channel.connectionId : undefined + } + + private subscribeEvents(listener: (event: FrameRxEvent) => void, replay: boolean): () => void { + if (this.eventsEnded) return () => {} + const subscription = (event: FrameRxEvent): void => { listener(event) } + this.eventListeners.add(subscription) + if (replay) this.queueEvents(() => { + const snapshot: FrameRxEvent[] = [ + ...this.channel === undefined ? [] : [{ kind: 'state' as const, channel: this.channel }], + ...this.viewportState === undefined ? [] : [{ kind: 'viewport' as const, viewport: this.viewportState }], + { kind: 'fullscreen', ...this.fullscreenState }, + { kind: 'content', submittedGeneration: this.submittedGeneration }, + ] + for (const event of snapshot) { + if (this.eventsEnded) break + this.notifyEvent(subscription, event) + } + }) + return () => { this.eventListeners.delete(subscription) } + } + + /** Reentrant callbacks append work rather than overtaking another subscriber's current event. */ + private queueEvents(task: () => void): void { + this.eventTasks.push(task) + if (this.deliveringEvents) return + this.deliveringEvents = true + try { + for (let next = this.eventTasks.shift(); next !== undefined; next = this.eventTasks.shift()) next() + } finally { this.deliveringEvents = false } + } + + private notifyEvent(listener: (event: FrameRxEvent) => void, event: FrameRxEvent): void { + if (!this.eventListeners.has(listener)) return + try { listener(event) } catch (error) { console.error('Native channel event listener failed', error) } + } + + private deliverEvent(event: FrameRxEvent, apply: boolean, terminal: boolean): void { + const listeners = [...this.eventListeners] + this.queueEvents(() => { + if (event.kind === 'content' && event.submittedGeneration === this.submittedGeneration) return + if (apply) this.applyEvent(event) + for (const listener of listeners) this.notifyEvent(listener, event) + if (terminal) this.eventListeners.clear() + }) + } + + private channelEvent(event: FrameRxEvent): void { + if (this.eventsEnded) return + const terminal = event.kind === 'failure' || event.kind === 'state' && event.channel.state === 'closed' + if (terminal) this.eventsEnded = true + this.deliverEvent(event, true, terminal) + } + + private applyEvent(event: FrameRxEvent): void { + switch (event.kind) { + case 'state': + this.applyState(event.channel) + return + case 'error': { + // Only failures of the current producer reach its stream. + if (event.connectionId !== this.connectionId) return + // Individual frame failures remain observable through onEvent without ending a mounted display. + if (this.mountStop === undefined) this.reportStreamFailure(new FrameFailureError(event.source, event.error)) + return + } + case 'failure': + this.terminate(new Error(event.error), 'failed') + return + case 'viewport': + this.viewportState = event.viewport + return + case 'content': + this.submittedGeneration = event.submittedGeneration + return + case 'fullscreen': { + const state = { active: event.active, holder: event.holder } + this.fullscreenState = state + this.mounted?.dirty() + return + } + /* v8 ignore next -- The bridge event union is exhausted above. */ + default: return assertNever(event) + } + } + + private applyState(state: FrameChannelState): void { + if (this.closing !== undefined || this.failure !== undefined) return + this.channel = state + if (state.state === 'closed') { + const { cause } = state + this.terminate(cause === 'failed' ? new Error(state.reason) : new FrameDiscardedError(cause), cause) + return + } + this.synchronizeMount?.() + if (state.state !== 'idle') this.knownConnection = Math.max(this.knownConnection, state.connectionId) + // The Host merges an unread `connected` into its successor state, so a connection may first appear as `draining`; + // its frames are released here, or its drain never completes. + for (const lease of this.unconfirmed.splice(0)) this.arrive(lease) + const ready = this.readyConnection() + if (ready === undefined) return + const waiters = [...this.readyWaiters] + this.readyWaiters.clear() + for (const waiter of waiters) waiter.resolve(ready) + } + + /** A Host closure or a renderer-side failure ends routing; the consumer still closes the channel. */ + private terminate(error: Error, cause: FrameChannelCloseCause): void { + this.end.resolve(cause) + this.failure = error + this.discardPending() + this.rejectReady(error) + this.reportStreamFailure(error) + } + + private rejectReady(error: Error): void { + const waiters = [...this.readyWaiters] + this.readyWaiters.clear() + for (const waiter of waiters) waiter.reject(error) + } + + private arrive(lease: FrameForwardingFrameLease): void { + const metadata = lease.metadata + if (this.closing !== undefined || this.failure !== undefined || metadata.rx !== this.rx + || !this.acceptsGeneration(metadata.generation)) { + lease.release() + return + } + if (metadata.connectionId !== this.connectionId) { + // The frame's texture can overtake the state announcing its connection; an older connection's frame is stale. + if (metadata.connectionId > this.knownConnection) this.unconfirmed.push(lease) + else lease.release() + return + } + if (this.stream !== undefined) { + this.streamPending?.release() + this.streamPending = lease + void this.drainStream() + } else lease.release() + } + + private discardPending(preserveContent = false): void { + const keep = (lease: FrameForwardingFrameLease): boolean => preserveContent && this.contentSnapshot() !== undefined + && this.acceptsGeneration(lease.metadata.generation) + if (this.streamPending !== undefined && !keep(this.streamPending)) { + this.streamPending.release() + this.streamPending = undefined + } + for (const lease of this.unconfirmed.splice(0)) { + if (keep(lease)) this.unconfirmed.push(lease) + else lease.release() + } + } +} diff --git a/packages/experimental/frame-forwarding/src/client/service.ts b/packages/experimental/frame-forwarding/src/client/service.ts new file mode 100644 index 0000000000..6414c51d54 --- /dev/null +++ b/packages/experimental/frame-forwarding/src/client/service.ts @@ -0,0 +1,54 @@ +/** Renderer half of frame forwarding: receive channels over `ctx.sharedTexture` and the Host's `frameForwarding` Remote. */ +import type { Context } from '@deepseek-ai/cordis' +import type { SharedTextureClientExport } from '@deepseek-ai/dsh-shared-texture/client' +import type { TypertClientRemote } from '@deepseek-ai/dsh-typert-protocol' +import type {} from '@deepseek-ai/dsh-frame-forwarding/remote' +import type { FrameForwardingEvent, FrameRxId } from '../types.ts' +import { FrameDiscardedError } from './errors.ts' +import { FrameRx } from './rx.ts' +import type { FrameForwardingBridge, FrameForwardingClient } from './api.ts' +import { adaptFrameForwardingBridge } from './wire.ts' + +/** Generated Client methods of the Host frame-forwarding service. */ +export type FrameForwardingRemote = TypertClientRemote['frameForwarding'] + +/** One renderer's subscription to channel events and its adapter over `ctx.sharedTexture`. */ +export class FrameForwardingClientService implements FrameForwardingClient { + private readonly bridge: FrameForwardingBridge + + /** + * Consume shared textures and subscribe to channel states for this renderer until the plugin scope is disposed. + * @param ctx - Client plugin scope with the mounted `frameForwarding` Remote namespace. + * @param textures - Client `ctx.sharedTexture` bridge; throws when another consumer holds it. + */ + constructor(ctx: Context, textures: SharedTextureClientExport) { + const remote = ctx.remote.frameForwarding + const bridge = adaptFrameForwardingBridge(textures, remote, globalThis.document) + ctx.effect(() => () => { bridge.dispose() }) + this.bridge = bridge + const events = ctx.remote.$stream({ + name: 'Frame-forwarding channel events', open: signal => remote.events(signal), + ended: () => new Error('Frame-forwarding channel events ended.'), + }) + // The Remote stream ends with an error only when it can no longer recover; every channel then fails, while the + // service stays provided and `connect` returns channels that fail at once. + void (async () => { + for await (const frame of events) { + frame.accept() + bridge.apply(frame.value) + } + })().catch((error: unknown) => { + ctx.logger.warn(error) + bridge.fail(`Frame-forwarding channel events failed: ${error instanceof Error ? error.message : String(error)}`) + }) + ctx.effect(() => () => events.dispose()) + } + + connect(rx: FrameRxId): FrameRx { + return new FrameRx(rx, this.bridge) + } + + discardReason(error: unknown): FrameDiscardedError['reason'] | undefined { + return error instanceof FrameDiscardedError ? error.reason : undefined + } +} diff --git a/packages/experimental/frame-forwarding/src/client/wire.ts b/packages/experimental/frame-forwarding/src/client/wire.ts new file mode 100644 index 0000000000..067026ec8a --- /dev/null +++ b/packages/experimental/frame-forwarding/src/client/wire.ts @@ -0,0 +1,282 @@ +/** + * Shared-frame routing, channel states, failure containment, and the document's fullscreen holder over the Client + * `sharedTexture` service, the `frameForwarding` Remote, and the document's Fullscreen API. + */ +import type { SharedTextureClientExport, SharedTextureLease } from '@deepseek-ai/dsh-shared-texture/client' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import type { + FrameChannelSnapshot, FrameConnectionId, FrameForwardingFrameMetadata, FrameForwardingViewport, FrameRxId, + FrameViewportResult, +} from '../types.ts' +import type { FrameChannelReceiver, FrameForwardingBridge, FrameRxEvent } from './api.ts' + +/** The `frameForwarding` Remote operation the bridge needs. */ +export interface FrameForwardingRemote { + viewport(rx: FrameRxId, viewport: FrameForwardingViewport): Promise> +} + +function natural(value: unknown): value is number { + return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 +} + +/** Metadata crosses two process boundaries before the renderer reads it; a texture without frame metadata is released. */ +function frameMetadata(value: unknown): FrameForwardingFrameMetadata | undefined { + if (typeof value !== 'object' || value === null) return undefined + const { rx, connectionId, requestId, frameId, generation, revision, width, height } = value as Record + if (typeof rx !== 'string' || rx === '' || !natural(connectionId) || connectionId === 0 || typeof requestId !== 'string' + || !natural(frameId) || !natural(generation) || !natural(revision) || !natural(width) || !natural(height)) { + return undefined + } + return { rx: rx as FrameRxId, connectionId: connectionId as FrameConnectionId, requestId, frameId, generation, revision, width, height } +} + +/** + * A channel that closed while no subscription was open is absent from the next snapshot, without its cause. The + * renderer cannot tell whether Desktop lost it, so it is reported `lost`; asking the owner for a replacement is harmless + * when the owner closed or replaced it. + */ +const vanishedChannel: FrameRxEvent = { + kind: 'state', channel: { state: 'closed', cause: 'lost', reason: 'Native channel closed while the renderer was not subscribed' }, +} + +/** + * Closures kept for channels without a consumer, so that a late consumer still receives them. Between snapshots + * nothing else forgets them, so the oldest beyond this count are dropped, and a later consumer of a dropped channel + * receives no state for it. + */ +const maxUnattachedClosures = 64 + +/** + * A channel's hold on the document's fullscreen, from its first request until fullscreen ends while none of its + * requests is pending, or until its last request settles while none of its elements has been the fullscreen element. + * The document reports only its topmost fullscreen element, so the hold lasts until fullscreen ends once the channel + * has shown an element, also while another element covers it or after the channel left it. + */ +interface FullscreenHolder { + readonly rx: FrameRxId + /** + * Every element the channel requested since it took the document's fullscreen: Chromium keeps an earlier fullscreen + * element below a later one, so an exit can reveal one of them. + */ + readonly elements: Set + /** The channel's requests that have not settled. */ + pending: number + /** Settles once every request the channel made so far does, whether or not the document accepted it. */ + entry: Promise + /** One of the channel's elements became the fullscreen element since the document entered fullscreen. */ + shown: boolean + /** The channel's latest exit; exits run one at a time, because each checks the element on top before leaving it. */ + leaving: Promise +} + +/** + * Adapt the shared-texture bridge and the Host Remote once per Client before connecting receive channels. The bridge + * is the document's texture consumer from creation until `dispose`, also while no channel is open. + * @param textures - The Client `ctx.sharedTexture` bridge; throws when another consumer holds it. + * @param remote - The Host's `frameForwarding` Remote namespace. + * @param document - The product document, whose fullscreen element channels request and observe. + * @returns Channel transport; each delivered lease is released once by the receive channel that holds it. + */ +export function adaptFrameForwardingBridge( + textures: SharedTextureClientExport, remote: FrameForwardingRemote, document: Document, +): FrameForwardingBridge { + const routes = new Map() + /** Latest state per channel, ordered by its arrival; a closed channel leaves once its consumer detaches. */ + let states = new Map() + /** Drop the oldest closures of channels without a consumer beyond {@link maxUnattachedClosures}. */ + const boundClosures = (): void => { + const unattached = [...states.values()].filter(({ rx, channel }) => channel.state === 'closed' && !routes.has(rx)) + for (const { rx } of unattached.slice(0, Math.max(0, unattached.length - maxUnattachedClosures))) states.delete(rx) + } + /** Set once by `fail`, which ends every channel; disposal ends the bridge without it. */ + let failure: Extract | undefined + let disposed = false + /** The channel holding the document's fullscreen. */ + let holder: FullscreenHolder | undefined + const deliver = (lease: SharedTextureLease): void => { + const metadata = frameMetadata(lease.metadata) + const route = metadata === undefined ? undefined : routes.get(metadata.rx) + if (metadata === undefined || route === undefined) { lease.release(); return } + route.onFrame({ frame: lease.frame, metadata, release: () => { lease.release() } }) + } + /** The document changes its fullscreen element on its own, for example on Escape, so every check reads it anew. */ + const fullscreenElement = (): Element | null => document.fullscreenElement + const fullscreenActive = (): boolean => fullscreenElement() !== null + /** The holder counts only while one of its channel's elements is the fullscreen element. */ + const fullscreenHolder = (): FrameRxId | undefined => { + const shown = fullscreenElement() + return holder !== undefined && shown !== null && holder.elements.has(shown) ? holder.rx : undefined + } + /** Record that the document shows the holder's element; the document reports an entry before its event. */ + const noteShown = (): void => { + if (holder !== undefined && fullscreenHolder() === holder.rx) holder.shown = true + } + const fullscreenChanged = (): void => { + const active = fullscreenActive() + noteShown() + // Only a channel whose element was fullscreen held a fullscreen that could end; a pending request held nothing yet. + const owner = active ? fullscreenHolder() : holder?.shown === true ? holder.rx : undefined + if (holder !== undefined && !active) { + holder.shown = false + // A pending request can still enter fullscreen, so its settlement decides whether the hold ends. + if (holder.pending === 0) holder = undefined + } + for (const rx of [...routes.keys()]) routes.get(rx)?.onEvent({ kind: 'fullscreen', active, holder: rx === owner }) + } + /** + * Leave the fullscreen `held` entered once its requests settle, while `owns` still reports its hold, and then each + * element of that channel that the exit reveals. Each exit waits for the hold's previous one and reads the document + * anew: two exits that both saw the channel's element on top would otherwise also leave the element below it. + */ + const leave = (held: FullscreenHolder, owns: () => boolean): Promise => { + const run = async (): Promise => { + // An exit during a pending entry would otherwise let the entry complete afterwards. + await held.entry + for (let remaining = held.elements.size; remaining > 0; remaining--) { + const shown = fullscreenElement() + if (!owns() || shown === null || !held.elements.has(shown)) return + try { + await document.exitFullscreen() + } catch (error) { + // Chromium leaves fullscreen on Escape itself; an exit that lost that race has nothing left to do. + if (fullscreenActive()) throw error + return + } + } + } + // The previous exit's outcome belongs to its caller; this one starts after it either way. + held.leaving = held.leaving.then(run, run) + return held.leaving + } + const exitFullscreen = async (rx: FrameRxId): Promise => { + const held = holder + if (held?.rx === rx) await leave(held, () => holder === held) + } + const endRoutes = (event: Extract): void => { + const active = [...routes.values()] + routes.clear() + for (const route of active) route.onEvent(event) + } + const unsubscribe = textures.onFrame(deliver) + document.addEventListener('fullscreenchange', fullscreenChanged) + const bridge: FrameForwardingBridge = { + async setViewport(rx, viewport) { + if (failure !== undefined) throw new Error(failure.error) + const result = await remote.viewport(rx, viewport) + if (!result.ok) throw new Error(result.error.message) + return result.value + }, + attach(rx, receiver) { + const onEvent = (event: FrameRxEvent): void => { + try { receiver.onEvent(event) } catch (error) { console.error('Native channel listener failed', error) } + } + if (failure !== undefined) { onEvent(failure); return async () => {} } + if (routes.has(rx)) throw new Error('Native channel already has a frame consumer') + let leaving: Promise | undefined + const detach = async (): Promise => { + if (routes.get(rx) === route) { + routes.delete(rx) + // A closed channel publishes no further state, so its closure stays only for the consumer that saw it. + if (states.get(rx)?.channel.state === 'closed') states.delete(rx) + leaving = exitFullscreen(rx).catch((error: unknown) => { console.error('Native channel fullscreen exit failed', error) }) + } + await leaving + } + const route: FrameChannelReceiver = { + onEvent, + onFrame(lease) { + try { receiver.onFrame(lease) } catch (error) { + lease.release() + if (routes.get(rx) !== route) return + void detach() + onEvent({ kind: 'failure', error: error instanceof Error ? error.message : String(error) }) + } + }, + } + routes.set(rx, route) + const known = states.get(rx) + if (known !== undefined) onEvent({ kind: 'state', channel: known.channel }) + if (fullscreenActive()) onEvent({ kind: 'fullscreen', active: true, holder: rx === fullscreenHolder() }) + return detach + }, + apply(event) { + if (failure !== undefined) return + switch (event.kind) { + case 'snapshot': { + const previous = states + states = new Map(event.channels.map(channel => [channel.rx, channel])) + // A channel known before and absent now closed while no subscription was open. + for (const rx of previous.keys()) if (!states.has(rx)) routes.get(rx)?.onEvent(vanishedChannel) + for (const { rx, channel } of event.channels) routes.get(rx)?.onEvent({ kind: 'state', channel }) + boundClosures() + return + } + case 'state': { + const known = states.get(event.rx) + if (known !== undefined && known.sequence >= event.sequence) return + const { rx, sequence, channel } = event + // Reinsertion orders the map by each channel's latest state, so the bound drops the oldest closures first. + states.delete(rx) + states.set(rx, { rx, sequence, channel }) + routes.get(rx)?.onEvent({ kind: 'state', channel }) + if (channel.state === 'closed') boundClosures() + return + } + case 'error': { + const { rx, connectionId, source, requestId, error } = event + routes.get(rx)?.onEvent({ kind: 'error', connectionId, source, ...requestId === undefined ? {} : { requestId }, error }) + return + } + /* v8 ignore next -- The Host stream's closed union is exhausted above. */ + default: return assertNever(event) + } + }, + requestFullscreen(rx, element) { + if (failure !== undefined) return Promise.reject(new Error(failure.error)) + if (holder !== undefined && holder.rx !== rx) return Promise.reject(new Error('Another native channel holds fullscreen.')) + // The holder is known before the document reports the change. + const held = holder ??= { + rx, elements: new Set(), pending: 0, entry: Promise.resolve(), shown: false, leaving: Promise.resolve(), + } + held.elements.add(element) + held.pending += 1 + const entry = element.requestFullscreen() + const settle = (): void => { + held.pending -= 1 + if (holder !== held) return + noteShown() + // A refused request leaves whatever the channel's other requests showed, covered or not; the hold ends once + // none is pending and none of the channel's elements was fullscreen. + if (held.pending === 0 && !held.shown) holder = undefined + } + const settled = entry.then(settle, settle) + // Teardown waits for every request to settle; the returned request promise reports the rejection. + held.entry = held.entry.then(() => settled) + return entry + }, + exitFullscreen, + fail(message) { + if (disposed || failure !== undefined) return + const event = { kind: 'failure', error: message } as const + failure = event + states = new Map() + // Textures arriving later have no consumer, so `deliver` releases them; delivered leases stay with their holders. + endRoutes(event) + const held = holder + holder = undefined + // A failed bridge refuses fullscreen requests, so no later holder replaces the one it leaves. + if (held !== undefined) void leave(held, () => true).catch((error: unknown) => { console.error('Native channel fullscreen exit failed', error) }) + }, + dispose() { + disposed = true + endRoutes({ kind: 'failure', error: 'Frame-forwarding Client disposed.' }) + unsubscribe() + document.removeEventListener('fullscreenchange', fullscreenChanged) + if (holder !== undefined) { + void exitFullscreen(holder.rx).catch((error: unknown) => { console.error('Native channel fullscreen exit failed', error) }) + } + }, + } + return bridge +} diff --git a/packages/experimental/frame-forwarding/src/config.ts b/packages/experimental/frame-forwarding/src/config.ts new file mode 100644 index 0000000000..514fcadb9d --- /dev/null +++ b/packages/experimental/frame-forwarding/src/config.ts @@ -0,0 +1,49 @@ +/** Native receiver limits for the Desktop window. */ +import z from '@deepseek-ai/schemastery' + +/** Validated receiver limits. */ +export const Config = z.object({ + maxFrames: z.natural().min(3).max(16).default(3), + maxBytes: z.union([z.const('auto'), z.natural().min(4096)]).default('auto'), + requestTimeoutMs: z.natural().min(1).max(2_147_483_646).default(10_000), + maxPendingRequests: z.natural().min(1).max(65536).default(128), + maxQueuedEvents: z.natural().min(1).max(4096).default(256), +}) +/** Receiver limits passed to the Host service. */ +export interface Config { + /** Maximum surfaces per channel. Video needs one displayed surface, one in flight and one for the producer to render into. */ + maxFrames: number + /** + * Native surface allocation budget that every channel of the Desktop window shares, including idle pooled surfaces: + * `auto` is half of physical memory and at least 256 MiB. The budget never exceeds physical memory; a larger byte + * count is reduced to it with a Host warning when the first channel opens. A producer whose allocation does not fit + * waits until other channels return surfaces. + */ + maxBytes: 'auto' | number + /** + * Deadline for adapter detection, native frame delivery including each Desktop shared-texture exchange, producer + * handshakes, and producer acknowledgements, in milliseconds. A frame's presentation through Desktop waits at most + * 30000 of them, Desktop's limit. + */ + requestTimeoutMs: number + /** Maximum control requests per producer connection awaiting acknowledgement. */ + maxPendingRequests: number + /** + * Channel events retained for a renderer that has not read them yet. A newer state of a channel replaces its queued + * one; beyond the limit the unread events become one snapshot of every channel's state, including unread closures of + * channels already torn down, and unread frame errors are dropped. + */ + maxQueuedEvents: number +} + +/** + * Resolve the window allocation budget for this machine. + * @param maxBytes - Configured budget. + * @param physicalMemory - Physical memory in bytes. + * @returns The budget in bytes: `auto` is half of physical memory and at least 256 MiB, and no budget exceeds physical + * memory. + */ +export function windowBudget(maxBytes: Config['maxBytes'], physicalMemory: number): number { + const requested = maxBytes === 'auto' ? Math.max(256 * 1024 * 1024, Math.floor(physicalMemory / 2)) : maxBytes + return Math.min(requested, physicalMemory) +} diff --git a/packages/experimental/frame-forwarding/src/host/forwarder.ts b/packages/experimental/frame-forwarding/src/host/forwarder.ts new file mode 100644 index 0000000000..b4f57c85d9 --- /dev/null +++ b/packages/experimental/frame-forwarding/src/host/forwarder.ts @@ -0,0 +1,523 @@ +/** + * Host-side owner of frame-forwarding channels. Each channel's receiver hands accepted frames in native code to the + * native sink of Desktop's shared-texture service; this module attaches that sink and keeps each receiver's + * presentation gate current. + */ +import { randomUUID } from 'node:crypto' +import { brandString } from '@deepseek-ai/dsh-brand' +import type { + FrameForwardingAdapterId, FrameForwardingBindings, FrameForwardingBudget, FrameForwardingReceiver, + FrameForwardingReceiverEvent, +} from './native.ts' +import type { SharedTextureNativeSink, SharedTextureService } from '@deepseek-ai/dsh-shared-texture' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import type { + FrameChannelCloseCause, FrameChannelSnapshot, FrameChannelState, FrameConnectionId, FrameForwardingCapabilities, FrameForwardingEvent, + FrameForwardingViewport, FrameRxId, FrameViewportResult, +} from '../types.ts' +import type { FrameChannel, FrameTx } from './service.ts' +import { parseFrameForwardingViewport } from './validation.ts' + +/** The longest presentation deadline Desktop's native sink accepts. */ +const maxPresentationTimeoutMs = 30_000 + +/** Native receiver limits for the Desktop window. */ +export interface FrameForwardingLimits { + /** Maximum surfaces per channel held at once by the producer's submissions, the Host, Desktop, and the renderer. */ + maxFrames: number + /** + * Window allocation budget including idle pooled surfaces, in bytes. It is read once, when the first channel opens + * after the receiver loads, so a Host whose receiver never loads never sizes it. + */ + maxBytes: () => number + /** + * Deadline for adapter detection, Desktop's sink, frame delivery, producer handshakes, and producer acknowledgements + * in milliseconds; each frame's presentation through Desktop's sink waits at most 30000 of them. + */ + requestTimeoutMs: number + /** Maximum control requests per connection awaiting producer acknowledgement. */ + maxPendingRequests: number +} + +/** Diagnostics and renderer-facing events of the forwarder. */ +export interface FrameForwarderListeners { + /** Receives every channel state and frame error, in publication order. */ + event(event: Exclude): void + /** Receives producer refusals, disconnect reasons, and blocked drains; never a credential. */ + warn(message: string): void +} + +/** The connection that received a control request ended before acknowledging it. */ +class ProducerChangedError extends Error { + constructor() { + super('Native producer changed before acknowledging the request') + this.name = 'ProducerChangedError' + } +} + +interface Pending { + resolve(): void + reject(error: Error): void + timer: ReturnType +} +interface Connection { + readonly id: FrameConnectionId + /** Newest viewport version this connection acknowledged. */ + confirmed: number | undefined + /** Viewport requests sent to this connection and awaiting acknowledgement, by request identifier. */ + readonly pending: Map + ended: boolean +} +interface Channel { + readonly rx: FrameRxId + readonly receiver: FrameForwardingReceiver + state: FrameChannelState + sequence: number + /** The connected or draining connection. */ + connection: Connection | undefined + /** Latest renderer viewport; every new connection receives it before its frames are delivered. */ + viewport: FrameForwardingViewport | undefined + closing: Promise | undefined +} + +function object(value: unknown): Record { + if (typeof value !== 'object' || value === null || Array.isArray(value)) + throw new Error('Invalid frame-forwarding message') + return value as Record +} +function errorOf(error: unknown): Error { + return error instanceof Error ? error : new Error(String(error)) +} +function text(value: unknown, fallback: string): string { + return typeof value === 'string' ? value : fallback +} + +/** Channels, their producer connections, viewports, and the Desktop sink their receivers present frames through. */ +export class FrameForwarder { + private readonly channels = new Map() + /** The window budget and its size, created when the first channel opens. */ + private budget: { readonly native: FrameForwardingBudget; readonly bytes: number } | undefined + private bindings: { native: FrameForwardingBindings } | { error: Error } | undefined + /** The one outstanding `nativeSink` request. */ + private sinkRequest: Promise | undefined + private generation = 0 + private sequence = 0 + private readonly operations = new Set>() + private resetting: Promise | undefined + + /** + * @param sharedTexture - Desktop's shared-texture service; its native sink receives every frame from the receiver + * addon, and its `adapterLuid` identifies Chromium's adapter on Windows. + * @param loadBindings - Load the receiver addon; called at most once, on the first native operation. + * @param limits - Receiver limits. + * @param listeners - Channel events for the renderer and diagnostics for the Host log. + */ + constructor( + private readonly sharedTexture: SharedTextureService, + private readonly loadBindings: () => FrameForwardingBindings, + private readonly limits: FrameForwardingLimits, + private readonly listeners: FrameForwarderListeners, + ) {} + + private async track(operation: Promise): Promise { + this.operations.add(operation) + try { + return await operation + } finally { + this.operations.delete(operation) + } + } + + /** A packaged build verifies the addon; a development build without a C++ toolchain reports the receiver unavailable. */ + private loaded(): { native: FrameForwardingBindings } | { error: Error } { + if (this.bindings === undefined) { + try { this.bindings = { native: this.loadBindings() } } catch (error) { this.bindings = { error: errorOf(error) } } + } + return this.bindings + } + + /** + * Probe native frame support. + * @returns Whether Desktop presents textures on this platform and the receiver addon loads. + */ + async capabilities(): Promise { + if (process.platform !== 'darwin' && process.platform !== 'win32') return { supported: false, reason: 'unsupported-platform' } + const bindings = this.loaded() + if ('error' in bindings) return { supported: false, reason: `receiver-unavailable: ${bindings.error.message}` } + const desktop = await this.sharedTexture.capabilities(this.limits.requestTimeoutMs) + if (!desktop.supported) return { supported: false, reason: desktop.reason ?? 'desktop-shared-texture-unavailable' } + return { supported: true } + } + + /** + * Open a channel with its own receiver under the window budget, attached to Desktop's native sink. + * @returns The producer credential and the receive identity; rejects when Desktop provides no native sink. + */ + channel(): Promise { + if (this.resetting !== undefined) return Promise.reject(new Error('Native channels are closing')) + return this.track(this.openChannel()) + } + + private async openChannel(): Promise { + const generation = this.generation + const { maxFrames, requestTimeoutMs } = this.limits + const bindings = this.loaded() + if ('error' in bindings) throw new Error(`Frame-forwarding receiver is unavailable: ${bindings.error.message}`) + const addon = bindings.native + // Software compositing can begin at any time, so every channel asks Desktop before relying on cached state. + const desktop = await this.sharedTexture.capabilities(this.limits.requestTimeoutMs) + if (!desktop.supported) throw new Error(`Desktop shared textures are unavailable: ${desktop.reason ?? 'unsupported'}`) + const unavailable = (error: unknown): Error => + new Error(`Desktop native frame submission is unavailable: ${errorOf(error).message}`, { cause: error }) + // The sink and the Windows adapter both precede the receiver, so their failures leave nothing to discard. + let sink: SharedTextureNativeSink + try { + sink = await this.nativeSink() + } catch (error) { + throw unavailable(error) + } + const displayAdapter = await this.displayAdapter() + if (generation !== this.generation) throw new Error('Native channel creation cancelled') + if (this.budget === undefined) { + const bytes = this.limits.maxBytes() + this.budget = { native: addon.createBudget(bytes), bytes } + } + const rx = brandString(randomUUID()) + const receiver = addon.createReceiver({ + maxFrames, maxBytes: this.budget.bytes, budget: this.budget.native, displayAdapter, readbackTimeoutMs: requestTimeoutMs, + }, (event) => { + const channel = this.channels.get(rx) + if (channel !== undefined) this.receive(channel, event) + else if (event.type === 'frame') receiver.release(event.deliveryId) + }) + try { + receiver.attachSink(rx, sink, this.presentationTimeoutMs()) + } catch (error) { + // No producer holds the credential before it is returned, so the discarded receiver has no frames to drain. + try { + await receiver.close() + } catch (closeError) { + console.error('Native receiver teardown failed', closeError) + } + throw unavailable(error) + } + const channel: Channel = { + rx, receiver, state: { state: 'idle' }, sequence: 0, connection: undefined, viewport: undefined, closing: undefined, + } + this.channels.set(rx, channel) + this.publish(channel, { state: 'idle' }) + return { tx: brandString(receiver.tx), rx } + } + + /** + * Desktop's native sink of its current connection. Desktop's service keeps that connection and replaces it after a + * disconnect, so every channel asks it; requests made while one is outstanding share that one. + */ + private nativeSink(): Promise { + return this.sinkRequest ??= this.sharedTexture.nativeSink(this.limits.requestTimeoutMs) + .finally(() => { this.sinkRequest = undefined }) + } + + /** Deadline of each presentation through Desktop's sink: the request deadline, up to the sink's limit. */ + private presentationTimeoutMs(): number { + return Math.min(this.limits.requestTimeoutMs, maxPresentationTimeoutMs) + } + + /** + * A receiver delivered a frame to JavaScript, so it has no usable sink: request Desktop's current one unless a + * request is outstanding, and attach it to every open channel. A failure is reported; the next such frame requests + * again. + */ + private refreshSink(): void { + if (this.sinkRequest !== undefined || this.resetting !== undefined) return + void this.track(this.nativeSink().then((sink) => { + for (const channel of this.channels.values()) { + if (channel.closing !== undefined) continue + try { + channel.receiver.attachSink(channel.rx, sink, this.presentationTimeoutMs()) + } catch (error) { + this.warn(`Native channel could not attach Desktop's sink: ${errorOf(error).message}`) + } + } + }, (error: unknown) => { + this.warn(`Desktop native frame submission is unavailable: ${errorOf(error).message}`) + })) + } + + /** + * Chromium's compositor adapter, null on macOS. Every Windows channel asks Desktop, whose answer follows the GPU + * process across restarts; the LUID is spelled as the receiver names adapters. + */ + private async displayAdapter(): Promise { + if (process.platform !== 'win32') return null + const luid = await this.sharedTexture.adapterLuid(this.limits.requestTimeoutMs) + if (luid === null) throw new Error('Desktop shared textures are unavailable: Electron graphics adapter could not be identified') + return luid as FrameForwardingAdapterId + } + + /** + * Report whether a channel still serves producers and its renderer. + * @param rx - Channel identity. + * @returns Whether the channel exists and is not closing. + */ + isOpen(rx: FrameRxId): boolean { + const channel = this.channels.get(rx) + return channel !== undefined && channel.closing === undefined + } + + /** + * Read every channel's latest published state, including channels still closing. + * @returns One entry per channel, for a new renderer subscription. + */ + snapshot(): FrameChannelSnapshot[] { + return [...this.channels.values()].map(({ rx, sequence, state }) => ({ rx, sequence, channel: state })) + } + + /** + * Keep a renderer viewport for the channel and apply it to the current connection. + * @param rx - Open channel. + * @param value - Untrusted viewport from the renderer, validated here. + * @returns The retained version for a stale submission, or the outcome of delivering a newer one. Producer refusal + * and acknowledgement timeout reject the request and leave the channel open. + */ + async setViewport(rx: FrameRxId, value: unknown): Promise { + const channel = this.open(rx) + const viewport = parseFrameForwardingViewport(value) + if (channel.viewport !== undefined && viewport.version <= channel.viewport.version) + return { applied: false, reason: 'stale-viewport', currentVersion: channel.viewport.version } + channel.viewport = viewport + this.updateDeliverable(channel) + const connection = channel.connection + if (connection === undefined || connection.ended) return { applied: false, reason: 'no-producer' } + try { + await this.track(this.applyViewport(channel, connection, viewport)) + } catch (error) { + if (error instanceof ProducerChangedError) return { applied: false, reason: 'producer-changed' } + throw error + } + return { applied: true, connectionId: connection.id } + } + + private open(rx: FrameRxId): Channel { + const channel = this.channels.get(rx) + if (channel === undefined || channel.closing !== undefined) throw new Error('Native channel is closed') + return channel + } + + private publish(channel: Channel, state: FrameChannelState): void { + channel.state = state + channel.sequence = ++this.sequence + this.notify({ kind: 'state', rx: channel.rx, sequence: channel.sequence, channel: state }) + } + + private notify(event: Exclude): void { + try { this.listeners.event(event) } catch (error) { console.error('Native channel event listener failed', error) } + } + + private warn(message: string): void { + try { this.listeners.warn(message) } catch (error) { console.error('Native channel warning listener failed', error) } + } + + /** Publish the current connection's state; a closing channel has already ended its connection. */ + private publishConnected(channel: Channel, connection: Connection): void { + const { id, confirmed } = connection + this.publish(channel, { state: 'connected', connectionId: id, ...confirmed === undefined ? {} : { viewportVersion: confirmed } }) + } + + /** Send one viewport to a connection; the request is bound to that connection and fails when it ends. */ + private applyViewport(channel: Channel, connection: Connection, viewport: FrameForwardingViewport): Promise { + if (connection.pending.size >= this.limits.maxPendingRequests) return Promise.reject(new Error('Native control queue is full')) + const requestId = randomUUID() + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + connection.pending.delete(requestId) + reject(new Error('Native producer acknowledgement timed out')) + }, this.limits.requestTimeoutMs) + connection.pending.set(requestId, { resolve, reject, timer }) + try { + channel.receiver.send(connection.id, JSON.stringify({ type: 'viewport', viewport, requestId })) + } catch { + // The addon refuses sends once the connection ended, before its disconnect event reaches this thread. + clearTimeout(timer) + connection.pending.delete(requestId) + reject(new ProducerChangedError()) + } + }) + } + + private settle(connection: Connection, requestId: unknown, error?: Error): void { + if (typeof requestId !== 'string') return + const pending = connection.pending.get(requestId) + if (pending === undefined) return + connection.pending.delete(requestId) + clearTimeout(pending.timer) + if (error === undefined) pending.resolve() + else pending.reject(error) + } + + private end(connection: Connection, error: () => Error): void { + connection.ended = true + for (const pending of connection.pending.values()) { + clearTimeout(pending.timer) + pending.reject(error()) + } + connection.pending.clear() + } + + private receive(channel: Channel, event: FrameForwardingReceiverEvent): void { + switch (event.type) { + case 'connected': { + if (channel.closing !== undefined) return + const connection: Connection = { id: event.connectionId, confirmed: undefined, pending: new Map(), ended: false } + channel.connection = connection + this.updateDeliverable(channel) + this.publishConnected(channel, connection) + const viewport = channel.viewport + if (viewport !== undefined) { + void this.track(this.applyViewport(channel, connection, viewport)).catch((error: unknown) => { + if (!(error instanceof ProducerChangedError)) this.warn(`Native viewport replay failed: ${errorOf(error).message}`) + }) + } + return + } + case 'message': + this.message(channel, event.connectionId, event.text) + return + case 'frame': + // A frame reaches JavaScript only while its receiver has no usable Desktop sink. + channel.receiver.release(event.deliveryId) + this.refreshSink() + return + case 'presentation-error': + this.notify({ + kind: 'error', rx: channel.rx, connectionId: event.connectionId, source: event.source, + ...event.requestId === undefined ? {} : { requestId: event.requestId }, error: event.text, + }) + return + case 'presentation-invalidated': + this.invalidate(channel) + return + case 'disconnected': { + const connection = channel.connection + if (connection?.id !== event.connectionId) return + this.end(connection, () => new ProducerChangedError()) + this.updateDeliverable(channel) + if (event.text !== undefined) this.warn(`Native producer ${String(event.connectionId)} disconnected: ${event.text}`) + if (channel.closing === undefined) this.publish(channel, { state: 'draining', connectionId: event.connectionId }) + return + } + case 'drained': + if (channel.connection?.id !== event.connectionId) return + channel.connection = undefined + this.updateDeliverable(channel) + if (channel.closing === undefined) this.publish(channel, { state: 'idle' }) + return + case 'drain-blocked': + this.warn(`Native producer ${String(event.connectionId)} drain is blocked: ${event.text}`) + if (channel.connection?.id === event.connectionId && channel.closing === undefined) + this.publish(channel, { state: 'draining', connectionId: event.connectionId, blocked: event.text }) + return + case 'rejected': + this.warn(`Native producer refused: ${event.text}`) + return + case 'failed': + void this.closeChannel(channel, 'failed', `Native channel failed: ${event.text}`).catch((error: unknown) => { + console.error('Native receiver teardown failed', error) + }) + return + /* v8 ignore next -- The addon event union is exhausted above. */ + default: return assertNever(event) + } + } + + /** Control messages only affect the connection that sent them while it is current. */ + private message(channel: Channel, connectionId: FrameConnectionId, json: string): void { + const connection = channel.connection + if (connection?.id !== connectionId || connection.ended) return + let message: Record + try { + message = object(JSON.parse(json)) + } catch { + this.notify({ kind: 'error', rx: channel.rx, connectionId, source: 'producer', error: 'Native producer sent an invalid control message' }) + return + } + switch (message.type) { + case 'viewport-applied': { + const version = message.version + if (typeof version === 'number' && Number.isSafeInteger(version) && version > (connection.confirmed ?? -1)) { + connection.confirmed = version + this.publishConnected(channel, connection) + } + this.settle(connection, message.requestId) + return + } + case 'viewport-rejected': + this.settle(connection, message.requestId, new Error(text(message.error, 'Native producer rejected viewport'))) + return + case 'error': + this.notify({ kind: 'error', rx: channel.rx, connectionId, source: 'producer', error: text(message.message, 'Native producer failed') }) + return + default: + // Input acknowledgements and other application messages carry no channel state. + } + } + + /** + * Push the receiver's presentation gate: frames of the current, unended connection while the latest viewport is + * visible, up to that viewport's version. The gate moves before the viewport is sent, so it admits a frame of the + * new generation even when that frame reaches the receiver before JavaScript handles the acknowledgement. Earlier + * generations pass because frames still in flight can follow a newer viewport; Desktop Main and the receive channel + * release generations outside their render windows. + */ + private updateDeliverable(channel: Channel): void { + const { connection, viewport } = channel + channel.receiver.setDeliverable(channel.closing === undefined && connection !== undefined && !connection.ended + && viewport !== undefined + ? { connectionId: connection.id, visible: viewport.visible, maxGeneration: viewport.version } + : null) + } + + private invalidate(channel: Channel): void { + void this.closeChannel(channel, 'lost', 'Desktop invalidated a presented frame').catch((error: unknown) => { + console.error('Native receiver teardown failed', error) + }) + } + + /** The receiver stops before the first await, so a frame released after this call returns no credit. */ + private async closeChannel(channel: Channel, cause: FrameChannelCloseCause, reason: string): Promise { + if (channel.closing !== undefined) return channel.closing + channel.receiver.setDeliverable(null) + const closing = channel.receiver.close() + channel.closing = closing + if (channel.connection !== undefined) this.end(channel.connection, () => new Error('Native channel closed')) + this.publish(channel, { state: 'closed', cause, reason }) + try { + await closing + } finally { + this.channels.delete(channel.rx) + } + } + + /** + * Close a channel permanently. + * @param rx - Owned channel; an unknown channel is already closed. + * @returns Completion of native resource and connection teardown. + */ + close(rx: FrameRxId): Promise { + const channel = this.channels.get(rx) + return channel === undefined ? Promise.resolve() : this.closeChannel(channel, 'closed', 'Native channel closed') + } + + /** Close every channel; presented textures stay owned by the renderer until Desktop settles them. + * @returns Completion of native I/O teardown. + */ + closeAll(): Promise { + return this.resetting ??= (async () => { + this.generation++ + const closures = await Promise.allSettled([...this.channels.keys()].map(rx => this.close(rx))) + await Promise.allSettled([...this.operations]) + const failures = closures.filter(result => result.status === 'rejected').map((result): unknown => result.reason) + if (failures.length > 0) throw new AggregateError(failures, 'Native receiver cleanup failed') + })().finally(() => { this.resetting = undefined }) + } +} diff --git a/packages/experimental/frame-forwarding/src/host/native.ts b/packages/experimental/frame-forwarding/src/host/native.ts new file mode 100644 index 0000000000..3a20895486 --- /dev/null +++ b/packages/experimental/frame-forwarding/src/host/native.ts @@ -0,0 +1,208 @@ +/** Host binding to the frame-forwarding receiver addon shipped with Desktop. */ +import { readFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { isAbsolute } from 'node:path' +import type { FrameConnectionId } from '../types.ts' + +/** + * Wire protocol version the receiver accepts; it equals `DSH_FRAME_FORWARDING_PROTOCOL_VERSION` + * in the receiver transport header, which the build records beside the addon. Protocol 2 sends each packet as + * a fixed header followed by only the bytes of its text; protocol 1 sent every packet at its full fixed size. + */ +export const FRAME_FORWARDING_PROTOCOL_VERSION = 2 + +/** + * Handshake capabilities the receiver requires of producers, as declared in the addon build record; a + * protocol 1 addon built before transferable channels records none and does not load. + */ +export const FRAME_FORWARDING_CAPABILITIES: readonly string[] = ['transferable-tx', 'producer-local-handles'] + +/** Adapter identity valid for the current OS GPU devices. */ +export type FrameForwardingAdapterId = string & { readonly __frameForwardingAdapterId: unique symbol } +/** Receiver-owned delivery identity; independent of reusable producer frame IDs. */ +export type FrameForwardingDeliveryId = number & { readonly __frameForwardingDeliveryId: unique symbol } + +/** Receiver notifications, delivered on the JavaScript thread; each connection event names its connection. */ +export type FrameForwardingReceiverEvent = + /** A producer holding the credential received ready; its frames follow. */ + | { type: 'connected'; connectionId: FrameConnectionId; pid: number } + | { + type: 'frame' + connectionId: FrameConnectionId + frameId: number + deliveryId: FrameForwardingDeliveryId + width: number + height: number + stride: number + metadata: string + adapterId: FrameForwardingAdapterId + transport: 'shared-texture' + /** Host-local `IOSurfaceRef` or NT handle, retained by the receiver until `release`. */ + handle: Buffer + /** Source descriptor declares key-0 synchronization; false on macOS. */ + sourceKeyedMutex: boolean + /** Windows adapter owning the output texture; null for macOS IOSurface. */ + presentationAdapterId: FrameForwardingAdapterId | null + } + | { type: 'message'; connectionId: FrameConnectionId; text: string } + /** + * The receiver could not present a frame through the attached Desktop sink: `producer` for invalid frame metadata, + * `presentation` when Desktop refused or failed to deliver it. `requestId` names the frame's request when known. + */ + | { + type: 'presentation-error' + connectionId: FrameConnectionId + source: 'producer' | 'presentation' + requestId?: string + text: string + } + /** Desktop invalidated a frame presented through the attached sink; the receiver is stopping. */ + | { type: 'presentation-invalidated'; connectionId: FrameConnectionId; text?: string } + /** The producer left or failed; `text` is absent after its goodbye. Delivered frames stay valid while the connection drains. */ + | { type: 'disconnected'; connectionId: FrameConnectionId; text?: string } + /** Every frame and resource of the connection was released; a waiting successor connects next. */ + | { type: 'drained'; connectionId: FrameConnectionId } + /** GPU completion is unknown, so the connection keeps its resources and budget and its drain waits. */ + | { type: 'drain-blocked'; connectionId: FrameConnectionId; text: string } + /** + * A candidate was refused: channel-busy, transferable-tx-required, producer-local-handles-required, invalid-credential, + * channel-closed, or a setup failure. + */ + | { type: 'rejected'; text: string } + /** The channel stopped accepting producers. */ + | { type: 'failed'; text: string } + +/** + * One channel's receiver; delivered frames stay retained until `release`. While a Desktop sink is attached, the + * receiver presents each frame through it in native code and releases it when Desktop settles the texture, so only + * frames that arrive without an attached sink reach `onEvent`. + */ +export interface FrameForwardingReceiver { + /** Producer credential; any process holding a copy may connect. */ + readonly tx: string + /** Send JSON to one connection; throws unless it is the connected one, or when larger than 16383 UTF-8 bytes. */ + send(connectionId: FrameConnectionId, json: string): void + /** Release after Desktop settled the texture; credit returns only to the frame's own connection. A duplicate release returns false. */ + release(deliveryId: FrameForwardingDeliveryId): boolean + /** + * Present later frames through a Desktop shared-texture sink, replacing an attached one. The receiver detaches the + * sink when it loses its connection, so later frames reach `onEvent` until a sink is attached again; a frame Desktop + * refuses leaves the sink attached. + * @param rx - Channel identity of 1 to 128 printable ASCII characters, carried in each frame's metadata. + * @param sink - The sink external Desktop's `nativeSink` returned; throws for another value or ABI version. + * @param timeoutMs - Delivery deadline of each presentation, 1 to 30 000 ms. + */ + attachSink(rx: string, sink: unknown, timeoutMs: number): void + /** + * Set which frames the attached sink presents: frames of `connectionId` whose generation is at most + * `maxGeneration` while `visible`. Other frames, and every frame while the state is null, are released unpresented. + * @param state - The presentation gate, or null to present nothing. + */ + setDeliverable(state: { connectionId: FrameConnectionId; visible: boolean; maxGeneration: number } | null): void + /** + * Stop accepting producers and end the current connection at once, then await GPU completion or confirmed device + * removal and worker exit. Delivered frames remain owned until released; a stalled driver can leave this promise pending. + */ + close(): Promise +} + +/** Allocation budget shared by every receiver of one window, including producer idle surface pools. */ +export interface FrameForwardingBudget { readonly __frameForwardingBudget: unique symbol } + +/** Receiver options for one channel. */ +export interface FrameForwardingReceiverOptions { + maxFrames: number + maxBytes: number + budget: FrameForwardingBudget + /** Electron's display adapter for Windows shared textures; null on macOS. */ + displayAdapter: FrameForwardingAdapterId | null + /** Queued GPU readback and upload deadline, also bounding a connecting producer's handshake; expiry ends the connection. */ + readbackTimeoutMs: number +} + +/** Receiver operations of the loaded addon. */ +export interface FrameForwardingBindings { + createBudget(maxBytes: number): FrameForwardingBudget + createReceiver(options: FrameForwardingReceiverOptions, onEvent: (event: FrameForwardingReceiverEvent) => void): FrameForwardingReceiver +} + +/** Events as the addon dispatches them: `presentation-error` carries its fields as JSON `text`. */ +type AddonEvent = + | Exclude + | { type: 'presentation-error'; connectionId: FrameConnectionId; text: string } + +interface Addon { + createBudget(maxBytes: number): object + create(maxFrames: number, maxBytes: number, onEvent: (event: AddonEvent) => void, budget: object, + displayAdapter: string, readbackTimeoutMs: number): { native: object; tx: string } + send(native: object, connectionId: number, json: string): void + release(native: object, deliveryId: number): boolean + attachSink(native: object, rx: string, sink: unknown, timeoutMs: number): void + setDeliverable(native: object, state: { connectionId: number; visible: boolean; maxGeneration: number } | null): void + close(native: object): Promise +} + +/** Read `{ source, requestId?, error }` from the addon's event text; other text is a presentation failure. */ +function presentationError( + { connectionId, text }: Extract, +): Extract { + let fields: unknown + try { + fields = JSON.parse(text) + } catch { + return { type: 'presentation-error', connectionId, source: 'presentation', text } + } + if (typeof fields !== 'object' || fields === null || !('source' in fields) || !('error' in fields) + || (fields.source !== 'producer' && fields.source !== 'presentation') || typeof fields.error !== 'string') { + return { type: 'presentation-error', connectionId, source: 'presentation', text } + } + const requestId = 'requestId' in fields && typeof fields.requestId === 'string' ? { requestId: fields.requestId } : {} + return { type: 'presentation-error', connectionId, source: fields.source, ...requestId, text: fields.error } +} + +function recordCapabilities(record: object): readonly unknown[] | undefined { + return 'capabilities' in record && Array.isArray(record.capabilities) ? record.capabilities : undefined +} + +/** + * Load the receiver addon after checking the build record beside it. + * @param path - Desktop-owned addon file; its record has the same name with a `.json` extension. + * @returns Receiver operations; throws when the addon or its record is absent, or the record names another platform, + * protocol version, or set of handshake capabilities. + */ +export function loadFrameForwardingBindings(path: string): FrameForwardingBindings { + if (!isAbsolute(path)) throw new Error('Desktop frame receiver path must be absolute') + const record: unknown = JSON.parse(readFileSync(path.replace(/\.[^./\\]+$/u, '.json'), 'utf8')) + const platform = `${process.platform}-${process.arch}` + const capabilities = typeof record === 'object' && record !== null ? recordCapabilities(record) : undefined + if (typeof record !== 'object' || record === null || !('platform' in record) || record.platform !== platform + || !('protocolVersion' in record) || record.protocolVersion !== FRAME_FORWARDING_PROTOCOL_VERSION + || capabilities === undefined || JSON.stringify(capabilities) !== JSON.stringify(FRAME_FORWARDING_CAPABILITIES)) { + throw new Error(`Frame-forwarding receiver at ${path} was not built for ${platform} at protocol version ${String(FRAME_FORWARDING_PROTOCOL_VERSION)} with ${FRAME_FORWARDING_CAPABILITIES.join(', ')}; install a compatible Desktop build`) + } + const addon = createRequire(import.meta.url)(path) as Addon + const budgets = new WeakMap() + return { + createBudget(maxBytes) { + const budget = Object.freeze({}) as FrameForwardingBudget + budgets.set(budget, addon.createBudget(maxBytes)) + return budget + }, + createReceiver({ maxFrames, maxBytes, budget, displayAdapter, readbackTimeoutMs }, onEvent) { + const allocation = budgets.get(budget) + if (allocation === undefined) throw new TypeError('Receiver requires a budget from createBudget()') + const { native, tx } = addon.create(maxFrames, maxBytes, (event) => { + onEvent(event.type === 'presentation-error' ? presentationError(event) : event) + }, allocation, displayAdapter ?? '', readbackTimeoutMs) + let closed: Promise | undefined + return { + tx, + send(connectionId, json) { addon.send(native, connectionId, json) }, + release(deliveryId) { return addon.release(native, deliveryId) }, + attachSink(rx, sink, timeoutMs) { addon.attachSink(native, rx, sink, timeoutMs) }, + setDeliverable(state) { addon.setDeliverable(native, state) }, + close() { return closed ??= addon.close(native) }, + } + }, + } +} diff --git a/packages/experimental/frame-forwarding/src/host/service.ts b/packages/experimental/frame-forwarding/src/host/service.ts new file mode 100644 index 0000000000..147e39a0c6 --- /dev/null +++ b/packages/experimental/frame-forwarding/src/host/service.ts @@ -0,0 +1,56 @@ +/** The `frameForwarding` Host service operations, its Host-only channel values, and their Cordis Context declaration. */ +import type { Branded } from '@deepseek-ai/dsh-brand' +import type { FrameForwardingCapabilities, FrameRxId } from '../types.ts' + +/** + * Opaque, serializable credential that lets any process holding a copy connect a producer to one channel. It stays + * in the Host and its producers: never send it to a renderer, log it, or put it in diagnostics. + */ +export type FrameTx = Branded<'FrameTx'> + +/** One channel: the producer credential and the receive identity the renderer connects to. */ +export interface FrameChannel { + readonly tx: FrameTx + readonly rx: FrameRxId +} + +/** + * Operations a Host plugin uses to render through channels; present while frame forwarding is loaded, so read it with + * `ctx.get('frameForwarding')` and probe {@link FrameForwardingService.capabilities} before opening a channel. + */ +export interface FrameForwardingService { + /** + * Probe native frame support. Support ends when Desktop stops compositing on the GPU, for example after repeated GPU + * process crashes, so probe again before opening a channel that replaces a `lost` one. + * @returns Whether this Host can present native frames now; a diagnostic reason accompanies `false`. + */ + capabilities(): Promise + /** + * Open a channel. It serves one producer connection at a time: a producer started with `tx` connects, a second one + * is refused as `channel-busy`, and after a producer disconnects or exits its frames drain before the next one + * connects with the same credential. The channel keeps the renderer's latest viewport and applies it to each new + * connection before delivering its frames. + * @returns The producer credential and the receive identity for the renderer. + */ + channel(): Promise + /** + * Report whether a channel still serves producers and its renderer. + * @param rx - Owned channel. + * @returns False once {@link close}, a listener failure, or Desktop losing one of its presented frames closed it. + */ + isOpen(rx: FrameRxId): boolean + /** + * Close a channel permanently: its credential stops connecting, the current connection ends, and the renderer sees + * the channel closed. An unknown channel is already closed. + * @param rx - Owned channel. + * @returns Completion of native resource and connection teardown; presented frames stay owned until Desktop settles them. + */ + close(rx: FrameRxId): Promise +} + +declare module '@deepseek-ai/cordis' { + interface Context { + /** Native frame forwarding; absent unless it is loaded, and unsupported in a Host that cannot present frames. */ + frameForwarding: FrameForwardingService + } +} diff --git a/packages/experimental/frame-forwarding/src/host/validation.ts b/packages/experimental/frame-forwarding/src/host/validation.ts new file mode 100644 index 0000000000..13211c67e2 --- /dev/null +++ b/packages/experimental/frame-forwarding/src/host/validation.ts @@ -0,0 +1,23 @@ +/** Validation of renderer viewports that enter the Host over Remote. */ +import { z } from 'zod' +import type { FrameForwardingViewport } from '../types.ts' + +const natural = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER) +const positive = natural.min(1) + +const viewport = z.object({ + version: natural, + width: positive.max(16384), + height: positive.max(16384), + deviceScaleFactor: z.number().positive().max(16), + visible: z.boolean(), +}) + +/** + * Parse a viewport received over Remote; size is bounded before native allocation. + * @param value - Renderer-supplied value. + * @returns Validated physical dimensions and display state. + */ +export function parseFrameForwardingViewport(value: unknown): FrameForwardingViewport { + return viewport.parse(value) +} diff --git a/packages/experimental/frame-forwarding/src/index.ts b/packages/experimental/frame-forwarding/src/index.ts new file mode 100644 index 0000000000..b99901ccf9 --- /dev/null +++ b/packages/experimental/frame-forwarding/src/index.ts @@ -0,0 +1,241 @@ +/** + * Native frame forwarding for Host plugins: channels whose producers present frames in the Desktop renderer through + * Desktop's shared-texture service. Consumers open channels and hand their credentials to producers through the + * `frameForwarding` service; the renderer applies viewports and follows channel states through the `frameForwarding` + * Remote namespace. + */ +import { totalmem } from 'node:os' +import { type Context } from '@deepseek-ai/cordis' +import type { SharedTextureClaim } from '@deepseek-ai/dsh-shared-texture' +import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import { Config, windowBudget } from './config.ts' +import { loadFrameForwardingBindings } from './host/native.ts' +import { FrameForwarder } from './host/forwarder.ts' +import type { FrameChannel, FrameForwardingService } from './host/service.ts' +import type { + FrameChannelSnapshot, FrameForwardingCapabilities, FrameForwardingEvent, FrameForwardingViewport, FrameRxId, + FrameViewportResult, +} from './types.ts' + +export type * from './types.ts' +export type { Config } from './config.ts' +export type { FrameChannel, FrameForwardingService, FrameTx } from './host/service.ts' + +/** + * Merge the closures the unread events still carry for channels absent from the forwarder's snapshot. Only the newest + * `maxClosed` of them are kept, so an unread queue never grows the snapshot without bound; the renderer reports an + * older closure it knew of as vanished. + * @param unread - Queued events, including earlier snapshots. + * @param channels - The forwarder's current channels, all of which are kept. + * @param maxClosed - Maximum closures of forgotten channels to keep. + * @returns The snapshot entries, one per channel: the current channels, then the kept closures in publication order. + */ +function compact(unread: readonly FrameForwardingEvent[], channels: FrameChannelSnapshot[], maxClosed: number): FrameChannelSnapshot[] { + const current = new Set(channels.map(entry => entry.rx)) + const closures = new Map() + for (const event of unread) { + const entries = event.kind === 'snapshot' ? event.channels + : event.kind === 'state' ? [{ rx: event.rx, sequence: event.sequence, channel: event.channel }] : [] + for (const entry of entries) { + if (entry.channel.state !== 'closed' || current.has(entry.rx)) continue + const known = closures.get(entry.rx) + if (known === undefined || known.sequence < entry.sequence) closures.set(entry.rx, entry) + } + } + const forgotten = [...closures.values()].sort((a, b) => a.sequence - b.sequence) + return [...channels, ...forgotten.slice(Math.max(0, forgotten.length - maxClosed))] +} + +/** Channels for every consumer of this Host, plus the Remote the renderer uses to drive them. */ +export default class FrameForwarding extends TypertRemoteService implements FrameForwardingService { + static Config = Config + + /** The forwarder over the claimed Desktop shared textures; absent while frame forwarding holds no claim. */ + private forwarder: FrameForwarder | undefined + /** Why no forwarder exists: Desktop provides no shared textures, or another consumer holds their claim. */ + private unavailable: 'desktop-shared-texture-unavailable' | 'desktop-shared-texture-claimed' = 'desktop-shared-texture-unavailable' + /** Disposers of the effects that bind each open channel to the scope that opened it. */ + private readonly owners = new Map void | Promise>() + private subscriber: { + readonly events: FrameForwardingEvent[] + wake: (() => void) | undefined + ended: boolean + } | undefined + + /** + * @param ctx - Host scope; Desktop's `sharedTexture` service is claimed whenever it is provided. + * @param config - Receiver limits. + */ + constructor(ctx: Context, readonly config: Config) { + super(ctx, 'frameForwarding') + // Physical memory is read only when a forwarder opens its first channel, so a Host that never loads the receiver, + // such as the browser worker deployment, never reads it. A budget above physical memory is reduced with a warning. + const maxBytes = (): number => { + const physicalMemory = totalmem() + const bytes = windowBudget(config.maxBytes, physicalMemory) + if (config.maxBytes !== 'auto' && bytes < config.maxBytes) { + ctx.logger.warn(`Frame forwarding maxBytes ${config.maxBytes} exceeds the ${physicalMemory} bytes of physical memory; ` + + `the window budget is ${bytes} bytes.`) + } + return bytes + } + // The Desktop Host provides shared textures after the profile loads. Frame forwarding holds their only claim while + // both are loaded and closes every channel before releasing it. + ctx.inject(['sharedTexture', 'desktopFrameReceiver'], (scope) => { + scope.effect(() => { + let claim: SharedTextureClaim + try { + claim = scope.sharedTexture.claim() + } catch (error) { + ctx.logger.warn(error) + this.unavailable = 'desktop-shared-texture-claimed' + return () => { this.unavailable = 'desktop-shared-texture-unavailable' } + } + const { maxFrames, requestTimeoutMs, maxPendingRequests } = config + const forwarder: FrameForwarder = new FrameForwarder( + claim, + () => loadFrameForwardingBindings(scope.desktopFrameReceiver.path), + { maxFrames, maxBytes, requestTimeoutMs, maxPendingRequests }, + { + event: (event) => { + this.publish(event, forwarder) + if (event.kind === 'state' && event.channel.state === 'closed') this.disown(event.rx) + }, + warn: (message) => { ctx.logger.warn(message) }, + }, + ) + this.forwarder = forwarder + return async () => { + this.forwarder = undefined + // Every channel closes with the claim, so the scopes that opened them stop tracking them. + for (const dispose of [...this.owners.values()]) void dispose() + try { await forwarder.closeAll() } catch (error) { ctx.logger.warn(error) } finally { claim.release() } + } + }) + }) + ctx.effect(() => () => { this.endSubscriber() }) + } + + private missingReceiver(): boolean { + return Boolean(this.ctx.get('sharedTexture')) && !this.ctx.get('desktopFrameReceiver') + } + + private frames(): FrameForwarder { + if (this.forwarder !== undefined) return this.forwarder + if (this.missingReceiver()) throw new Error('Desktop frame receiver is unavailable.') + throw new Error(this.unavailable === 'desktop-shared-texture-claimed' + ? 'Desktop shared textures are claimed by another consumer.' : 'Desktop shared textures are unavailable.') + } + + /** + * A queued state is superseded by a newer state of its channel, so the queue keeps the latest state per channel. + * Beyond the limit the unread events become one snapshot of every channel, which keeps each channel's latest state + * and drops unread frame errors. The forwarder forgets a channel once its closure completes, so an unread closure of + * a forgotten channel moves into the snapshot; at most the newest `maxQueuedEvents` such closures do, so the + * snapshot stays bounded by the open channels however many channels close unread. The first snapshot never waits + * here: the stream takes it on its first read. + */ + private publish(event: FrameForwardingEvent, forwarder: FrameForwarder): void { + const subscriber = this.subscriber + if (subscriber === undefined || subscriber.ended) return + const { events } = subscriber + if (event.kind === 'state') { + const index = events.findIndex(queued => queued.kind === 'state' && queued.rx === event.rx) + if (index >= 0) events.splice(index, 1) + } + const { maxQueuedEvents } = this.config + if (events.length >= maxQueuedEvents) events.splice(0, events.length, { kind: 'snapshot', channels: compact(events, forwarder.snapshot(), maxQueuedEvents) }) + else events.push(event) + subscriber.wake?.() + } + + /** A channel the forwarder closed itself, after a lost frame or a failed receiver, no longer binds its opening scope. */ + private disown(rx: FrameRxId): void { + const owner = this.owners.get(rx) + if (owner === undefined) return + void Promise.resolve(owner()).catch(() => { + // The forwarder reports the teardown failure of a channel it closed itself. + }) + } + + private endSubscriber(): void { + const subscriber = this.subscriber + this.subscriber = undefined + if (subscriber === undefined) return + subscriber.ended = true + subscriber.wake?.() + } + + async capabilities(): Promise { + if (this.forwarder === undefined) return { supported: false, reason: this.missingReceiver() ? 'receiver-unavailable' : this.unavailable } + return this.forwarder.capabilities() + } + + async channel(): Promise { + const forwarder = this.frames() + const channel = await forwarder.channel() + const { rx } = channel + try { + // `this.ctx` is the scope that read this service, so disposing that scope closes the channel. + const dispose = this.ctx.effect(() => () => { + this.owners.delete(rx) + return this.forwarder?.close(rx) + }, 'frameForwarding.channel()') + this.owners.set(rx, dispose) + } catch (error) { + await forwarder.close(rx) + throw error + } + return channel + } + + isOpen(rx: FrameRxId): boolean { return this.forwarder?.isOpen(rx) ?? false } + + async close(rx: FrameRxId): Promise { + const owner = this.owners.get(rx) + if (owner !== undefined) await owner() + else await this.forwarder?.close(rx) + } + + /** + * Keep the renderer's physical viewport for a channel and apply it to the current producer connection; later + * connections receive it before their frames are delivered. + * @param rx - A channel the renderer consumes. + * @param viewport - Physical pixel size, scale, and visibility with a strictly increasing version. + * @returns The acknowledging connection, the Host's retained version for a stale submission, or why no producer acknowledged it. + */ + @Remote + async viewport(rx: FrameRxId, viewport: FrameForwardingViewport): Promise { + return this.frames().setViewport(rx, viewport) + } + + /** + * Deliver channel states and frame errors to the current renderer, starting with a snapshot of every channel. + * Each subscription replaces the previous one. + * @param signal - Subscriber lifetime. + * @returns The snapshot, then states and errors until replacement, cancellation, or disposal. + */ + @Remote({ mode: 'stream' }) + async *events(signal: AbortSignal): AsyncIterable { + this.endSubscriber() + const subscriber = { + events: [{ kind: 'snapshot', channels: this.forwarder?.snapshot() ?? [] }] as FrameForwardingEvent[], + wake: undefined as (() => void) | undefined, + ended: false, + } + this.subscriber = subscriber + const abort = (): void => { subscriber.wake?.() } + signal.addEventListener('abort', abort, { once: true }) + try { + while (!signal.aborted && !subscriber.ended) { + const next = subscriber.events.shift() + if (next !== undefined) { yield next; continue } + await new Promise((resolve) => { subscriber.wake = resolve }) + subscriber.wake = undefined + } + } finally { + signal.removeEventListener('abort', abort) + if (this.subscriber === subscriber) this.subscriber = undefined + } + } +} diff --git a/packages/experimental/frame-forwarding/src/types.ts b/packages/experimental/frame-forwarding/src/types.ts new file mode 100644 index 0000000000..5c604ac5bd --- /dev/null +++ b/packages/experimental/frame-forwarding/src/types.ts @@ -0,0 +1,108 @@ +/** Browser-safe frame-forwarding values: channel identity and state, viewports, frame metadata, and the `frameForwarding` Remote. */ +import type { Branded, BrandedNumber } from '@deepseek-ai/dsh-brand' +import type {} from '@deepseek-ai/dsh-typert-protocol' + +/** Host-issued identity of one receive channel; it survives producer switches and is invalid after the channel closes. */ +export type FrameRxId = Branded<'FrameRxId'> + +/** Increasing identity of one producer connection within its channel; a channel never reuses one. */ +export type FrameConnectionId = BrandedNumber<'FrameConnectionId'> + +/** Physical size and display state of one viewport version; frames of another `version` are discarded. */ +export interface FrameForwardingViewport { + readonly version: number + readonly width: number + readonly height: number + readonly deviceScaleFactor: number + readonly visible: boolean +} + +/** + * Identity of one delivered frame, carried as the Desktop shared-texture metadata; `generation` is the viewport + * version the producer rendered for, and `connectionId` the producer connection that rendered it. + */ +export interface FrameForwardingFrameMetadata { + readonly rx: FrameRxId + readonly connectionId: FrameConnectionId + /** Producer-echoed correlation identifier chosen by the requesting feature. */ + readonly requestId: string + readonly frameId: number + readonly generation: number + readonly revision: number + readonly width: number + readonly height: number +} + +/** + * Native frame support of the running Host. `reason` explains `supported: false` for diagnostics; its values are not a + * closed set, so consumers branch only on `supported`. + */ +export interface FrameForwardingCapabilities { + readonly supported: boolean + readonly reason?: string +} + +/** + * Why a channel closed. `closed`: its owner closed it. `lost`: Desktop could no longer account for a frame it + * presented, after a committed navigation, a renderer or GPU process exit, window closure, or the loss of Desktop's + * channel, so the channel stopped before its producer could write that frame again; the owner opens a new channel to + * continue. `failed`: its receiver stopped accepting producers. + */ +export type FrameChannelCloseCause = 'closed' | 'lost' | 'failed' + +/** + * Producer state of one channel. `idle`: no producer is connected. `connected`: connection `connectionId` serves the + * channel, and `viewportVersion` is the newest channel viewport it acknowledged. `draining`: that connection ended and + * its frames are being released; a successor connects only afterwards, and `blocked` reports GPU work of unknown + * completion that holds the drain. `closed`: terminal, with its cause. + */ +export type FrameChannelState = + | { readonly state: 'idle' } + | { readonly state: 'connected'; readonly connectionId: FrameConnectionId; readonly viewportVersion?: number } + | { readonly state: 'draining'; readonly connectionId: FrameConnectionId; readonly blocked?: string } + | { readonly state: 'closed'; readonly cause: FrameChannelCloseCause; readonly reason: string } + +/** + * Where a frame failed. `producer`: the producer reported a rendering failure or sent an invalid message or frame. + * `presentation`: Desktop could not present a frame the producer delivered. + */ +export type FrameFailureSource = 'producer' | 'presentation' + +/** One channel's state with the Host sequence number it was published under. */ +export interface FrameChannelSnapshot { + readonly rx: FrameRxId + /** Increases with every state the Host publishes; within one subscription a higher number is newer. */ + readonly sequence: number + readonly channel: FrameChannelState +} + +/** Items of the `frameForwarding` event stream. */ +export type FrameForwardingEvent = + /** + * The state of each channel: the first item of every subscription, and later in place of unread events beyond the + * Host's queue limit, which keeps the unread closures of channels the Host has since forgotten. A channel known + * before and absent from it closed while no subscription was open. + */ + | { readonly kind: 'snapshot'; readonly channels: readonly FrameChannelSnapshot[] } + | ({ readonly kind: 'state' } & FrameChannelSnapshot) + /** + * A frame of connection `connectionId` failed at `source`; `requestId` names the frame's request when the failure + * concerns one frame. + */ + | { + readonly kind: 'error' + readonly rx: FrameRxId + readonly connectionId: FrameConnectionId + readonly source: FrameFailureSource + readonly requestId?: string + readonly error: string + } + +/** + * Outcome of one renderer viewport. A stale submission leaves the Host's retained viewport intact and returns its + * version. For a newer submission the Host keeps the viewport even if the producer changes before acknowledging it. + */ +export type FrameViewportResult = + | { readonly applied: true; readonly connectionId: FrameConnectionId } + | { readonly applied: false; readonly reason: 'no-producer' | 'producer-changed' } + | { readonly applied: false; readonly reason: 'stale-viewport'; readonly currentVersion: number } diff --git a/packages/experimental/frame-forwarding/tests/backlog-harness.ts b/packages/experimental/frame-forwarding/tests/backlog-harness.ts new file mode 100644 index 0000000000..6df3fd6499 --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/backlog-harness.ts @@ -0,0 +1,258 @@ +/** + * Shared setup of the pending-event e2e suites: builds `fixtures/backlog-producer.cc` and the fake Desktop sink with the + * host toolchain, records receiver events and producer output, and blocks the JavaScript thread so the receiver's + * native threads queue events behind it. A blocked thread cannot read child output, so producers also report each + * observation as a signal file that a blocked wait can test synchronously. + */ +import { receiverAddon } from './desktop-receiver.ts' +import { spawn, type ChildProcess } from 'node:child_process' +import { once } from 'node:events' +import { existsSync } from 'node:fs' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect } from 'vitest' +import { loadFrameForwardingBindings } from '../src/host/native.ts' +import type { FrameForwardingAdapterId, FrameForwardingBindings, FrameForwardingBudget, FrameForwardingReceiver, FrameForwardingReceiverEvent } from '../src/host/native.ts' +import { buildFakeSink, buildFixtureProducer, type FakeSinkAddon } from './fake-sink.ts' + +export type Event = FrameForwardingReceiverEvent + +/** The `disconnected` text of a connection the receiver ended for exceeding its pending-event quota. */ +export const pendingLimitText = 'Frame-forwarding producer exceeded the pending event limit (256)' +/** Producer events (messages, presentation errors and frames for JavaScript) one connection may have pending. */ +export const pendingLimit = 256 + +const addonPath = receiverAddon + +/** Whether this host can build the fixtures and load the receiver: Windows or macOS with the addon built. */ +export const nativeSupported = (process.platform === 'win32' || process.platform === 'darwin') && existsSync(addonPath) + +export interface Harness { + scratch: string + producer: string + fakes: FakeSinkAddon + bindings: FrameForwardingBindings + displayAdapter: FrameForwardingAdapterId | null + children: ChildProcess[] + signals: number +} + +/** Build the producer and fake sink into a scratch directory and load the receiver addon. */ +export async function setupHarness(): Promise { + const scratch = await mkdtemp(join(tmpdir(), 'dsh-frame-forwarding-backlog-')) + const built = buildFakeSink(scratch) + const producer = buildFixtureProducer(scratch, 'backlog-producer', built.run) + let displayAdapter: FrameForwardingAdapterId | null = null + if (process.platform === 'win32') { + displayAdapter = built.fakes.defaultAdapter() as FrameForwardingAdapterId | null + expect(displayAdapter, 'a Windows receiver needs a hardware D3D11 adapter').not.toBeNull() + } + const bindings = loadFrameForwardingBindings(addonPath) + return { scratch, producer, fakes: built.fakes, bindings, displayAdapter, children: [], signals: 0 } +} + +/** Stop every producer still running. */ +export async function killProducers(harness: Harness): Promise { + await Promise.all(harness.children.splice(0).map(async (child) => { + if (child.exitCode !== null || child.signalCode !== null) return + const exited = once(child, 'exit') + child.kill('SIGKILL') + await exited + })) +} + +/** Stop every producer still running and remove the scratch directory. */ +export async function teardownHarness(harness: Harness | undefined): Promise { + if (!harness) return + await killProducers(harness) + try { + await rm(harness.scratch, { recursive: true, force: true }) + } catch (error) { + // Windows keeps the loaded fake sink open until the worker exits; the other build outputs are gone. + if (process.platform !== 'win32' || !(error instanceof Error) || !('code' in error) || error.code !== 'EPERM') throw error + } +} + +/** A fresh signal-file prefix for one producer. */ +export function signalPrefix(harness: Harness): string { + return join(harness.scratch, `signal-${String(++harness.signals)}`) +} + +/** Whether the producer started with `signal=` has reported `word`. */ +export function signalled(prefix: string, word: string): boolean { + return existsSync(`${prefix}.${word}`) +} + +/** + * Block the JavaScript thread, so no receiver event is dispatched, until `condition` holds or `ms` elapses. + * @returns Whether the condition held; the caller asserts it after the receiver callback that blocked has returned. + */ +export function blockUntil(condition: () => boolean, ms: number): boolean { + const cell = new Int32Array(new SharedArrayBuffer(4)) + const deadline = performance.now() + ms + while (!condition()) { + if (performance.now() >= deadline) return false + Atomics.wait(cell, 0, 0, 5) + } + return true +} + +/** Block the JavaScript thread for `ms`; the stress suite varies stalls without a condition. */ +export function blockFor(ms: number): void { + if (ms > 0) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) +} + +/** Await a promise with a deadline; resolves to 'timeout' when it expires. */ +export async function within(promise: Promise, ms: number): Promise { + let timer: ReturnType | undefined + try { + return await Promise.race([promise, new Promise<'timeout'>((resolve) => { timer = setTimeout(() => { resolve('timeout') }, ms) })]) + } finally { + clearTimeout(timer) + } +} + +/** A credential naming the same endpoint with a wrong secret. */ +export function corruptTx(tx: string): string { + const parts = tx.split('|') + parts[2] = parts[2]!.replace(/[0-9a-f]/gu, char => (char === '0' ? '1' : '0')) + return parts.join('|') +} + +/** Events of one connection, in arrival order. */ +export function ofConnection(events: readonly Event[], connectionId: number): Event[] { + return events.filter(event => 'connectionId' in event && event.connectionId === connectionId) +} + +/** The `seq` of each flooded message, or -1 for another message. */ +export function sequence(events: readonly Event[]): number[] { + return events.flatMap(event => event.type === 'message' ? [Number(/^\{"seq":(\d+),/u.exec(event.text)?.[1] ?? -1)] : []) +} + +export interface Channel { + receiver: FrameForwardingReceiver + events: Event[] + /** + * Resolve once `condition` holds over the recorded events, checked after each event. + * @throws When `ms` elapses first, naming `label` and the recorded event types. + */ + waitFor(label: string, condition: (events: readonly Event[]) => boolean, ms: number): Promise + count(type: Event['type']): number +} + +export interface ChannelOptions { + maxFrames?: number + maxBytes?: number + budget?: FrameForwardingBudget + /** Release each delivered frame before `hook` runs; defaults to true. */ + releaseFrames?: boolean +} + +/** + * One native receiver without a Desktop sink, so frames reach JavaScript, whose events are recorded. `hook` runs + * inside the receiver callback, after recording, so a stall there holds back every later event. + */ +export function createChannel(harness: Harness, hook?: (event: Event, receiver: FrameForwardingReceiver) => void, + options: ChannelOptions = {}): Channel { + const { maxFrames = 2, maxBytes = 1 << 20, releaseFrames = true } = options + const events: Event[] = [] + const waiters = new Set<() => void>() + const receiver: FrameForwardingReceiver = harness.bindings.createReceiver({ + maxFrames, maxBytes, budget: options.budget ?? harness.bindings.createBudget(maxBytes), + displayAdapter: harness.displayAdapter, readbackTimeoutMs: 10_000, + }, (event) => { + events.push(event) + if (event.type === 'frame' && releaseFrames) receiver.release(event.deliveryId) + hook?.(event, receiver) + for (const waiter of [...waiters]) waiter() + }) + return { + receiver, events, + count: type => events.filter(event => event.type === type).length, + waitFor: async (label, condition, ms) => { + if (condition(events)) return + let check = () => {} + const met = new Promise((resolve) => { + check = () => { if (condition(events)) resolve() } + waiters.add(check) + }) + try { + if (await within(met, ms) === 'timeout') + throw new Error(`Timed out after ${String(ms)} ms waiting for ${label}; events: ${summarize(events)}`) + } finally { + waiters.delete(check) + } + }, + } +} + +/** Event types with consecutive repeats folded, such as `connected message×256 disconnected drained`. */ +export function summarize(events: readonly Event[]): string { + const runs: { type: string; count: number }[] = [] + for (const event of events) { + const type = 'connectionId' in event ? `${event.type}#${String(event.connectionId)}` : event.type + const last = runs.at(-1) + if (last?.type === type) last.count++; else runs.push({ type, count: 1 }) + } + return runs.map(({ type, count }) => (count > 1 ? `${type}×${String(count)}` : type)).join(' ') +} + +export interface Producer { + child: ChildProcess + /** Stdout lines without their timestamps, as `
`. */ + lines: string[] + /** Settles once the process exited and its output was read. */ + exited: Promise + /** The first line whose word is `word`. */ + line(word: string): string | undefined + /** Resolve with the first line whose word is one of `words`; undefined when `ms` elapses first. */ + waitLine(words: string[], ms: number): Promise + stderr(): string + kill(): Promise +} + +/** Start the backlog producer with ` key=value...`. */ +export function startProducer(harness: Harness, tx: string, mode: 'produce' | 'refuse', options: Record = {}): Producer { + const args = [tx, mode, ...Object.entries(options).map(([key, value]) => `${key}=${String(value)}`)] + const child = spawn(harness.producer, args, { stdio: ['ignore', 'pipe', 'pipe'] }) + harness.children.push(child) + const lines: string[] = [] + const listeners = new Set<() => void>() + let buffer = '', stderr = '' + child.stdout.on('data', (chunk: Buffer) => { + buffer += chunk.toString() + let newline + while ((newline = buffer.indexOf('\n')) >= 0) { + lines.push(buffer.slice(0, newline).trim().replace(/^\d+ /u, '')) + buffer = buffer.slice(newline + 1) + } + for (const listener of [...listeners]) listener() + }) + child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString() }) + const exited = once(child, 'close') + const line = (word: string) => lines.find(text => text.split(' ')[0] === word) + return { + child, lines, exited, line, stderr: () => stderr, + waitLine: async (words, ms) => { + const find = () => words.map(line).find(text => text !== undefined) + let listener = () => {} + const found = new Promise((resolve) => { + listener = () => { const text = find(); if (text !== undefined) resolve(text) } + listeners.add(listener) + listener() + }) + try { + const text = await within(found, ms) + return text === 'timeout' ? undefined : text + } finally { + listeners.delete(listener) + } + }, + async kill() { + if (child.exitCode !== null || child.signalCode !== null) return + child.kill('SIGKILL') + await exited + }, + } +} diff --git a/packages/experimental/frame-forwarding/tests/content.client.spec.ts b/packages/experimental/frame-forwarding/tests/content.client.spec.ts new file mode 100644 index 0000000000..40006f78e4 --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/content.client.spec.ts @@ -0,0 +1,31 @@ +/** Mapping vectors cover document view coordinates. */ +import { describe, expect, it } from 'vitest' +import { contentFrame, validateView, validateWindow } from '../src/client/content.ts' +import vectors from './fixtures/content-vectors.json' + +const view = { x: 0, y: 0, scale: 1 } +const window = { x: 0, y: 0, width: 100, height: 80 } + +describe('content mapping', () => { + it.each(vectors.mapping)('$name', ({ window, view, expected }) => { + validateView(view) + validateWindow(window) + expect(contentFrame(window, view)).toEqual(expected) + }) + it.each([NaN, Infinity, -Infinity, 2 ** 24 + 1, -(2 ** 24 + 1)])('rejects coordinate %s', (value) => { + for (const key of ['x', 'y'] as const) { + expect(() => { validateView({ ...view, [key]: value }) }).toThrow(TypeError) + expect(() => { validateWindow({ ...window, [key]: value }) }).toThrow(TypeError) + } + }) + it.each([NaN, Infinity, -Infinity, 0, -1, 64.001])('rejects scale %s', (scale) => { + expect(() => { validateView({ ...view, scale }) }).toThrow(TypeError) + }) + it.each([NaN, Infinity, -Infinity, 0, -1, 2 ** 24 + 1])('rejects extent %s', (value) => { + for (const key of ['width', 'height'] as const) expect(() => { validateWindow({ ...window, [key]: value }) }).toThrow(TypeError) + }) + it('accepts positive fractional extents and scale at the lower bound', () => { + expect(() => { validateView({ ...view, scale: Number.MIN_VALUE }) }).not.toThrow() + expect(() => { validateWindow({ ...window, width: Number.MIN_VALUE, height: Number.MIN_VALUE }) }).not.toThrow() + }) +}) diff --git a/packages/experimental/frame-forwarding/tests/desktop-bridge-native.e2e.ts b/packages/experimental/frame-forwarding/tests/desktop-bridge-native.e2e.ts new file mode 100644 index 0000000000..e5de4f38c8 --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/desktop-bridge-native.e2e.ts @@ -0,0 +1,402 @@ +/** + * The built receiver presents frames of a real producer through a Desktop shared-texture sink in native code: a test + * addon implements the sink ABI of Desktop's `shared-texture-sink.h` and answers each presentation. Covers the frame + * metadata, credit return on release, the presentation gate, invalid producer metadata, failed deliveries, an + * invalidated settlement that stops the channel before releasing the frame, a rejected presentation that keeps the + * sink, a disconnected sink that is detached, answers inside `present`, ABI checks that refuse a sink of another magic + * or of version 1 or 3, argument checks, the sink references of attaching and presenting, and settlements that arrive + * after the receiver was closed and collected. On Windows, a receiver closes without waiting out the handshake of a + * connected client that has not sent its hello. With Desktop's addons built, frames cross Desktop's real hop sink into + * Desktop's ingress. + */ +import { receiverAddon } from './desktop-receiver.ts' +import { spawn, type ChildProcess } from 'node:child_process' +import { once } from 'node:events' +import { existsSync } from 'node:fs' +import { mkdtemp, rm } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { connect } from 'node:net' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { setFlagsFromString } from 'node:v8' +import { runInNewContext } from 'node:vm' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { loadFrameForwardingBindings } from '../src/host/native.ts' +import type { FrameForwardingAdapterId, FrameForwardingBindings, FrameForwardingReceiver, FrameForwardingReceiverEvent } from '../src/host/native.ts' +import type { FrameConnectionId } from '../src/types.ts' +import { buildFakeSink, buildFixtureProducer, type FakeSinkAddon } from './fake-sink.ts' + +const addon = receiverAddon +const platform = `${process.platform}-${process.arch}` +const desktopNative = fileURLToPath(new URL(`../../../../apps/desktop/lib/native/${platform}/`, import.meta.url)) +const desktopIngress = join(desktopNative, 'shared-texture-ingress.node') +const desktopHop = join(desktopNative, 'shared-texture-hop.node') +const supported = (process.platform === 'darwin' || process.platform === 'win32') && existsSync(addon) +type Event = FrameForwardingReceiverEvent +const connection = (value: number) => value as FrameConnectionId + +// Run `pnpm --filter @deepseek-ai/dsh-desktop run build:native` first; Windows needs the Visual Studio C++ tools. +describe.skipIf(!supported)('Desktop sink bridge of the built frame-forwarding receiver', () => { + let scratch = '' + let producer = '' + let fakes: FakeSinkAddon + let bindings: FrameForwardingBindings + let displayAdapter: FrameForwardingAdapterId | null = null + const children: ChildProcess[] = [] + + beforeAll(async () => { + scratch = await mkdtemp(join(tmpdir(), 'dsh-frame-forwarding-bridge-')) + const built = buildFakeSink(scratch) + fakes = built.fakes + producer = buildFixtureProducer(scratch, 'producer', built.run) + if (process.platform === 'win32') { + displayAdapter = fakes.defaultAdapter() as FrameForwardingAdapterId | null + expect(displayAdapter, 'a Windows receiver needs a hardware D3D11 adapter').not.toBeNull() + } + bindings = loadFrameForwardingBindings(addon) + }, 180_000) + afterAll(async () => { + await Promise.all(children.map(async (child) => { + if (child.exitCode !== null || child.signalCode !== null) return + const exited = once(child, 'exit') + child.kill() + await exited + })) + if (!scratch) return + try { + await rm(scratch, { recursive: true, force: true }) + } catch (error) { + // Windows keeps the loaded test addon's file open until this worker exits; the other build outputs are gone. + if (process.platform !== 'win32' || !(error instanceof Error) || !('code' in error) || error.code !== 'EPERM') throw error + } + }) + + /** One receiver with a fresh sink attached, whose events are read in order; a channel failure fails the read. */ + function channel(rx = 'rx-bridge') { + const queued: Event[] = [] + const waiters: ((event: Event) => void)[] = [] + const receiver = bindings.createReceiver({ + maxFrames: 1, maxBytes: 65536, budget: bindings.createBudget(65536), displayAdapter, readbackTimeoutMs: 10_000, + }, (event) => { const waiter = waiters.shift(); if (waiter === undefined) queued.push(event); else waiter(event) }) + const next = async (type: T, match: (event: Extract) => boolean = () => true): Promise> => { + for (;;) { + const event = queued.shift() ?? await new Promise((resolve) => { waiters.push(resolve) }) + if (event.type === 'failed' && type !== 'failed') throw new Error(event.text) + if (event.type === type && match(event as Extract)) return event as Extract + } + } + const fake = fakes.create() + receiver.attachSink(rx, fake.sink, 5000) + /** Wait for the producer to report submitting `frame`; its credit for the previous frame must have returned. */ + const submitted = (frame: number) => next('message', event => event.text === JSON.stringify({ submitted: frame })) + const render = (metadata: object | string) => { + receiver.send(connection(1), `render ${typeof metadata === 'string' ? metadata : JSON.stringify(metadata)}`) + } + return { receiver, next, queued, fake, rx, submitted, render, presented: () => fakes.presented(fake.native) } + } + function start(receiver: FrameForwardingReceiver) { + const child = spawn(producer, [receiver.tx], { stdio: ['ignore', 'ignore', 'pipe'] }) + children.push(child) + let stderr = '' + child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString() }) + return { child, exited: once(child, 'exit'), stderr: () => stderr } + } + const frame = (requestId: string, generation = 1, revision = 0) => ({ requestId, generation, revision }) + const open = (maxGeneration = 5) => ({ connectionId: connection(1), visible: true, maxGeneration }) + /** Connect a producer and consume the presentation error of its first frame, whose metadata names no request. */ + async function connected(context: ReturnType) { + const process = start(context.receiver) + await context.next('connected') + expect(await context.next('presentation-error')).toEqual({ + type: 'presentation-error', connectionId: 1, source: 'producer', + text: 'Invalid native frame metadata: requestId must be a string of 1 to 512 characters', + }) + return process + } + + it('presents a frame with its identity as metadata and returns its credit once Desktop releases it', async () => { + const context = channel() + const { receiver, fake, rx } = context + expect(fakes.references(fake.native)).toEqual({ refs: 2, retains: 1, releases: 0 }) + receiver.setDeliverable(open()) + try { + await connected(context) + context.render({ ...frame('tile-α', 3, 2), extra: true }) + await context.submitted(2) + await vi.waitFor(() => { expect(context.presented()).toHaveLength(1) }) + const [presented] = context.presented() + expect(Object.entries(JSON.parse(presented!.metadata) as object)).toEqual(Object.entries({ + requestId: 'tile-α', generation: 3, revision: 2, rx, connectionId: 1, frameId: 2, width: 64, height: 64, + })) + expect({ ...presented, id: undefined, metadata: undefined, handle: undefined }) + .toEqual({ width: 64, height: 64, timeoutMs: 5000, pixelFormat: 0 }) + expect(presented!.handle.readBigUInt64LE()).not.toBe(0n) + // Desktop holds the only credit, so the producer cannot submit its next frame. + context.render(frame('second', 3, 3)) + await new Promise(resolve => setTimeout(resolve, 300)) + expect(context.presented()).toHaveLength(1) + fakes.answer(fake.native, presented!.id, 'delivered', null) + fakes.answer(fake.native, presented!.id, 'settled', false) + await context.submitted(3) + await vi.waitFor(() => { expect(context.presented()).toHaveLength(2) }) + expect(JSON.parse(context.presented()[1]!.metadata)).toMatchObject({ requestId: 'second', frameId: 3 }) + // The attach holds the only reference the bridge takes; presenting frames retains nothing more. + expect(fakes.references(fake.native)).toEqual({ refs: 2, retains: 1, releases: 0 }) + expect(context.queued.filter(event => event.type === 'frame' || event.type === 'presentation-error')).toEqual([]) + receiver.send(connection(1), 'exit') + } finally { + await receiver.close() + } + }, 30_000) + + it('returns the credit of frames outside the deliverable state without presenting them', async () => { + const context = channel() + const { receiver } = context + try { + await connected(context) + const gates = [null, { ...open(), visible: false }, { ...open(), connectionId: connection(2) }, open(2)] + for (const [index, gate] of gates.entries()) { + receiver.setDeliverable(gate) + context.render(frame(`gated-${String(index)}`, 3)) + await context.submitted(index + 2) + } + // Invalid metadata is reported only after the last gated frame returned its credit. + context.render('not json') + expect(await context.next('presentation-error')).toMatchObject({ source: 'producer', text: 'Invalid native frame metadata: metadata is not valid JSON' }) + receiver.setDeliverable(open(3)) + context.render(frame('visible', 3)) + await vi.waitFor(() => { expect(context.presented()).toHaveLength(1) }) + expect(JSON.parse(context.presented()[0]!.metadata)).toMatchObject({ requestId: 'visible', generation: 3 }) + expect(context.queued.filter(event => event.type === 'frame')).toEqual([]) + receiver.send(connection(1), 'exit') + } finally { + await receiver.close() + } + }, 30_000) + + it('reports a failed delivery, then stops the channel before releasing a frame Desktop invalidated', async () => { + const context = channel() + const { receiver, fake } = context + receiver.setDeliverable(open()) + try { + const producerProcess = await connected(context) + context.render(frame('lost')) + await vi.waitFor(() => { expect(context.presented()).toHaveLength(1) }) + const { id } = context.presented()[0]! + fakes.answer(fake.native, id, 'delivered', 'renderer import failed') + const failed = await context.next('presentation-error') + expect(failed).toMatchObject({ connectionId: 1, source: 'presentation', requestId: 'lost' }) + expect(failed.text).toMatch(/^Native frame transfer failed \(source=.+, presentation=.+\): renderer import failed$/u) + context.render(frame('after-loss')) + fakes.answer(fake.native, id, 'settled', true) + expect(await context.next('presentation-invalidated')).toEqual({ + type: 'presentation-invalidated', connectionId: 1, text: 'Desktop invalidated a presented frame', + }) + // The stopped channel ends the producer's connection without returning the invalidated frame's credit. + expect((await context.next('disconnected')).connectionId).toBe(1) + expect(await producerProcess.exited).toEqual([0, null]) + expect(context.presented()).toHaveLength(1) + } finally { + await receiver.close() + } + }, 30_000) + + it('returns the credit of a rejected frame and keeps presenting later frames through the same sink', async () => { + const context = channel() + const { receiver, fake } = context + receiver.setDeliverable(open()) + try { + await connected(context) + fakes.refuseNext(fake.native, 'Desktop shared-texture presentation limit reached', 1) + context.render(frame('rejected')) + const rejected = await context.next('presentation-error') + expect(rejected).toMatchObject({ source: 'presentation', requestId: 'rejected' }) + expect(rejected.text).toContain('Desktop shared-texture presentation limit reached') + // The sink stays attached and holds only its attach reference. + expect(fakes.references(fake.native)).toEqual({ refs: 2, retains: 1, releases: 0 }) + context.render(frame('kept')) + // The producer submits the next frame only once the rejected frame's credit returned. + await context.submitted(3) + await vi.waitFor(() => { expect(context.presented()).toHaveLength(1) }) + expect(JSON.parse(context.presented()[0]!.metadata)).toMatchObject({ requestId: 'kept', frameId: 3 }) + expect(context.queued.filter(event => event.type === 'frame')).toEqual([]) + receiver.send(connection(1), 'exit') + } finally { + await receiver.close() + } + }, 30_000) + + it('returns the credit of a frame whose sink disconnected, detaches the sink, and delivers later frames to JavaScript', async () => { + const context = channel() + const { receiver, fake, rx } = context + receiver.setDeliverable(open()) + try { + await connected(context) + fakes.refuseNext(fake.native, 'Desktop shared-texture ingress disconnected', 2) + context.render(frame('refused')) + const refused = await context.next('presentation-error') + expect(refused).toMatchObject({ source: 'presentation', requestId: 'refused' }) + expect(refused.text).toContain('Desktop shared-texture ingress disconnected') + // The detached attach released its reference; only the sink external's own reference remains. + expect(fakes.references(fake.native)).toEqual({ refs: 1, retains: 1, releases: 1 }) + context.render(frame('unattached')) + const delivered = await context.next('frame') + expect(JSON.parse(delivered.metadata)).toMatchObject({ requestId: 'unattached' }) + expect(receiver.release(delivered.deliveryId)).toBe(true) + receiver.attachSink(rx, fake.sink, 5000) + expect(fakes.references(fake.native)).toEqual({ refs: 2, retains: 2, releases: 1 }) + context.render(frame('reattached')) + await vi.waitFor(() => { expect(context.presented()).toHaveLength(1) }) + expect(JSON.parse(context.presented()[0]!.metadata)).toMatchObject({ requestId: 'reattached' }) + receiver.send(connection(1), 'exit') + } finally { + await receiver.close() + } + }, 30_000) + + it('accepts a delivery and release that Desktop reports before present returns', async () => { + const context = channel() + const { receiver, fake } = context + fakes.answerInline(fake.native, true) + receiver.setDeliverable(open()) + try { + await connected(context) + for (const [index, requestId] of ['inline-1', 'inline-2', 'inline-3'].entries()) { + context.render(frame(requestId)) + await context.submitted(index + 2) + } + await vi.waitFor(() => { expect(context.presented()).toHaveLength(3) }) + receiver.send(connection(1), 'exit') + } finally { + await receiver.close() + } + }, 30_000) + + it('refuses a sink of another ABI and invalid attach or gate arguments', async () => { + const { receiver, fake } = channel() + try { + const refused = [fakes.create({ magic: 0x12345678 }), fakes.create({ version: 1 }), fakes.create({ version: 3 })] + for (const other of refused) + expect(() => { receiver.attachSink('rx', other.sink, 5000) }).toThrow('Unsupported Desktop shared-texture sink ABI') + expect(refused.map(other => fakes.references(other.native).retains)).toEqual([0, 0, 0]) + expect(() => { receiver.attachSink('rx', {}, 5000) }).toThrow('Expected a Desktop shared-texture sink external') + for (const rx of ['', 'x'.repeat(129), 'rx-é', 'rx\n']) + expect(() => { receiver.attachSink(rx, fake.sink, 5000) }).toThrow('Expected an rx of 1 to 128 printable ASCII characters') + for (const timeout of [0, 30_001, 1.5, Number.NaN]) + expect(() => { receiver.attachSink('rx', fake.sink, timeout) }).toThrow('Expected a presentation timeout of 1 to 30000 ms') + receiver.attachSink('x'.repeat(128), fake.sink, 30_000) + // Attaching again replaces the previous reference. + expect(fakes.references(fake.native)).toEqual({ refs: 2, retains: 2, releases: 1 }) + const invalid = [ + {}, { connectionId: 0, visible: true, maxGeneration: 0 }, { connectionId: 1, visible: 1, maxGeneration: 0 }, + { connectionId: 1, visible: true, maxGeneration: -1 }, { connectionId: 1, visible: true, maxGeneration: 2 ** 53 }, + { connectionId: 1, visible: true }, + ] + for (const state of invalid) { + expect(() => { receiver.setDeliverable(state as never) }).toThrow('Expected { connectionId, visible, maxGeneration } or null') + } + expect(() => { receiver.setDeliverable('open' as never) }).toThrow('Expected { connectionId, visible, maxGeneration } or null') + receiver.setDeliverable({ connectionId: connection(1), visible: false, maxGeneration: 0 }) + receiver.setDeliverable(null) + } finally { + await receiver.close() + } + }, 30_000) + + it('survives settlements that arrive after the receiver closed and was collected, then releases the sink', async () => { + setFlagsFromString('--expose-gc') + const gc = runInNewContext('gc') as () => void + // Everything that refers to the receiver stays inside this function, so it can be collected afterwards. + const held = async () => { + const context = channel() + context.receiver.setDeliverable(open()) + await connected(context) + context.render(frame('late')) + await vi.waitFor(() => { expect(context.presented()).toHaveLength(1) }) + context.receiver.send(connection(1), 'exit') + await context.receiver.close() + return { fake: context.fake, id: context.presented()[0]!.id } + } + const { fake, id } = await held() + fakes.answer(fake.native, id, 'delivered', 'renderer gone') + for (let round = 0; round < 5; round++) { + gc() + await new Promise(resolve => setImmediate(resolve)) + } + // The settlement drops the last reference to the receiver on the answering thread. + fakes.answer(fake.native, id, 'settled', true) + await vi.waitFor(() => { + gc() + expect(fakes.references(fake.native).refs).toBe(1) + }, { timeout: 10_000 }) + }, 30_000) + + it.runIf(process.platform === 'win32')('closes without waiting out the handshake of a client that has not sent its hello', async () => { + const { receiver } = channel('rx-silent') + // A connected pipe client that never says hello, like a producer still creating its D3D11 device. + const client = connect(receiver.tx.split('|').at(-1)!) + client.on('error', () => {}) + await once(client, 'connect') + await new Promise(resolve => setTimeout(resolve, 300)) + const started = performance.now() + await receiver.close() + // The handshake deadline is the 10 s readback timeout. + expect(performance.now() - started).toBeLessThan(5_000) + client.destroy() + }, 30_000) + + it.skipIf(!existsSync(desktopIngress) || !existsSync(desktopHop))('presents through Desktop\'s hop sink into Desktop\'s ingress and follows Main\'s settlements', async () => { + interface IngressFrame { type: 'frame'; requestId: number; handle: Buffer; width: number; height: number; pixelFormat: 'bgra' | 'rgba'; metadata: string } + interface Ingress { + open(pid: number, onEvent: (event: { type: string }) => void): { native: object; endpoint: string } + reply(native: object, requestId: number, kind: number, noReferenceKept: boolean, error: string): void + release(handle: Buffer): void + close(native: object): Promise + } + interface Hop { + connect(endpoint: string, onEvent: (event: { type: string }) => void): { native: object; sink: object } + close(native: object): void + } + const require = createRequire(import.meta.url) + const ingress = require(desktopIngress) as Ingress, hop = require(desktopHop) as Hop + const frames: IngressFrame[] = [] + // This process is both Desktop Host and Main, so the ingress admits its own process as the Host. + const opened = ingress.open(process.pid, (event) => { if (event.type === 'frame') frames.push(event as IngressFrame) }) + const connection = hop.connect(opened.endpoint, () => {}) + const context = channel() + const { receiver, rx } = context + receiver.attachSink(rx, connection.sink, 5000) + receiver.setDeliverable(open()) + const settle = (frame: IngressFrame, kind: 3 | 4) => { + ingress.reply(opened.native, frame.requestId, 1, false, '') + ingress.reply(opened.native, frame.requestId, kind, false, '') + ingress.release(frame.handle) + } + try { + await connected(context) + context.render(frame('through-desktop', 2, 1)) + await vi.waitFor(() => { expect(frames).toHaveLength(1) }) + const [first] = frames + expect(JSON.parse(first!.metadata)).toEqual({ + requestId: 'through-desktop', generation: 2, revision: 1, rx, connectionId: 1, frameId: 2, width: 64, height: 64, + }) + expect({ width: first!.width, height: first!.height, pixelFormat: first!.pixelFormat }).toEqual({ width: 64, height: 64, pixelFormat: 'bgra' }) + expect(first!.handle).toHaveLength(8) + // The producer regains its only credit once Main releases the texture. + context.render(frame('second')) + await new Promise(resolve => setTimeout(resolve, 300)) + expect(frames).toHaveLength(1) + settle(first!, 3) + await context.submitted(3) + await vi.waitFor(() => { expect(frames).toHaveLength(2) }) + settle(frames[1]!, 4) + expect(await context.next('presentation-invalidated')).toMatchObject({ connectionId: 1 }) + expect((await context.next('disconnected')).connectionId).toBe(1) + } finally { + await receiver.close() + hop.close(connection.native) + await ingress.close(opened.native) + } + }, 30_000) +}) diff --git a/packages/experimental/frame-forwarding/tests/desktop-receiver.ts b/packages/experimental/frame-forwarding/tests/desktop-receiver.ts new file mode 100644 index 0000000000..374ac3201e --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/desktop-receiver.ts @@ -0,0 +1,4 @@ +/** Desktop build output used by the native integration tests. */ +import { fileURLToPath } from 'node:url' + +export const receiverAddon = fileURLToPath(new URL(`../../../../apps/desktop/lib/native/${process.platform}-${process.arch}/frame-forwarding.node`, import.meta.url)) diff --git a/packages/experimental/frame-forwarding/tests/element-mount.client.spec.ts b/packages/experimental/frame-forwarding/tests/element-mount.client.spec.ts new file mode 100644 index 0000000000..0229b853ee --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/element-mount.client.spec.ts @@ -0,0 +1,734 @@ +// @vitest-environment jsdom +/** Mounted presentation and observer races without a GPU or browser layout engine. */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { FrameConnectionId, FrameRxId } from '../src/types.ts' +import type { FrameForwardingBridge, FrameForwardingFrameLease, FrameRxEvent } from '../src/client/api.ts' +import { FrameRx } from '../src/client/rx.ts' +import vectors from './fixtures/content-vectors.json' +import { createMediaPresenter } from '../src/client/presenters.ts' +import { mountElement } from '../src/client/element-mount.ts' + +const displays = new Set<{ dispose(): void }>() +const channels = new Set() +let rafs: Map +let nextRaf: number +let resized: () => void +let intersected: (entries: Partial[]) => void +let observerStops: ReturnType[] +let writer: { + write: ReturnType Promise>> + abort: ReturnType Promise>> +} +let trackStops: ReturnType[] + +beforeEach(() => { + rafs = new Map(); nextRaf = 0; observerStops = []; trackStops = [] + writer = { write: vi.fn(async () => {}), abort: vi.fn(async () => {}) } + vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => { rafs.set(++nextRaf, callback); return nextRaf }) + vi.stubGlobal('cancelAnimationFrame', (id: number) => { rafs.delete(id) }) + vi.stubGlobal('ResizeObserver', class { + disconnect = vi.fn() + constructor(callback: () => void) { resized = callback; observerStops.push(this.disconnect) } + observe() {} + }) + vi.stubGlobal('IntersectionObserver', class { + disconnect = vi.fn() + constructor(callback: typeof intersected) { intersected = callback; observerStops.push(this.disconnect) } + observe() {} + }) + vi.stubGlobal('MediaStreamTrackGenerator', class { + writable = { getWriter: () => writer } + stop = vi.fn() + constructor() { trackStops.push(this.stop) } + }) + vi.stubGlobal('MediaStream', vi.fn(function MediaStream() { return { active: true } })) + vi.spyOn(HTMLMediaElement.prototype, 'play').mockResolvedValue() + vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {}) +}) +afterEach(async () => { + for (const display of displays) display.dispose() + displays.clear() + await Promise.all([...channels].map(channel => channel.close())) + channels.clear() + document.body.replaceChildren() + document.documentElement.removeAttribute('style') + document.body.removeAttribute('style') + vi.restoreAllMocks() + vi.useRealTimers() + vi.unstubAllGlobals() +}) +async function tick() { + await Promise.resolve() + const callbacks = [...rafs.values()] + rafs.clear() + for (const callback of callbacks) callback(0) + await Promise.resolve() + await Promise.resolve() +} +function box(element: Element, x = 10, y = 20, width = 100, height = 80) { + vi.spyOn(element, 'getBoundingClientRect').mockReturnValue({ x, y, width, height, left: x, top: y, right: x + width, bottom: y + height, toJSON: () => ({}) }) +} +function frameImage() { + return { + codedWidth: 100, codedHeight: 80, codedRect: null, displayWidth: 100, displayHeight: 80, + duration: null, format: 'RGBA', timestamp: 0, visibleRect: null, + colorSpace: { fullRange: null, matrix: null, primaries: null, transfer: null, toJSON: () => ({}) }, + allocationSize: () => 100 * 80 * 4, copyTo: async () => [], + clone: (): VideoFrame => frameImage(), close: vi.fn(), + } satisfies VideoFrame +} +function fixture(connected = true) { + const slot = document.createElement('div') + const element = document.createElement('div') + slot.append(element); document.body.append(slot); box(element) + let arrive: (lease: FrameForwardingFrameLease) => void = () => {} + let event: (event: FrameRxEvent) => void = () => {} + const bridge = { + setViewport: vi.fn(async () => ({ applied: true, connectionId: 1 as FrameConnectionId })), + attach(_rx, { onFrame, onEvent }) { + arrive = onFrame + event = onEvent + if (connected) event({ kind: 'state', channel: { state: 'connected', connectionId: 1 as FrameConnectionId } }) + return async () => {} + }, + apply: vi.fn(), requestFullscreen: vi.fn(async () => {}), + exitFullscreen: vi.fn(async () => {}), fail: vi.fn(), dispose: vi.fn(), + } satisfies FrameForwardingBridge + const channel = new FrameRx('rx' as FrameRxId, bridge) + channels.add(channel) + const failure = vi.fn() + const visible = () =>{ intersected([{ target: element, isIntersecting: true }]) } + const frame = () => { + const copy = frameImage() + const image = { ...frameImage(), clone: vi.fn(() => copy) } + const lease = { frame: image, + metadata: { rx: channel.rx, connectionId: 1 as FrameConnectionId, requestId: '', frameId: 1, revision: 1, + generation: bridge.setViewport.mock.calls.at(-1)?.[1].version ?? 0, width: 100, height: 80 }, + release: vi.fn() } satisfies FrameForwardingFrameLease + return { lease, copy } + } + return { slot, element, channel, bridge, failure, visible, frame, + arrive: (lease: FrameForwardingFrameLease) => { arrive(lease) }, event: (value: FrameRxEvent) => { event(value) } } +} + +const contentView = { x: 0, y: 0, scale: 1 } +const contentWindow = { x: 0, y: 0, width: 200, height: 160 } + +describe('video mount', () => { + it('mounts a reopened receive channel before the first state arrives and uses the retained Host generation', async () => { + const f = fixture(false) + let retained = 0 + f.bridge.setViewport.mockImplementation(async (_rx, viewport) => { + if (viewport.version <= retained) return { applied: false, reason: 'stale-viewport', currentVersion: retained } + retained = viewport.version + return { applied: false, reason: 'no-producer' } + }) + await f.channel.setViewport({ version: 7, width: 20, height: 20, deviceScaleFactor: 1, visible: true }) + await f.channel.close() + const reopened = new FrameRx(f.channel.rx, f.bridge) + channels.add(reopened) + reopened.mount(f.element, f.failure) + reopened.setContentView(contentView) + let nextWindow: Promise> | undefined + reopened.onEvent((event) => { + if (event.kind === 'viewport' && event.viewport.version === 8) { + nextWindow = reopened.setContentWindow({ ...contentWindow, y: 100 }) + } + }) + const viewport = await reopened.setContentWindow(contentWindow) + expect(viewport.version).toBe(8) + await expect(nextWindow).resolves.toMatchObject({ version: 9 }) + expect(f.bridge.setViewport.mock.calls.map(([, value]) => value.version)).toEqual([7, 1, 8, 9]) + f.event({ kind: 'state', channel: { state: 'connected', connectionId: 1 as FrameConnectionId, viewportVersion: retained } }) + await expect(reopened.ready()).resolves.toBe(1) + expect(f.failure).not.toHaveBeenCalled() + }) + + it('keeps a mount opened during draining reserved until connected, and closes it while suspended', async () => { + const f = fixture() + f.event({ kind: 'state', channel: { state: 'draining', connectionId: 1 as FrameConnectionId } }) + f.channel.mount(f.element, f.failure) + await tick() + expect(writer.write).not.toHaveBeenCalled() + expect(f.element.getAttribute('data-dsh-frame-mount')).toBe('pending') + await expect(f.channel.setContentWindow(contentWindow)).rejects.toMatchObject({ reason: 'producer-changed' }) + const other = fixture() + expect(() => other.channel.mount(f.element, other.failure)).toThrow('frame consumer') + f.event({ kind: 'state', channel: { state: 'closed', cause: 'lost', reason: 'Host exited' } }) + expect(f.element.hasAttribute('data-dsh-frame-mount')).toBe(false) + expect(f.failure).toHaveBeenCalledOnce() + }) + it('creates the video display before a window request sends the first viewport, so its frame is shown', async () => { + const f = fixture() + f.channel.mount(f.element, f.failure) + f.visible() + f.channel.setContentView(contentView) + // The window request runs before the mount's first animation frame and sends the first viewport itself. + const request = f.channel.setContentWindow(contentWindow) + await vi.waitFor(() => { expect(f.bridge.setViewport).toHaveBeenCalledOnce() }) + const { lease } = f.frame() + f.arrive(lease) + await request + await vi.waitFor(() => { expect(writer.write).toHaveBeenCalledOnce() }) + }) + it('lends video frames until the writer settles and stops the track on unmount', async () => { + const f = fixture() + const write = Promise.withResolvers() + writer.write.mockReturnValue(write.promise) + const unmount = f.channel.mount(f.element, f.failure); await tick() + const { lease, copy } = f.frame(); f.arrive(lease) + expect(lease.release).not.toHaveBeenCalled() + unmount(); expect(trackStops[0]).toHaveBeenCalledOnce() + write.resolve(undefined); await tick() + expect(copy.close).toHaveBeenCalledOnce() + expect(lease.release).toHaveBeenCalledOnce() + expect(writer.abort).toHaveBeenCalledOnce() + }) + it('cleans up and reports a lost channel, including an explicit local close', async () => { + const f = fixture() + f.channel.mount(f.element, f.failure); await tick(); await tick() + f.event({ kind: 'state', channel: { state: 'closed', cause: 'lost', reason: 'GPU stopped' } }) + expect(trackStops[0]).toHaveBeenCalledOnce() + expect(f.failure).toHaveBeenCalledWith(expect.objectContaining({ reason: 'lost' })) + await f.channel.close() + expect(f.failure).toHaveBeenCalledOnce() + }) + it('keeps mounted and continuous consumption exclusive', () => { + const f = fixture() + const unmount = f.channel.mount(f.element, f.failure) + expect(() => f.channel.mount(f.element, f.failure)).toThrow('frame consumer') + expect(() => f.channel.consume(() => {}, f.failure)).toThrow('frame consumer') + unmount() + unmount() + const consume = f.channel.consume(() => {}, f.failure) + expect(() => f.channel.mount(f.element, f.failure)).toThrow('frame consumer') + consume() + }) + it('sends a final hidden update without rAF and restores visibility on the next frame', async () => { + const f = fixture() + f.channel.mount(f.element, f.failure); f.visible(); await tick(); await tick() + const visibility = vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden') + document.dispatchEvent(new Event('visibilitychange')) + await Promise.resolve(); await Promise.resolve() + expect(f.bridge.setViewport.mock.calls.at(-1)?.[1].visible).toBe(false) + document.dispatchEvent(new Event('visibilitychange')) + visibility.mockReturnValue('visible'); document.dispatchEvent(new Event('visibilitychange')) + await tick(); await tick() + }) + it('queues an invisible viewport between a pending visible mount and its replacement', async () => { + const f = fixture() + const ack = Promise.withResolvers>>() + f.bridge.setViewport.mockReturnValueOnce(ack.promise) + const detach = f.channel.mount(f.element, f.failure) + f.visible(); await tick() + const first = f.bridge.setViewport.mock.calls[0]![1] + expect(first.visible).toBe(true) + detach() + detach() + f.channel.mount(f.element, f.failure) + f.visible(); await tick() + expect(f.bridge.setViewport).toHaveBeenCalledTimes(1) + ack.resolve({ applied: true, connectionId: 1 as FrameConnectionId }) + await vi.waitFor(() => { + expect(f.bridge.setViewport.mock.calls.map(([, viewport]) => viewport)).toEqual([ + first, { ...first, version: first.version + 1, visible: false }, { ...first, version: first.version + 2 }, + ]) + }) + await f.channel.close() + detach() + expect(f.bridge.setViewport).toHaveBeenCalledTimes(3) + }) + it.each(['close', 'replace'] as const)('respects a reentrant %s when the displayed frame is cleared', async (action) => { + const f = fixture() + const detach = f.channel.mount(f.element, f.failure) + f.visible(); await tick() + const viewport = f.channel.viewport! + const { lease } = f.frame() + f.arrive(lease) + await vi.waitFor(() => { expect(lease.release).toHaveBeenCalledOnce() }) + let completion: Promise | undefined + f.channel.onEvent((event) => { + if (event.kind === 'content' && event.submittedGeneration === undefined) { + completion = action === 'close' ? f.channel.close() : f.channel.setViewport({ ...viewport, version: 10 }) + } + }) + detach() + await completion + const sent = f.bridge.setViewport.mock.calls.map(([, value]) => value) + expect(sent).toEqual(action === 'close' ? [viewport] : [viewport, { ...viewport, version: 10 }]) + }) + it.each(['producer-changed', 'refused'] as const)('handles an unmount viewport that ends with %s', async (result) => { + const f = fixture() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const detach = f.channel.mount(f.element, f.failure) + f.visible(); await tick() + if (result === 'producer-changed') f.bridge.setViewport.mockResolvedValueOnce({ applied: false, reason: result }) + else f.bridge.setViewport.mockRejectedValueOnce(new Error('refused')) + detach() + await vi.waitFor(() => { expect(f.bridge.setViewport).toHaveBeenCalledTimes(2) }) + if (result === 'refused') expect(log).toHaveBeenCalledWith('Frame unmount viewport failed', expect.any(Error)) + else expect(log).not.toHaveBeenCalled() + expect(f.failure).not.toHaveBeenCalled() + }) + it('sends no queued unmount viewport after the channel closes', async () => { + const f = fixture() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const ack = Promise.withResolvers>>() + f.bridge.setViewport.mockReturnValueOnce(ack.promise) + const detach = f.channel.mount(f.element, f.failure) + f.visible(); await tick() + detach() + await f.channel.close() + ack.resolve({ applied: true, connectionId: 1 as FrameConnectionId }) + await tick(); await tick() + expect(f.bridge.setViewport).toHaveBeenCalledOnce() + expect(log).not.toHaveBeenCalled() + }) + it('coalesces viewport changes while an acknowledgement is pending', async () => { + const f = fixture() + const ack = Promise.withResolvers>>() + f.bridge.setViewport.mockReturnValueOnce(ack.promise) + f.channel.mount(f.element, f.failure); await tick() + box(f.element, 0, 0, 150, 100); resized(); await tick() + box(f.element, 0, 0, 250, 200); resized(); await tick() + expect(f.bridge.setViewport).toHaveBeenCalledOnce() + ack.resolve({ applied: true, connectionId: 1 as FrameConnectionId }) + await tick(); await tick(); await tick() + expect(f.bridge.setViewport).toHaveBeenCalledTimes(2) + expect(f.bridge.setViewport.mock.calls[1]?.[1].width).toBe(250) + }) + it('queues reanchors behind mount updates and omits coalesced windows from previous', async () => { + const f = fixture() + f.channel.mount(f.element, f.failure); await tick(); await tick() + f.channel.setContentView(contentView) + await f.channel.setContentWindow(contentWindow) + const acknowledgement = Promise.withResolvers>>() + f.bridge.setViewport.mockReturnValueOnce(acknowledgement.promise) + box(f.element, 0, 0, 200, 200); resized(); await tick() + const skipped = f.channel.setContentWindow({ ...contentWindow, y: 100 }) + const latestWindow = { ...contentWindow, y: 200 } + const latest = f.channel.setContentWindow(latestWindow) + expect(latest).toBe(skipped) + expect(f.bridge.setViewport.mock.calls.at(-1)?.[1].version).toBe(3) + acknowledgement.resolve({ applied: true, connectionId: 1 as FrameConnectionId }) + expect((await latest).version).toBe(4) + expect(await skipped).toEqual(await latest) + expect(f.bridge.setViewport.mock.calls.map(call => call[1].version)).toEqual([1, 2, 3, 4]) + }) + it('keeps a reentrant newer window request ahead of an unchanged retry', async () => { + const f = fixture() + f.channel.mount(f.element, f.failure); await tick(); await tick() + f.channel.setContentView(contentView) + let nested: Promise> | undefined + f.channel.onEvent((event) => { + if (event.kind === 'viewport' && event.viewport.version === 2) nested = f.channel.setContentWindow({ ...contentWindow, y: 200 }) + }) + await f.channel.setContentWindow(contentWindow) + const retry = f.channel.setContentWindow({ ...contentWindow, y: 200 }) + expect(retry).toBe(nested) + expect((await retry).version).toBe(3) + }) + it('rejects invalid values synchronously without changing state or sending messages', async () => { + const f = fixture() + const unmount = f.channel.mount(f.element, f.failure); await tick(); await tick() + f.channel.setContentView(contentView) + await f.channel.setContentWindow(contentWindow) + const versions = f.bridge.setViewport.mock.calls.length + for (const value of [NaN, Infinity, -Infinity, 2 ** 24 + 1]) { + expect(() => { f.channel.setContentView({ ...contentView, x: value }) }).toThrow(TypeError) + expect(() => f.channel.setContentWindow({ ...contentWindow, y: value })).toThrow(TypeError) + } + expect(() => { f.channel.setContentView({ ...contentView, scale: 0 }) }).toThrow(TypeError) + expect(() => f.channel.setContentWindow({ ...contentWindow, height: -1 })).toThrow(TypeError) + await tick() + expect(f.bridge.setViewport).toHaveBeenCalledTimes(versions) + unmount() + expect(() => f.channel.setContentWindow(contentWindow)).toThrow('Frame content requires mount.') + expect(() => { f.channel.setContentView(contentView) }).toThrow('Frame content requires mount.') + }) + it('rejects pending content calls on unmount and never sends their queued successor', async () => { + const f = fixture() + f.channel.mount(f.element, f.failure); await tick(); await tick() + f.channel.setContentView(contentView) + const acknowledgement = Promise.withResolvers>>() + f.bridge.setViewport.mockReturnValueOnce(acknowledgement.promise) + const inFlight = f.channel.setContentWindow(contentWindow) + const queued = f.channel.setContentWindow({ ...contentWindow, y: 100 }) + const rejected = [expect(inFlight).rejects.toMatchObject({ reason: 'producer-changed' }), + expect(queued).rejects.toMatchObject({ reason: 'producer-changed' })] + await vi.waitFor(() => { expect(f.bridge.setViewport).toHaveBeenCalledTimes(2) }) + await f.channel.close() + await Promise.all(rejected) + acknowledgement.resolve({ applied: true, connectionId: 1 as FrameConnectionId }) + await tick(); await tick() + expect(f.bridge.setViewport).toHaveBeenCalledTimes(2) + }) + it('rejects refused content viewports and stops mount resources before reporting failure', async () => { + const f = fixture() + f.channel.mount(f.element, f.failure); await tick(); await tick() + f.channel.setContentView(contentView) + const refusal = new Error('viewport acknowledgement refused') + f.bridge.setViewport.mockRejectedValueOnce(refusal) + await expect(f.channel.setContentWindow(contentWindow)).rejects.toBe(refusal) + expect(trackStops[0]).toHaveBeenCalledOnce() + expect(f.failure).toHaveBeenCalledExactlyOnceWith(refusal) + expect(() => f.channel.setContentWindow(contentWindow)).toThrow('Frame content requires mount.') + }) + it('settles an unchanged-window wait when a resized mount closes before Host acknowledges', async () => { + const f = fixture() + f.channel.mount(f.element, f.failure); await tick(); await tick() + f.channel.setContentView(contentView) + await f.channel.setContentWindow(contentWindow) + const acknowledgement = Promise.withResolvers>>() + f.bridge.setViewport.mockReturnValueOnce(acknowledgement.promise) + box(f.element, 0, 0, 300, 200); resized(); await tick() + const unchanged = f.channel.setContentWindow(contentWindow).catch((error: unknown) => error) + await f.channel.close() + const result = await Promise.race([unchanged, Promise.resolve('still waiting')]) + acknowledgement.resolve({ applied: true, connectionId: 1 as FrameConnectionId }) + await tick() + expect(result).toMatchObject({ reason: 'producer-changed' }) + }) + it('ignores late playback rejection after idempotent disposal and reports writer teardown failure', async () => { + const f = fixture() + const playback = Promise.withResolvers() + vi.spyOn(HTMLMediaElement.prototype, 'play').mockReturnValueOnce(playback.promise) + const error = new Error('writer teardown refused') + writer.abort.mockRejectedValueOnce(error) + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const presenter = createMediaPresenter(f.element, f.failure, vi.fn()) + presenter.dispose(); presenter.dispose() + playback.reject(new Error('late playback')) + await tick() + expect(f.failure).not.toHaveBeenCalled() + expect(trackStops[0]).toHaveBeenCalledOnce() + expect(log).toHaveBeenCalledWith('Frame video writer teardown failed', error) + }) + it('stops the track and removes media when playback setup throws', () => { + const f = fixture() + const error = new Error('play setup failed') + vi.spyOn(HTMLMediaElement.prototype, 'play').mockImplementationOnce(() => { throw error }) + expect(() => createMediaPresenter(f.element, f.failure, vi.fn())).toThrow(error) + expect(trackStops[0]).toHaveBeenCalledOnce() + expect(writer.abort).toHaveBeenCalledOnce() + expect(f.element.children).toHaveLength(0) + }) + it('rejects failed writes while closing the cloned frame', async () => { + const f = fixture() + const error = new Error('write failed') + writer.write.mockRejectedValueOnce(error) + const presenter = createMediaPresenter(f.element, f.failure, vi.fn()) + const { lease, copy } = f.frame() + await expect(presenter.present({ image: lease.frame, metadata: lease.metadata })).rejects.toBe(error) + expect(copy.close).toHaveBeenCalledOnce() + presenter.dispose() + }) + + it('reports the generation accepted by the video track only after its write completes', async () => { + const f = fixture() + const events: FrameRxEvent[] = [] + f.channel.onEvent(event => events.push(event)) + const write = Promise.withResolvers() + writer.write.mockReturnValue(write.promise) + const unmount = f.channel.mount(f.element, f.failure) + f.visible(); await tick() + const { lease } = f.frame() + f.arrive(lease) + const content = () => events.filter(event => event.kind === 'content').at(-1) + expect(content()?.submittedGeneration).toBeUndefined() + write.resolve(undefined) + await tick() + expect(content()?.submittedGeneration).toBe(lease.metadata.generation) + unmount() + expect(content()?.submittedGeneration).toBeUndefined() + }) + + it.each(vectors.mapping)('places the video for $name', async ({ window, view, expected }) => { + const f = fixture() + f.channel.mount(f.element, f.failure) + await tick() + f.channel.setContentView(view) + await f.channel.setContentWindow(window) + const video = f.element.querySelector('video')! + expect([video.style.width, video.style.height, video.style.transform]).toEqual([ + `${expected.width}px`, `${expected.height}px`, `translate(${expected.x}px, ${expected.y}px)`, + ]) + }) +}) + +function directMount(element: HTMLElement) { + const owner = { + fullscreen: () => ({ active: false, holder: false }), content: () => undefined, + viewport: vi.fn[1]['viewport']>(async value => ({ ...value, version: 1 })), + report: vi.fn[1]['report']>(), failure: vi.fn(), + } + const mount = mountElement(element, owner) + displays.add(mount) + return { mount, owner } +} + +describe('display resource ownership', () => { + it('requires a live document and an unclaimed element', () => { + const f = fixture() + expect(() => directMount(document.implementation.createHTMLDocument().createElement('div'))).toThrow('needs a live document') + f.element.setAttribute('data-dsh-frame-mount', 'pending') + expect(() => directMount(f.element)).toThrow('already has a frame consumer') + }) + it.each(['', 'static', 'absolute'])('restores inline styles and priorities after unmount: %s', (position) => { + const f = fixture() + f.element.style.setProperty('position', position, 'important') + f.element.style.setProperty('isolation', 'auto', 'important') + const { mount } = directMount(f.element) + expect(f.element.style.position).toBe(position === 'absolute' ? 'absolute' : 'relative') + mount.dispose() + expect(f.element.style.position).toBe(position) + expect(f.element.style.getPropertyPriority('position')).toBe(position === '' ? '' : 'important') + expect(f.element.style.isolation).toBe('auto') + expect(f.element.style.getPropertyPriority('isolation')).toBe('important') + }) + it('reports synchronous viewport failure and ignores completion after disposal', async () => { + const f = fixture() + const { mount, owner } = directMount(f.element) + const error = new Error('viewport failed') + owner.viewport.mockImplementationOnce(() => { throw error }) + await expect(mount.requestViewport()).rejects.toBe(error) + expect(owner.failure).toHaveBeenCalledWith(error) + mount.pushContent(); mount.dirty() + await expect(mount.requestViewport()).rejects.toMatchObject({ reason: 'producer-changed' }) + }) + it('rejects content requests when synchronous geometry measurement fails', async () => { + const f = fixture() + const { mount, owner } = directMount(f.element) + vi.spyOn(f.element, 'getBoundingClientRect').mockImplementationOnce(() => { throw new Error('layout unavailable') }) + await expect(mount.requestViewport()).rejects.toThrow('layout unavailable') + expect(owner.failure).toHaveBeenCalledWith(expect.objectContaining({ message: 'layout unavailable' })) + }) + it('contains hidden-document measurement failure', async () => { + const f = fixture() + f.channel.mount(f.element, f.failure); await tick(); await tick() + vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden') + vi.spyOn(f.element, 'getBoundingClientRect').mockImplementationOnce(() => { throw new Error('hidden layout failed') }) + document.dispatchEvent(new Event('visibilitychange')) + expect(f.failure).toHaveBeenCalledWith(expect.objectContaining({ message: 'hidden layout failed' })) + expect(trackStops[0]).toHaveBeenCalledOnce() + }) + it('ignores queued animation and visibility callbacks after unmount', async () => { + const f = fixture() + const events = vi.spyOn(document, 'addEventListener') + const unmount = f.channel.mount(f.element, f.failure) + const flush = [...rafs.values()][0]! + const visibility = events.mock.calls.find(([type]) => type === 'visibilitychange')![1] + unmount() + flush(0) + if (typeof visibility !== 'function') throw new Error('Expected visibility callback') + visibility(new Event('visibilitychange')) + await tick() + expect(trackStops).toHaveLength(0) + expect(f.bridge.setViewport).not.toHaveBeenCalled() + }) + it('rolls back synchronous observer setup failure', () => { + const f = fixture() + vi.stubGlobal('IntersectionObserver', class { + disconnect = vi.fn() + constructor() { observerStops.push(this.disconnect) } + observe() { throw new Error('observe failed') } + }) + expect(() => f.channel.mount(f.element, f.failure)).toThrow('observe failed') + expect(f.element.hasAttribute('data-dsh-frame-mount')).toBe(false) + expect(observerStops.every(stop => stop.mock.calls.length > 0)).toBe(true) + expect(() => f.channel.consume(vi.fn(), vi.fn())).not.toThrow() + }) + it('contains cleanup and failure-listener errors while freeing consumption', async () => { + const f = fixture() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + f.channel.mount(f.element, () => { throw new Error('listener failed') }); await tick(); await tick() + trackStops[0]!.mockImplementationOnce(() => { throw new Error('detach failed') }) + await f.channel.close() + expect(log).toHaveBeenCalledWith('Frame mount cleanup failed', expect.objectContaining({ message: 'detach failed' })) + expect(log).toHaveBeenCalledWith('Native frame failure listener failed', expect.objectContaining({ message: 'listener failed' })) + }) + it('reports replacement mount setup failure', async () => { + const f = fixture() + f.channel.mount(f.element, f.failure); await tick(); await tick() + f.event({ kind: 'state', channel: { state: 'draining', connectionId: 1 as FrameConnectionId } }) + vi.spyOn(window, 'getComputedStyle').mockImplementationOnce(() => { throw 'computed style failed' }) + f.event({ kind: 'state', channel: { state: 'connected', connectionId: 2 as FrameConnectionId } }) + expect(f.failure).toHaveBeenCalledWith(expect.objectContaining({ message: 'computed style failed' })) + expect(f.element.hasAttribute('data-dsh-frame-mount')).toBe(false) + }) +}) + +it('reports non-Error layout failures even when video cleanup also fails', async () => { + const f = fixture() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + f.channel.mount(f.element, f.failure); await tick(); await tick() + trackStops[0]!.mockImplementationOnce(() => { throw new Error('detach failed') }) + vi.spyOn(f.element, 'getBoundingClientRect').mockImplementationOnce(() => { throw 'layout lost' }) + resized(); await tick() + expect(log).toHaveBeenCalledWith('Frame mount cleanup failed', expect.objectContaining({ message: 'detach failed' })) + expect(f.failure).toHaveBeenCalledWith(expect.objectContaining({ source: 'presentation', message: 'layout lost' })) +}) + +it('retains unconfirmed frames while their windows remain in the content snapshot', async () => { + const f = fixture() + f.channel.mount(f.element, f.failure); await tick(); await tick() + f.channel.setContentView(contentView) + const first = await f.channel.setContentWindow(contentWindow) + const future = f.frame().lease + future.metadata.generation = first.version + 1 + f.arrive(future) + expect(future.release).toHaveBeenCalledOnce() + const { lease } = f.frame() + lease.metadata.connectionId = 2 as FrameConnectionId + lease.metadata.generation = first.version + f.arrive(lease) + await f.channel.setContentWindow({ ...contentWindow, y: 100 }) + expect(lease.release).not.toHaveBeenCalled() + await f.channel.setContentWindow({ ...contentWindow, y: 200 }) + expect(lease.release).toHaveBeenCalledOnce() +}) + +it('drops a retained queued document frame when fill mode makes its generation obsolete', async () => { + const f = fixture() + f.channel.mount(f.element, f.failure); await tick(); await tick() + f.channel.setContentView(contentView) + await f.channel.setContentWindow(contentWindow) + const writing = Promise.withResolvers() + writer.write.mockReturnValueOnce(writing.promise) + const first = f.frame(), queued = f.frame() + try { + f.arrive(first.lease); f.arrive(queued.lease) + await f.channel.setContentWindow({ ...contentWindow, y: 100 }) + expect(queued.lease.release).not.toHaveBeenCalled() + f.channel.setContentView(undefined) + } finally { + writing.resolve(undefined) + await tick(); await tick() + } + expect(first.lease.release).toHaveBeenCalledOnce() + expect(queued.lease.release).toHaveBeenCalledOnce() + expect(writer.write).toHaveBeenCalledOnce() +}) + +it('keeps video display after an individual frame failure and reports it through onEvent', async () => { + const f = fixture() + const events: FrameRxEvent[] = [] + f.channel.onEvent(event => events.push(event)) + f.channel.mount(f.element, f.failure); await tick(); await tick() + const error = { kind: 'error', connectionId: 1 as FrameConnectionId, source: 'presentation', error: 'invalid-surface' } as const + f.event(error); await tick() + expect(f.element.getAttribute('data-dsh-frame-mount')).toBe('video') + expect(trackStops[0]).not.toHaveBeenCalled() + expect(events).toContainEqual(error) + expect(f.failure).not.toHaveBeenCalled() +}) +it('recreates the display when a snapshot skips draining and connects a replacement producer', async () => { + const f = fixture() + f.channel.mount(f.element, f.failure); f.visible(); await tick(); await tick() + f.event({ kind: 'state', channel: { state: 'connected', connectionId: 1 as FrameConnectionId, viewportVersion: 1 } }) + await tick() + expect(trackStops).toHaveLength(1) + f.event({ kind: 'state', channel: { state: 'connected', connectionId: 2 as FrameConnectionId } }) + expect(trackStops[0]).toHaveBeenCalledOnce() + f.visible(); await tick(); await tick() + expect(f.bridge.setViewport.mock.calls.map(([, viewport]) => viewport.visible)).toEqual([true, true]) + expect(trackStops).toHaveLength(2) + expect(f.element.getAttribute('data-dsh-frame-mount')).toBe('video') + expect(f.failure).not.toHaveBeenCalled() +}) +it('releases a previous-window video frame older than the submitted generation', async () => { + const f = fixture() + const events: FrameRxEvent[] = [] + f.channel.onEvent(event => events.push(event)) + f.channel.mount(f.element, f.failure); await tick() + f.channel.setContentView(contentView) + await f.channel.setContentWindow(contentWindow) + const previous = await f.channel.setContentWindow({ ...contentWindow, y: 100 }) + const current = await f.channel.setContentWindow({ ...contentWindow, y: 200 }) + const shown = f.frame().lease + f.arrive(shown); await tick() + expect(shown.metadata.generation).toBe(current.version) + const older = f.frame().lease; older.metadata.generation = previous.version + f.arrive(older); await tick() + expect(older.release).toHaveBeenCalledOnce() + expect(writer.write).toHaveBeenCalledOnce() + expect(events.filter(event => event.kind === 'content').at(-1)).toEqual({ kind: 'content', submittedGeneration: current.version }) +}) +it.each([new Error('play denied'), 'play denied'])('reports rejected playback: %s', async (error) => { + const f = fixture() + vi.spyOn(HTMLMediaElement.prototype, 'play').mockRejectedValueOnce(error) + const presenter = createMediaPresenter(f.element, f.failure, vi.fn()) + displays.add(presenter) + await tick() + expect(f.failure).toHaveBeenCalledWith(expect.objectContaining({ source: 'presentation', message: 'play denied' })) +}) + +it('observes only its own intersection and pauses a covered viewport', async () => { + const f = fixture() + f.channel.mount(f.element, f.failure) + intersected([{ target: f.slot, isIntersecting: true }]); await tick() + expect(f.bridge.setViewport.mock.calls.at(-1)?.[1].visible).toBe(false) + f.visible() + f.event({ kind: 'fullscreen', active: true, holder: false }); await tick() + expect(f.bridge.setViewport.mock.calls.at(-1)?.[1].visible).toBe(false) + f.event({ kind: 'fullscreen', active: true, holder: true }); await tick(); await tick() + expect(f.bridge.setViewport.mock.calls.at(-1)?.[1].visible).toBe(true) + expect(() => f.channel.setViewport({ version: 100, width: 1, height: 1, deviceScaleFactor: 1, visible: true })).toThrow('managed by mount') +}) + +it('reports video startup failure and releases the mount', async () => { + vi.stubGlobal('MediaStreamTrackGenerator', undefined) + const f = fixture() + f.channel.mount(f.element, f.failure); await tick() + expect(f.failure).toHaveBeenCalledWith(expect.objectContaining({ source: 'presentation' })) + expect(f.element.hasAttribute('data-dsh-frame-mount')).toBe(false) +}) + +it('ignores a rejected viewport whose display was disposed before the rejection was delivered', async () => { + const f = fixture() + const { mount, owner } = directMount(f.element) + const error = new Error('viewport failed') + owner.viewport.mockImplementationOnce(() => { throw error }) + const request = mount.requestViewport() + mount.dispose() + await expect(request).rejects.toBe(error) + expect(owner.failure).not.toHaveBeenCalled() +}) + +it('keeps an idle channel available for a producer and ignores a cancelled track write during unmount', async () => { + const f = fixture() + f.event({ kind: 'state', channel: { state: 'idle' } }) + const unmount = f.channel.mount(f.element, f.failure) + f.event({ kind: 'state', channel: { state: 'connected', connectionId: 2 as FrameConnectionId } }) + await tick() + const pending = Promise.withResolvers() + writer.write.mockReturnValueOnce(pending.promise) + const { lease } = f.frame() + lease.metadata.connectionId = 2 as FrameConnectionId + f.arrive(lease) + expect(writer.write).toHaveBeenCalledOnce() + unmount() + pending.reject(new Error('track stopped')) + await tick() + expect(lease.release).toHaveBeenCalledOnce() + expect(f.failure).not.toHaveBeenCalled() +}) + +it('updates visibility when the mount is trimmed or its docked or floating pane is hidden', async () => { + const f = fixture() + f.channel.mount(f.element, f.failure) + f.visible(); await tick(); await tick() + const visible = () => f.bridge.setViewport.mock.calls.at(-1)?.[1].visible + expect(visible()).toBe(true) + f.element.style.visibility = 'hidden'; await tick(); await tick() + expect(visible()).toBe(false) + f.element.style.visibility = ''; await tick(); await tick() + expect(visible()).toBe(true) + f.slot.appendChild(document.createTextNode('unrelated sibling')).remove() + await tick(); await tick() + const float = document.body.appendChild(document.createElement('div')) + float.append(f.slot); float.hidden = true; await tick(); await tick() + expect(visible()).toBe(false) + float.hidden = false; await tick(); await tick() + expect(visible()).toBe(true) +}) diff --git a/packages/experimental/frame-forwarding/tests/event-backlog-native.e2e.ts b/packages/experimental/frame-forwarding/tests/event-backlog-native.e2e.ts new file mode 100644 index 0000000000..660ea93e63 --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/event-backlog-native.e2e.ts @@ -0,0 +1,274 @@ +/** + * Pending-event limit of the built receiver. One connection may have at most 256 producer events (messages, + * presentation errors and frames for JavaScript) awaiting the JavaScript thread. A connection that exceeds it ends + * with one `disconnected` carrying the reason, after the events already queued, and then one `drained` once its frames + * are released; the channel stays open for a successor. Lifecycle notices take no quota, and refusals coalesce to one + * pending `rejected` event. On Windows, valid producers keep connecting while other processes present a wrong + * credential. + * + * Each case stalls the JavaScript thread with `Atomics.wait` inside a receiver callback, so native threads queue events + * that nothing dispatches, and ends the stall on a producer's signal file rather than after a fixed time. + * + * Prerequisites: build the addon with `pnpm --filter @deepseek-ai/dsh-desktop run build:native`, on Windows + * from a Visual Studio x64 developer environment (vcvarsall); on macOS the Xcode command line tools provide clang++. + * The suite compiles its producer with the same toolchain and skips itself when the addon is missing. + */ +import type { SharedTextureNativeSink, SharedTextureService } from '@deepseek-ai/dsh-shared-texture' +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' +import { FrameForwarder } from '../src/host/forwarder.ts' +import type { FrameForwardingReceiver } from '../src/host/native.ts' +import type { FrameChannelState, FrameConnectionId, FrameForwardingEvent } from '../src/types.ts' +import { + blockUntil, corruptTx, createChannel, killProducers, nativeSupported, ofConnection, pendingLimit, pendingLimitText, sequence, + setupHarness, signalled, signalPrefix, startProducer, teardownHarness, within, + type Channel, type ChannelOptions, type Event, type Harness, type Producer, +} from './backlog-harness.ts' + +const connection = (value: number) => value as FrameConnectionId +const range = (length: number) => Array.from({ length }, (_, index) => index) +const types = (events: readonly Event[]) => events.map(event => event.type) +const indexOf = (events: readonly Event[], type: Event['type'], connectionId: number) => + events.findIndex(event => event.type === type && 'connectionId' in event && event.connectionId === connectionId) + +describe.skipIf(!nativeSupported)('pending-event limit of the built frame-forwarding receiver', () => { + let harness: Harness | undefined + const receivers: FrameForwardingReceiver[] = [] + beforeAll(async () => { harness = await setupHarness() }, 180_000) + afterEach(async () => { + await Promise.all(receivers.splice(0).map(async receiver => within(receiver.close(), 10_000))) + if (harness) await killProducers(harness) + }, 30_000) + afterAll(async () => { await teardownHarness(harness) }, 30_000) + + function open(hook?: (event: Event, receiver: FrameForwardingReceiver) => void, options?: ChannelOptions): Channel { + const channel = createChannel(harness!, hook, options) + receivers.push(channel.receiver) + return channel + } + + /** + * Send `messages` control messages while JavaScript stays blocked in the first `connected` callback. A successor + * started there retries while the first connection is current, so its connection ends the stall only after the + * receiver ended and drained the first one. The successor then sends three messages and leaves when asked. + */ + async function stalledFlood(messages: number, after: 'goodbye' | 'hold') { + const h = harness! + const successorSignal = signalPrefix(h) + let successor: Producer | undefined + let stalled: boolean | undefined + const channel = open((event, receiver) => { + if (event.type === 'connected') { + receiver.send(event.connectionId, 'go') + if (event.connectionId !== 1) return + successor = startProducer(h, receiver.tx, 'produce', { + messages: 3, 'wait-go': 1, after: 'hold', 'hold-ms': 30_000, 'retry-busy': 1, signal: successorSignal, + }) + stalled = blockUntil(() => signalled(successorSignal, 'connected') || signalled(successorSignal, 'connect-failed'), 30_000) + } else if (event.type === 'message' && event.connectionId === 2 && sequence([event])[0] === 2) { + receiver.send(event.connectionId, 'exit') + } + }) + const main = startProducer(h, channel.receiver.tx, 'produce', { messages, 'wait-go': 1, after, 'hold-ms': 30_000 }) + await channel.waitFor('the successor to drain', + events => indexOf(events, 'drained', 2) >= 0 || events.some(event => event.type === 'failed'), 60_000) + return { channel, main, successor: successor!, stalled } + } + + /** The successor of `stalledFlood` exchanged its messages and left normally after the first connection drained. */ + async function expectSuccessor(channel: Channel, successor: Producer) { + await successor.exited + expect(successor.line('connected'), successor.lines.join('\n')).toBeDefined() + const second = ofConnection(channel.events, 2) + expect(types(second)).toEqual(['connected', 'message', 'message', 'message', 'disconnected', 'drained']) + expect(sequence(second)).toEqual([0, 1, 2]) + expect(second.at(-2)).toEqual({ type: 'disconnected', connectionId: 2 }) + expect(indexOf(channel.events, 'drained', 1)).toBeLessThan(indexOf(channel.events, 'connected', 2)) + // The successor's busy refusals all happened during the stall, so at most one was pending. + const rejected = channel.events.filter(event => event.type === 'rejected') + expect(rejected.length).toBeLessThanOrEqual(1) + for (const event of rejected) expect(event).toEqual({ type: 'rejected', text: 'channel-busy' }) + expect(channel.count('failed')).toBe(0) + } + + it.each([200, pendingLimit])('delivers %i messages queued behind a stalled JavaScript thread and ends the connection without a reason', async (messages) => { + const { channel, main, successor, stalled } = await stalledFlood(messages, 'goodbye') + expect(stalled, successor.lines.join('\n')).toBe(true) + const first = ofConnection(channel.events, 1) + expect(types(first)).toEqual(['connected', ...Array(messages).fill('message'), 'disconnected', 'drained']) + expect(sequence(first)).toEqual(range(messages)) + expect(first.at(-2)).toEqual({ type: 'disconnected', connectionId: 1 }) + expect(await main.waitLine(['sent'], 10_000)).toBe(`sent ok=${String(messages)} failed=0`) + await expectSuccessor(channel, successor) + }) + + it.each([pendingLimit + 1, 2000])('ends a connection whose %i messages exceed the limit after delivering the first 256, and admits a successor', async (messages) => { + const { channel, main, successor, stalled } = await stalledFlood(messages, 'hold') + expect(stalled, successor.lines.join('\n')).toBe(true) + const first = ofConnection(channel.events, 1) + expect(types(first)).toEqual(['connected', ...Array(pendingLimit).fill('message'), 'disconnected', 'drained']) + expect(sequence(first)).toEqual(range(pendingLimit)) + expect(first.at(-2)).toEqual({ type: 'disconnected', connectionId: 1, text: pendingLimitText }) + // The receiver ended the producer's connection; the producer did not leave on its own. + expect(await main.waitLine(['closed', 'hold-timeout'], 10_000)).toMatch(/^closed\b/u) + expect(() => { channel.receiver.send(connection(1), 'exit') }).toThrow('Frame-forwarding connection is not active') + await expectSuccessor(channel, successor) + }) + + it('sends drained for a connection ended at the limit only after JavaScript releases its frame', async () => { + const h = harness! + const signal = signalPrefix(h) + let held: Extract | undefined + let stalled: boolean | undefined + // The frame was dispatched before the flood started and JavaScript still holds it, so drained waits for its release. + // Its event keeps a queue slot until the callback that blocked returns, so 255 messages fit. + const channel = open((event, receiver) => { + if (event.type !== 'frame') return + held = event + receiver.send(event.connectionId, 'go') + stalled = blockUntil(() => signalled(signal, 'closed'), 30_000) + }, { releaseFrames: false }) + startProducer(h, channel.receiver.tx, 'produce', { + frames: 1, 'frames-first': 1, 'wait-go': 1, messages: 2000, after: 'hold', 'hold-ms': 30_000, signal, + }) + await channel.waitFor('the disconnect', events => events.some(event => event.type === 'disconnected'), 30_000) + expect(stalled).toBe(true) + expect(types(channel.events)).toEqual(['connected', 'frame', ...Array(pendingLimit - 1).fill('message'), 'disconnected']) + expect(channel.events.at(-1)).toEqual({ type: 'disconnected', connectionId: 1, text: pendingLimitText }) + expect(channel.receiver.release(held!.deliveryId)).toBe(true) + await channel.waitFor('the drain', events => events.some(event => event.type === 'drained'), 10_000) + expect(channel.events.slice(-1)).toEqual([{ type: 'drained', connectionId: 1 }]) + expect(channel.count('failed')).toBe(0) + }) + + it('keeps a FrameForwarder channel open through draining to idle after a connection exceeds the limit, then reconnects', async () => { + const h = harness! + const successorSignal = signalPrefix(h) + const states: FrameChannelState[] = [] + const warnings: string[] = [] + let stalled: boolean | undefined + const service = { + capabilities: async () => ({ supported: true }), + adapterLuid: async () => h.displayAdapter, + nativeSink: async () => h.fakes.create().sink as SharedTextureNativeSink, + } satisfies SharedTextureService + const forwarder = new FrameForwarder(service, () => ({ + ...h.bindings, + createReceiver(options, listener) { + const receiver = h.bindings.createReceiver(options, (event) => { + listener(event) + if (event.type !== 'connected' || event.connectionId !== 1) return + receiver.send(event.connectionId, 'go') + startProducer(h, receiver.tx, 'produce', { 'retry-busy': 1, after: 'hold', 'hold-ms': 30_000, signal: successorSignal }) + stalled = blockUntil(() => signalled(successorSignal, 'connected') || signalled(successorSignal, 'connect-failed'), 30_000) + }) + return receiver + }, + }), { maxFrames: 2, maxBytes: () => 1 << 20, requestTimeoutMs: 5000, maxPendingRequests: 8 }, { + event: (event: Exclude) => { if (event.kind === 'state') states.push(event.channel) }, + warn: (message) => { warnings.push(message) }, + }) + try { + const channel = await forwarder.channel() + const main = startProducer(h, channel.tx, 'produce', { messages: 2000, 'wait-go': 1, after: 'hold', 'hold-ms': 30_000 }) + await vi.waitFor(() => { + expect(states.some(state => (state.state === 'connected' && state.connectionId === 2) || state.state === 'closed')).toBe(true) + }, { timeout: 60_000, interval: 20 }) + expect(stalled).toBe(true) + expect(states).toEqual([ + { state: 'idle' }, { state: 'connected', connectionId: 1 }, { state: 'draining', connectionId: 1 }, { state: 'idle' }, + { state: 'connected', connectionId: 2 }, + ]) + expect(forwarder.isOpen(channel.rx)).toBe(true) + expect(forwarder.snapshot().map(entry => entry.channel)).toEqual([{ state: 'connected', connectionId: 2 }]) + expect(warnings).toContain(`Native producer 1 disconnected: ${pendingLimitText}`) + expect(await main.waitLine(['closed', 'hold-timeout'], 10_000)).toMatch(/^closed\b/u) + } finally { + expect(await within(forwarder.closeAll().then(() => 'closed' as const), 10_000)).toBe('closed') + } + }) + + it('coalesces credential refusals made while JavaScript is blocked into one rejected event, then admits a producer', async () => { + const h = harness! + const channel = open() + const bad = corruptTx(channel.receiver.tx) + const signals = [signalPrefix(h), signalPrefix(h)] + const refusers = signals.map(signal => startProducer(h, bad, 'refuse', { count: 40, 'max-ms': 30_000, signal })) + // Nothing is dispatched between starting the refusers and blocking, so every refusal happens during the stall. The + // receiver admits candidates one at a time, so the producer connects only after every refusal was queued. + const refused = blockUntil(() => signals.every(signal => signalled(signal, 'refused') || signalled(signal, 'device-failed')), 45_000) + const producerSignal = signalPrefix(h) + startProducer(h, channel.receiver.tx, 'produce', { after: 'goodbye', signal: producerSignal }) + const admitted = blockUntil(() => signalled(producerSignal, 'connected') || signalled(producerSignal, 'connect-failed'), 30_000) + expect({ refused, admitted }).toEqual({ refused: true, admitted: true }) + await Promise.all(refusers.map(async refuser => refuser.exited)) + for (const refuser of refusers) expect(refuser.line('refused')).toMatch(/^refused credential=40 other=0 accepted=0\b/u) + await channel.waitFor('the producer to drain', events => events.some(event => event.type === 'drained'), 30_000) + expect(channel.events).toEqual([ + { type: 'rejected', text: 'invalid-credential' }, + { type: 'connected', connectionId: 1, pid: expect.any(Number) as number }, + { type: 'disconnected', connectionId: 1 }, + { type: 'drained', connectionId: 1 }, + ]) + }) + + it('delivers between one and N rejected events for N refusals while JavaScript keeps dispatching', async () => { + const h = harness! + const channel = open() + const refuser = startProducer(h, corruptTx(channel.receiver.tx), 'refuse', { count: 20, 'max-ms': 30_000 }) + await refuser.exited + expect(refuser.line('refused')).toMatch(/^refused credential=20 other=0 accepted=0\b/u) + startProducer(h, channel.receiver.tx, 'produce', { after: 'goodbye' }) + await channel.waitFor('the producer to drain', events => events.some(event => event.type === 'drained'), 30_000) + // Every refusal was queued before the producer connected, so its rejected events all come first. + const rejected = channel.events.filter(event => event.type === 'rejected') + expect(rejected.length).toBeGreaterThanOrEqual(1) + expect(rejected.length).toBeLessThanOrEqual(20) + expect(new Set(rejected.map(event => event.text))).toEqual(new Set(['invalid-credential'])) + expect(types(channel.events.slice(rejected.length))).toEqual(['connected', 'disconnected', 'drained']) + }) + + it.each([ + { messages: 2000, barrier: 'closed' }, + { messages: 200, barrier: 'sent' }, + ])('closes promptly while JavaScript has not dispatched the events of $messages messages', async ({ messages, barrier }) => { + const h = harness! + const signal = signalPrefix(h) + let stalled: boolean | undefined + let closing: Promise | undefined + const channel = open((event, receiver) => { + if (event.type !== 'connected') return + receiver.send(event.connectionId, 'go') + // With 2000 messages the receiver has already ended the connection; with 200 it is still current. + stalled = blockUntil(() => signalled(signal, barrier), 30_000) + closing = receiver.close() + }) + const producer = startProducer(h, channel.receiver.tx, 'produce', { messages, 'wait-go': 1, after: 'hold', 'hold-ms': 30_000, signal }) + await channel.waitFor('the connection', events => events.some(event => event.type === 'connected'), 30_000) + expect(stalled).toBe(true) + expect(await within(closing!.then(() => 'closed' as const), 10_000)).toBe('closed') + expect(await producer.waitLine(['closed', 'hold-timeout'], 10_000)).toMatch(/^closed\b/u) + const first = ofConnection(channel.events, 1) + expect(sequence(first)).toEqual(range(sequence(first).length)) + expect(channel.count('failed')).toBe(0) + expect(channel.count('disconnected')).toBeLessThanOrEqual(1) + }) + + it.runIf(process.platform === 'win32')('connects valid producers, or refuses them as busy, while other processes keep presenting a wrong credential', async () => { + const h = harness! + const channel = open() + const bad = corruptTx(channel.receiver.tx) + const refusers = [0, 1].map(() => startProducer(h, bad, 'refuse', { count: 0, 'max-ms': 150_000 })) + for (const refuser of refusers) expect(await refuser.waitLine(['refusing', 'refused', 'device-failed'], 30_000)).toBe('refusing') + const outcomes: string[] = [] + for (let round = 0; round < 20; round++) { + const probe = startProducer(h, channel.receiver.tx, 'produce', { after: 'goodbye' }) + await probe.exited + outcomes.push(probe.lines[0] ?? `no output: ${probe.stderr()}`) + } + // Both refusers were still presenting the wrong credential when the last probe finished. + expect(refusers.map(refuser => refuser.child.exitCode)).toEqual([null, null]) + expect(outcomes.filter(outcome => !/^connected\b/u.test(outcome) && !outcome.startsWith('connect-failed channel-busy'))).toEqual([]) + expect(outcomes.some(outcome => /^connected\b/u.test(outcome))).toBe(true) + expect(channel.count('failed')).toBe(0) + }, 240_000) +}) diff --git a/packages/experimental/frame-forwarding/tests/event-backlog-stress.e2e.ts b/packages/experimental/frame-forwarding/tests/event-backlog-stress.e2e.ts new file mode 100644 index 0000000000..3565888c69 --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/event-backlog-stress.e2e.ts @@ -0,0 +1,312 @@ +/** + * Seeded stress of the built receiver's pending-event limit. Each case varies message count and length, JavaScript + * stalls, wrong-credential connections, how the producer leaves, when a successor arrives, when the channel closes, + * and whether frames are submitted, then checks the channel invariants: + * + * - no case hangs and `close()` settles within 10 s; no channel reports `failed`; + * - each connection gets exactly one `disconnected` and one `drained`, in that order and after its producer events, so + * no connection and no channel ends silently; a channel closed early still disconnects every connection and drains + * each connection that held no frames; + * - messages of one connection arrive once each and in order, and all of them when the connection ended without a + * reason; a connection the receiver ended carries the reason; + * - while the channel is open, valid producers connect or are refused as `channel-busy`, never as unavailable, and a + * later producer connects; + * - `rejected` events number at least one and at most the refusals made; + * - the shared byte budget returns in full, so a fresh receiver on it still presents a frame. + * + * The suite is skipped unless `DSH_FRAME_FORWARDING_STRESS=1`. Further variables: + * - `DSH_FRAME_FORWARDING_STRESS_CASES`: number of cases, default 40; + * - `DSH_FRAME_FORWARDING_STRESS_SEED`: base seed, default random; case i uses `(seed + i * 7919) >>> 0`; + * - `DSH_FRAME_FORWARDING_STRESS_SEEDS`: comma-separated case seeds to replay instead; + * - `DSH_FRAME_FORWARDING_STRESS_MINUTES`: start no case after this many minutes, default 15. + * Each case logs its seed and parameters when it starts and is named after its seed; replay a failure with + * `DSH_FRAME_FORWARDING_STRESS_SEEDS=`. + * + * Prerequisites match `event-backlog-native.e2e.ts`: build the addon with + * `pnpm --filter @deepseek-ai/dsh-desktop run build:native`, on Windows from a Visual Studio x64 developer + * environment (vcvarsall); on macOS the Xcode command line tools provide clang++. + */ +import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest' +import type { FrameForwardingBudget, FrameForwardingReceiver } from '../src/host/native.ts' +import { + blockFor, corruptTx, createChannel, killProducers, nativeSupported, ofConnection, pendingLimitText, sequence, setupHarness, + startProducer, summarize, teardownHarness, within, type Channel, type ChannelOptions, type Event, type Harness, type Producer, +} from './backlog-harness.ts' + +function integer(name: string, fallback: number): number { + const raw = process.env[name] + if (raw === undefined || raw === '') return fallback + const value = Number(raw) + if (!Number.isSafeInteger(value) || value < 0) throw new Error(`${name} must be a non-negative integer, got ${JSON.stringify(raw)}`) + return value +} + +const enabled = process.env.DSH_FRAME_FORWARDING_STRESS === '1' +const baseSeed = enabled ? integer('DSH_FRAME_FORWARDING_STRESS_SEED', Math.floor(Math.random() * 2 ** 31)) : 0 +const replay = process.env.DSH_FRAME_FORWARDING_STRESS_SEEDS?.split(',').map(seed => seed.trim()).filter(Boolean).map((seed) => { + const value = Number(seed) + if (!Number.isSafeInteger(value) || value < 0) throw new Error(`DSH_FRAME_FORWARDING_STRESS_SEEDS has an invalid seed ${JSON.stringify(seed)}`) + return value >>> 0 +}) +// A disabled run keeps one skipped case, since a file without tests fails the run. +const seeds = enabled + ? replay ?? Array.from({ length: integer('DSH_FRAME_FORWARDING_STRESS_CASES', 40) }, (_, index) => (baseSeed + index * 7919) >>> 0) + : [0] +const budgetMs = (enabled ? integer('DSH_FRAME_FORWARDING_STRESS_MINUTES', 15) : 0) * 60_000 + +function mulberry32(seed: number): () => number { + let state = seed >>> 0 + return () => { + state = (state + 0x6D2B79F5) >>> 0 + let value = Math.imul(state ^ (state >>> 15), 1 | state) + value = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value + return ((value ^ (value >>> 14)) >>> 0) / 4294967296 + } +} + +type End = 'hold' | 'goodbye' | 'crash' | 'kill' +type CloseAt = 'after' | 'connected' | 'during' +interface Params { + messages: number + length: number + /** Stall inside the first `connected` callback. */ + blockOnConnected: number + /** Stall inside the callback of one flooded message. */ + blockAtMessage: { seq: number; ms: number } | null + /** Stalls from timers, `at` ms after the case starts. */ + timedBlocks: { at: number; ms: number }[] + refusals: number + refusers: number + end: End + holdMs: number + killAt: number + /** -1 for no successor. */ + successorAt: number + closeAt: CloseAt + closeDelay: number + frames: number +} + +function params(seed: number): Params { + const random = mulberry32(seed) + const pick = (values: readonly T[]): T => values[Math.floor(random() * values.length)]! + const messages = pick([0, 10, 200, 255, 256, 257, 400, 1000, 3000, 20000]) + let length = pick([16, 64, 1024, 8000, 16000]) + // Keep one case's traffic below 40 MB. + while (messages * length > 40e6) length = Math.floor(length / 2) + const blockOnConnected = pick([0, 0, 0, 50, 300, 1500]) + const blockAtMessage = pick([false, false, true]) ? { seq: pick([0, 100, 255]), ms: pick([100, 500, 1500]) } : null + const timedBlocks = Array.from({ length: pick([0, 0, 1, 2, 3]) }, () => ({ + at: Math.floor(random() * 1500), ms: pick([20, 100, 500, 1500]), + })) + const refusals = pick([0, 0, 0, 50, 300]) + return { + messages, length, blockOnConnected, blockAtMessage, timedBlocks, refusals, refusers: refusals ? pick([1, 2]) : 0, + end: pick(['hold', 'goodbye', 'crash', 'kill'] as const), holdMs: 500 + Math.floor(random() * 2500), killAt: Math.floor(random() * 1500), + successorAt: pick([-1, 0, 300, 1000, 2500]), closeAt: pick(['after', 'after', 'after', 'connected', 'during'] as const), + closeDelay: Math.floor(random() * 500), frames: pick([0, 0, 2, 5]), + } +} + +interface Violation { kind: string; detail?: unknown } + +const connectionIds = (events: readonly Event[]) => events.flatMap(event => (event.type === 'connected' ? [event.connectionId as number] : [])) +const has = (events: readonly Event[], type: Event['type'], id: number) => ofConnection(events, id).some(event => event.type === type) +const unavailable = (producer: Producer | undefined) => producer?.lines.some(line => line.includes('receiver unavailable')) ?? false +/** A valid producer connected, or was refused because another producer held the channel. */ +const admittedOrBusy = (producer: Producer) => producer.line('connected') !== undefined || producer.line('connect-failed')?.startsWith('connect-failed channel-busy') === true + +describe.skipIf(!enabled || !nativeSupported)('seeded stress of the receiver pending-event limit', { retry: 0 }, () => { + let harness: Harness | undefined + /** The smallest budget with which a receiver of maxFrames 1 still presents a 64x64 frame, so a leak blocks the next. */ + let tightBudget = 0 + let started = 0 + let hung: number | undefined + const receivers: FrameForwardingReceiver[] = [] + beforeAll(async () => { + harness = await setupHarness() + for (const bytes of [16384, 32768, 65536, 131072, 262144, 524288, 1048576]) { + if ((await framesFlow(harness.bindings.createBudget(bytes), bytes)).ok) { tightBudget = bytes; break } + } + expect(tightBudget, 'no budget up to 1 MiB presented a frame').toBeGreaterThan(0) + console.log(`[frame-forwarding stress] base seed ${String(baseSeed)}, ${String(seeds.length)} cases, tight budget ${String(tightBudget)} bytes`) + started = performance.now() + }, 300_000) + afterEach(async () => { + await Promise.all(receivers.splice(0).map(async receiver => within(receiver.close(), 10_000))) + if (harness) await killProducers(harness) + }, 30_000) + afterAll(async () => { await teardownHarness(harness) }, 30_000) + + function open(hook: Parameters[1], options: ChannelOptions): Channel { + const channel = createChannel(harness!, hook, options) + receivers.push(channel.receiver) + return channel + } + + /** Whether a fresh receiver on `budget` presents one frame of a new producer. */ + async function framesFlow(budget: FrameForwardingBudget, maxBytes: number): Promise<{ ok: boolean; detail: string }> { + const channel = createChannel(harness!, undefined, { maxFrames: 1, maxBytes, budget }) + // A producer that leaves at once loses a frame the receiver has not delivered, so this one holds until asked to exit. + const producer = startProducer(harness!, channel.receiver.tx, 'produce', { frames: 1, after: 'hold', 'hold-ms': 8000 }) + try { + await channel.waitFor('the frame check frame', events => events.some(event => event.type === 'frame'), 6_000) + const connected = channel.events.find(event => event.type === 'connected') + if (connected?.type === 'connected') channel.receiver.send(connected.connectionId, 'exit') + await within(producer.exited, 15_000) + await channel.waitFor('the frame check to drain', events => events.some(event => event.type === 'drained'), 10_000) + return { ok: channel.count('frame') === 1, detail: `${producer.lines.join(' | ')}; ${summarize(channel.events)}` } + } catch (error) { + return { ok: false, detail: `${(error as Error).message}; ${producer.lines.join(' | ')}` } + } finally { + await within(channel.receiver.close(), 10_000) + await producer.kill() + } + } + + async function runCase(p: Params): Promise<{ violations: Violation[]; events: Event[] }> { + const h = harness! + const violations: Violation[] = [] + const add = (kind: string, detail?: unknown) => { violations.push({ kind, detail }) } + const maxBytes = p.frames > 0 ? tightBudget : 1 << 20 + const budget = h.bindings.createBudget(maxBytes) + let closing: Promise | undefined + let stalledOnConnect = false + const channel = open((event, receiver) => { + if (event.type === 'connected') { + // The successor can connect first; it ignores "go". + try { + receiver.send(event.connectionId, 'go') + } catch (_connectionEnded) { + // A connection that already ended refuses the send, and its disconnected event still follows. + } + if (stalledOnConnect) return + stalledOnConnect = true + blockFor(p.blockOnConnected) + if (p.closeAt === 'connected') closing ??= receiver.close() + } else if (event.type === 'message' && p.blockAtMessage && sequence([event])[0] === p.blockAtMessage.seq) { + blockFor(p.blockAtMessage.ms) + } + }, { maxFrames: 1, maxBytes, budget }) + const { receiver, events } = channel + const timers: ReturnType[] = [] + const later = (ms: number, action: () => void) => { timers.push(setTimeout(action, ms)) } + const refusers = Array.from({ length: p.refusers }, () => startProducer(h, corruptTx(receiver.tx), 'refuse', { + count: Math.ceil(p.refusals / p.refusers), 'max-ms': 8000, + })) + const main = startProducer(h, receiver.tx, 'produce', { + messages: p.messages, length: p.length, 'wait-go': 1, after: p.end === 'kill' ? 'hold' : p.end, 'hold-ms': p.holdMs, frames: p.frames, + }) + for (const timed of p.timedBlocks) later(timed.at, () => { blockFor(timed.ms) }) + if (p.end === 'kill') later(p.killAt, () => { main.child.kill('SIGKILL') }) + if (p.closeAt === 'during') later(300 + p.closeDelay, () => { closing ??= receiver.close() }) + let successor: Producer | undefined + const successorStarted = new Promise((resolve) => { + if (p.successorAt < 0) { resolve(); return } + later(p.successorAt, () => { + successor = startProducer(h, receiver.tx, 'produce', { after: 'hold', 'hold-ms': 300, frames: p.frames > 0 ? 1 : 0 }) + resolve() + }) + }) + if (await within(main.exited, 30_000) === 'timeout') add('producer-hang', main.lines) + for (const refuser of refusers) if (await within(refuser.exited, 20_000) === 'timeout') add('refuser-hang', refuser.lines) + await successorStarted + if (successor && await within(successor.exited, 20_000) === 'timeout') add('successor-hang', successor.lines) + for (const timer of timers) clearTimeout(timer) + + const closedEarly = closing !== undefined + const legit = [main, successor].filter((producer): producer is Producer => producer !== undefined) + let probe: Producer | undefined + if (!closedEarly) { + const reported = legit.filter(producer => producer.line('connected') !== undefined).length + // Every connection a producer reported is known to JavaScript and drained before the probe connects. + const settled = (list: readonly Event[]) => connectionIds(list).length >= reported && connectionIds(list).every(id => has(list, 'drained', id)) + await channel.waitFor('every connection to drain', settled, 20_000).catch((error: unknown) => { add('missing-drained', (error as Error).message) }) + const before = connectionIds(events).length + probe = startProducer(h, receiver.tx, 'produce', { after: 'goodbye' }) + if (await within(probe.exited, 20_000) === 'timeout') add('probe-hang', probe.lines) + if (probe.line('connected') === undefined) add('probe-refused', probe.lines) + else { + await channel.waitFor('the probe to drain', list => connectionIds(list).length > before && settled(list), 20_000) + .catch((error: unknown) => { add('probe-not-drained', (error as Error).message) }) + } + } + closing ??= receiver.close() + const closeStarted = performance.now() + if (await within(closing, 10_000) === 'timeout') add('close-timeout', Math.round(performance.now() - closeStarted)) + else if (closedEarly) { + // Events queued before the close are still dispatched, possibly after close settles. + const ended = (list: readonly Event[]) => connectionIds(list).every(id => has(list, 'disconnected', id) && (p.frames > 0 || has(list, 'drained', id))) + await channel.waitFor('every connection to end after close', ended, 10_000) + .catch((error: unknown) => { add('missing-terminal-after-close', (error as Error).message) }) + } + + // Per-connection order, uniqueness and message sequence. + const pidOf = new Map(events.flatMap(event => (event.type === 'connected' ? [[event.connectionId as number, event.pid] as const] : []))) + for (const id of connectionIds(events)) { + const own = ofConnection(events, id) + const types = own.map(event => event.type) + if (types[0] !== 'connected' || types.lastIndexOf('connected') !== 0) add('connected-order', { id, types: summarize(own) }) + const disconnected = types.filter(type => type === 'disconnected').length, drained = types.filter(type => type === 'drained').length + if (disconnected > 1 || drained > 1) add('duplicate-terminal', { id, disconnected, drained }) + if (!closedEarly && (disconnected !== 1 || drained !== 1)) add('missing-terminal', { id, disconnected, drained }) + if (drained === 1 && types.at(-1) !== 'drained') add('event-after-drained', { id, types: summarize(own) }) + const ending = types.indexOf('disconnected') + if (drained === 1 && (ending < 0 || types.indexOf('drained') < ending)) add('drained-before-disconnected', { id }) + if (ending >= 0 && types.slice(ending).some(type => type === 'message' || type === 'frame' || type === 'presentation-error')) + add('producer-event-after-disconnected', { id, types: summarize(own) }) + const seqs = sequence(own) + const bad = seqs.findIndex((seq, index) => seq !== index) + if (bad >= 0) add('message-order', { id, index: bad, seq: seqs[bad] }) + const text = own.find(event => event.type === 'disconnected')?.text + if (text === pendingLimitText && pidOf.get(id) !== main.child.pid) add('overflow-without-flood', { id }) + } + if (channel.count('failed') > 0) add('failed', events.filter(event => event.type === 'failed')) + + if (!closedEarly) { + const mainId = [...pidOf].find(([, pid]) => pid === main.child.pid)?.[0] + const mainEvents = mainId === undefined ? [] : ofConnection(events, mainId) + const mainText = mainEvents.find(event => event.type === 'disconnected')?.text + for (const producer of [...legit, probe]) if (unavailable(producer)) add('receiver-unavailable', producer!.lines) + const killedEarly = p.end === 'kill' && main.lines.length === 0 + if (!killedEarly && !admittedOrBusy(main)) add('main-refused', main.lines) + if (successor && !admittedOrBusy(successor)) add('successor-refused', successor.lines) + if (main.line('connected') !== undefined && mainId === undefined) add('missing-connected', main.lines) + // The receiver ends a connection only with a reason; a clean end delivers every message sent. + if (main.line('closed') !== undefined && mainText === undefined) add('closed-without-reason', main.line('closed')) + const sent = /^sent ok=(\d+)/u.exec(main.line('sent') ?? '') + if (mainId !== undefined && mainText === undefined && (p.end === 'hold' || p.end === 'goodbye') && sent && sequence(mainEvents).length !== Number(sent[1])) + add('lost-messages', { sent: Number(sent[1]), received: sequence(mainEvents).length }) + const frames = /^frames submitted=(\d+) failure=(.*)$/u.exec(main.line('frames') ?? '') + const plannedStall = p.blockOnConnected + (p.blockAtMessage?.ms ?? 0) + p.timedBlocks.reduce((total, block) => total + block.ms, 0) + if (frames && mainText === undefined && (frames[2] !== '' || (Number(frames[1]) < p.frames && plannedStall <= 2000))) + add('frames-stalled', main.line('frames')) + // Each refusal queues at most one rejected event, and a pending one is always delivered. + const counts = refusers.map(refuser => /credential=(\d+) other=(\d+)/u.exec(refuser.line('refused') ?? '')) + const credential = counts.reduce((total, match) => total + Number(match?.[1] ?? 0), 0) + const refusals = credential + counts.reduce((total, match) => total + Number(match?.[2] ?? 0), 0) + + [...legit, probe].filter(producer => producer?.line('connect-failed') !== undefined).length + const rejected = channel.count('rejected') + if (rejected > refusals || (credential > 0 && rejected === 0)) add('rejected-count', { rejected, refusals, credential }) + } + if (p.frames > 0 && violations.every(violation => violation.kind !== 'close-timeout')) { + const check = await framesFlow(budget, maxBytes) + if (!check.ok) add('budget-not-returned', check.detail) + } + return { violations, events } + } + + it.for(seeds)('keeps channel invariants for seed %i', { timeout: 150_000 }, async (seed, { skip }) => { + if (hung !== undefined) skip(`seed ${String(hung)} hung, and its producers or receiver may still be running`) + if (performance.now() - started > budgetMs) skip('the stress time budget is spent') + const p = params(seed) + console.log(`[frame-forwarding stress] seed ${String(seed)} ${JSON.stringify(p)}`) + const outcome = await within(runCase(p), 120_000) + if (outcome === 'timeout') { + hung = seed + expect.fail(`seed ${String(seed)} did not finish within 120 s; replay with DSH_FRAME_FORWARDING_STRESS_SEEDS=${String(seed)}`) + } + expect(outcome.violations, `seed ${String(seed)} ${JSON.stringify(p)}; events: ${summarize(outcome.events)}; ` + + `replay with DSH_FRAME_FORWARDING_STRESS=1 DSH_FRAME_FORWARDING_STRESS_SEEDS=${String(seed)}`).toEqual([]) + }) +}) diff --git a/packages/experimental/frame-forwarding/tests/fake-sink.ts b/packages/experimental/frame-forwarding/tests/fake-sink.ts new file mode 100644 index 0000000000..83e1504bec --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/fake-sink.ts @@ -0,0 +1,95 @@ +/** + * Builds and loads `fixtures/fake-sink.cc`, a stand-in for Desktop's shared-texture hop sink that native tests attach + * to the built receiver, with the host toolchain: MSVC's developer environment on Windows, clang++ on macOS. + */ +import { spawnSync } from 'node:child_process' +import { createRequire } from 'node:module' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { expect } from 'vitest' +import { nativeBuildEnvironment } from '../../../../apps/desktop/scripts/native-package-builds.mjs' + +/** One presentation the fake sink accepted. */ +export interface FakePresented { + /** Identifier the fake assigned: the presentation's position among accepted ones, from "1". */ + id: string + metadata: string + /** Eight-byte Host-local handle, valid until the presentation settles. */ + handle: Buffer + width: number + height: number + timeoutMs: number + pixelFormat: number +} + +/** Exports of the fake sink addon; `native` identifies one sink to the other operations. */ +export interface FakeSinkAddon { + /** A sink whose `sink` external owns one reference, as Desktop's does; `magic` and `version` override its ABI header. */ + create(header?: { magic?: number; version?: number }): { sink: object; native: object } + presented(native: object): FakePresented[] + /** Run the presentation's delivery (error text or null) or settlement (`invalidated`) callback on a native thread. */ + answer(native: object, id: string, kind: 'delivered' | 'settled', value: string | null | boolean): void + /** + * Refuse the next presentation with `reason`: `code` 1 (`DSH_SHARED_TEXTURE_PRESENT_REJECTED`, the default) refuses + * only that frame, 2 (`DSH_SHARED_TEXTURE_PRESENT_DISCONNECTED`) reports that the sink lost its connection. + */ + refuseNext(native: object, reason: string, code?: 1 | 2): void + /** Deliver and release later presentations inside `present`. */ + answerInline(native: object, enabled: boolean): void + references(native: object): { refs: number; retains: number; releases: number } + /** The receiver's name for the default hardware D3D11 adapter; null outside Windows. */ + defaultAdapter(): string | null +} + +const fixtures = fileURLToPath(new URL('../../../../apps/desktop/tests/frame-forwarding/fixtures/', import.meta.url)) +const native = fileURLToPath(new URL('../native/', import.meta.url)) +const desktopSinkHeaders = fileURLToPath(new URL('../../../../apps/desktop/native/shared-texture/', import.meta.url)) + +/** + * Build the fake sink into `directory` and load it. On Windows the loaded file stays open until the process exits. + * @param directory - Scratch directory for build outputs. + * @returns The addon exports, and a runner of further build commands in the same toolchain environment. + */ +export function buildFakeSink(directory: string): { fakes: FakeSinkAddon; run: (command: string, args: string[]) => void } { + const environment = nativeBuildEnvironment(process.arch) + const headers = environment.DSH_NODE_API_HEADERS ?? '' + const run = (command: string, args: string[]): void => { + const result = spawnSync(command, args, { cwd: directory, env: environment, encoding: 'utf8', timeout: 120_000 }) + expect(result.error).toBeUndefined() + expect(result.signal).toBeNull() + expect(result.status, result.stdout + result.stderr).toBe(0) + } + const output = join(directory, 'fake-sink.node') + const source = join(fixtures, 'fake-sink.cc') + if (process.platform === 'win32') { + run('lib.exe', ['/nologo', `/def:${join(headers, 'def', 'node_api.def')}`, '/name:node.exe', `/machine:${process.arch}`, `/out:${join(directory, 'node.lib')}`]) + run('cl.exe', ['/nologo', '/LD', '/EHsc', '/MD', '/std:c++17', `/I${join(headers, 'include')}`, `/I${desktopSinkHeaders}`, '/DNAPI_VERSION=8', + '/DNODE_GYP_MODULE_NAME=fake_sink', `/Fo${directory}\\`, source, join(desktopSinkHeaders, 'win-delay-load.cc'), + '/link', '/DELAYLOAD:node.exe', 'delayimp.lib', join(directory, 'node.lib'), 'd3d11.lib', 'dxgi.lib', + `/IMPLIB:${join(directory, 'fake-sink.lib')}`, `/OUT:${output}`]) + } else { + run('clang++', ['-arch', process.arch === 'x64' ? 'x86_64' : 'arm64', '-std=c++17', `-I${join(headers, 'include')}`, `-I${desktopSinkHeaders}`, + '-DNAPI_VERSION=8', '-DNODE_GYP_MODULE_NAME=fake_sink', '-shared', '-undefined', 'dynamic_lookup', source, '-o', output]) + } + return { fakes: createRequire(import.meta.url)(output) as FakeSinkAddon, run } +} + +/** Compile a producer fixture against the receiver transport inside the test's scratch directory. + * @param directory - Private output directory owned by the test. + * @param name - Fixture source basename. + * @param run - Build command runner using the host toolchain environment. + * @returns Executable path. + */ +export function buildFixtureProducer(directory: string, name: string, run: (command: string, args: string[]) => void): string { + const windows = process.platform === 'win32' + const output = join(directory, windows ? `${name}.exe` : name) + const sources = [join(fixtures, `${name}.cc`), join(fixtures, 'fixture-client.cc'), join(native, 'transport.cc')] + if (windows) { + run('cl.exe', ['/nologo', '/EHsc', '/MD', '/std:c++17', '/D_WIN32_WINNT=0x0602', `/I${native}`, ...sources, + '/link', 'd3d11.lib', 'dxgi.lib', 'advapi32.lib', 'bcrypt.lib', `/OUT:${output}`]) + } else { + run('clang++', ['-arch', process.arch === 'x64' ? 'x86_64' : 'arm64', '-std=c++17', `-I${native}`, ...sources, + '-framework', 'IOSurface', '-framework', 'CoreFoundation', '-lbsm', '-o', output]) + } + return output +} diff --git a/packages/experimental/frame-forwarding/tests/fixtures/content-vectors.json b/packages/experimental/frame-forwarding/tests/fixtures/content-vectors.json new file mode 100644 index 0000000000..bebd1de1e6 --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/fixtures/content-vectors.json @@ -0,0 +1,11 @@ +{ + "mapping": [ + { "name": "identity", "view": { "x": 0, "y": 0, "scale": 1 }, "window": { "x": 0, "y": 0, "width": 100, "height": 80 }, "expected": { "x": 0, "y": 0, "width": 100, "height": 80 } }, + { "name": "scroll within an overscan window", "view": { "x": 30, "y": 120, "scale": 0.5 }, "window": { "x": 0, "y": 100, "width": 300, "height": 400 }, "expected": { "x": -15, "y": -10, "width": 150, "height": 200 } }, + { "name": "centered negative origin", "view": { "x": -50, "y": -20, "scale": 2 }, "window": { "x": 0, "y": 0, "width": 100, "height": 80 }, "expected": { "x": 100, "y": 40, "width": 200, "height": 160 } }, + { "name": "old window during reanchor", "view": { "x": 40, "y": 950, "scale": 0.25 }, "window": { "x": 0, "y": 0, "width": 2000, "height": 1600 }, "expected": { "x": -10, "y": -237.5, "width": 500, "height": 400 } }, + { "name": "new window after reanchor", "view": { "x": 40, "y": 950, "scale": 0.25 }, "window": { "x": 0, "y": 900, "width": 2000, "height": 1600 }, "expected": { "x": -10, "y": -12.5, "width": 500, "height": 400 } }, + { "name": "fractional units", "view": { "x": 10.5, "y": -2.25, "scale": 0.125 }, "window": { "x": -3.5, "y": 1.75, "width": 0.5, "height": 1.5 }, "expected": { "x": -1.75, "y": 0.5, "width": 0.0625, "height": 0.1875 } }, + { "name": "maximum coordinates and scale", "view": { "x": -16777216, "y": 16777216, "scale": 64 }, "window": { "x": 16777216, "y": -16777216, "width": 16777216, "height": 16777216 }, "expected": { "x": 2147483648, "y": -2147483648, "width": 1073741824, "height": 1073741824 } } + ] +} diff --git a/packages/experimental/frame-forwarding/tests/fixtures/two-slides.pptx b/packages/experimental/frame-forwarding/tests/fixtures/two-slides.pptx new file mode 100644 index 0000000000..1c4ddc6ac2 Binary files /dev/null and b/packages/experimental/frame-forwarding/tests/fixtures/two-slides.pptx differ diff --git a/packages/experimental/frame-forwarding/tests/forwarder.host.spec.ts b/packages/experimental/frame-forwarding/tests/forwarder.host.spec.ts new file mode 100644 index 0000000000..beb595ad4f --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/forwarder.host.spec.ts @@ -0,0 +1,643 @@ +/** + * The Host forwarder owns channels, follows their producer connections, attaches Desktop's native sink to each + * receiver, keeps each receiver's presentation gate current, and reports the receiver's presentation failures. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { + FrameForwardingAdapterId, FrameForwardingBindings, FrameForwardingDeliveryId, FrameForwardingReceiver, + FrameForwardingReceiverEvent, +} from '../src/host/native.ts' +import type { SharedTextureCapabilities, SharedTextureNativeSink, SharedTextureService } from '@deepseek-ai/dsh-shared-texture' +import { FrameForwarder } from '../src/host/forwarder.ts' +import type { FrameChannelState, FrameConnectionId, FrameForwardingEvent, FrameRxId } from '../src/types.ts' + +const platform = Object.getOwnPropertyDescriptor(process, 'platform')! +function setPlatform(value: NodeJS.Platform): void { Object.defineProperty(process, 'platform', { value, configurable: true }) } + +const BUDGET = 128 * 1024 * 1024 +const limits = { + maxFrames: 3, maxBytes: vi.fn(() => BUDGET), requestTimeoutMs: 10000, maxPendingRequests: 128 } +const order: string[] = [] +type Deliverable = Parameters[0] +function mockReceiver(tx: string) { + return { + tx, + send: vi.fn<(connectionId: FrameConnectionId, json: string) => void>(), + release: vi.fn((deliveryId: FrameForwardingDeliveryId) => { order.push(`release:${String(deliveryId)}`); return true }), + attachSink: vi.fn<(rx: string, sink: unknown, timeoutMs: number) => void>(), + setDeliverable: vi.fn<(state: Deliverable) => void>(), + close: vi.fn(async () => {}), + } satisfies FrameForwardingReceiver +} +const receiver = mockReceiver('1|1|secret|ai.deepseek.render.name') +let onEvent: ((event: FrameForwardingReceiverEvent) => void) | undefined +const createBudget = vi.fn(() => ({}) as ReturnType) +const createReceiver = vi.fn((_options: object, callback: (event: FrameForwardingReceiverEvent) => void): FrameForwardingReceiver => { + onEvent = callback + return receiver +}) +const bindings = { createBudget, createReceiver } satisfies FrameForwardingBindings +const desktop: SharedTextureCapabilities = { supported: true } +/** An opaque sink that equality checks tell apart by `name`. */ +function sink(name: string): SharedTextureNativeSink { + const value = {} as SharedTextureNativeSink + Object.defineProperty(value, 'name', { value: name, enumerable: true }) + return value +} +const firstSink = sink('first'), secondSink = sink('second') +const sharedTexture = { + capabilities: vi.fn(async () => desktop), + nativeSink: vi.fn(async (_timeoutMs: number) => firstSink), + adapterLuid: vi.fn(async (_timeoutMs: number): Promise => '0:1234'), +} satisfies SharedTextureService +const listeners = { + event: vi.fn<(event: Exclude) => void>(), + warn: vi.fn<(message: string) => void>(), +} +let forwarder: FrameForwarder +let loadFailure: Error | undefined + +beforeEach(() => { + vi.clearAllMocks() + setPlatform('darwin') + order.length = 0 + onEvent = undefined + loadFailure = undefined + receiver.close.mockImplementation(async () => { order.push('close') }) + receiver.setDeliverable.mockImplementation((state) => { order.push(`gate:${JSON.stringify(state)}`) }) + sharedTexture.capabilities.mockResolvedValue(desktop) + sharedTexture.nativeSink.mockResolvedValue(firstSink) + forwarder = new FrameForwarder(sharedTexture, () => { + if (loadFailure !== undefined) throw loadFailure + return bindings + }, limits, listeners) +}) +afterEach(async () => { + try { + await forwarder.closeAll() + if (vi.isFakeTimers()) expect(vi.getTimerCount()).toBe(0) + } finally { vi.useRealTimers(); Object.defineProperty(process, 'platform', platform) } +}) + +const id = (value: number): FrameConnectionId => value as FrameConnectionId +const viewport = (version: number, visible = true): object => ({ version, width: 512, height: 512, deviceScaleFactor: 1, visible }) +async function open(): Promise { + return (await forwarder.channel()).rx +} +function connect(connectionId = 1): void { + onEvent!({ type: 'connected', connectionId: id(connectionId), pid: 4000 + connectionId }) +} +/** The last viewport request sent to the producer. */ +function lastRequest(): { connectionId: FrameConnectionId; requestId: string; version: number } { + const [connectionId, json] = receiver.send.mock.calls.at(-1)! + const message = JSON.parse(json) as { requestId: string; viewport: { version: number } } + return { connectionId, requestId: message.requestId, version: message.viewport.version } +} +function message(connectionId: number, value: object | string): void { + onEvent!({ type: 'message', connectionId: id(connectionId), text: typeof value === 'string' ? value : JSON.stringify(value) }) +} +/** Acknowledge the last viewport request from the connection it was sent to. */ +function ack(): void { + const { connectionId, requestId, version } = lastRequest() + message(connectionId, { type: 'viewport-applied', requestId, version }) +} +async function applyViewport(rx: FrameRxId, value: object): Promise { + const pending = forwarder.setViewport(rx, value) + ack() + return pending +} +/** A connected channel whose producer acknowledged viewport 1. */ +async function ready(): Promise { + const rx = await open() + connect() + await applyViewport(rx, viewport(1)) + return rx +} +type Frame = Extract +function frame(options: { connectionId?: number; deliveryId?: number } = {}): Frame { + const { connectionId = 1, deliveryId = 7007 } = options + return { + type: 'frame', connectionId: id(connectionId), frameId: 7, deliveryId: deliveryId as FrameForwardingDeliveryId, width: 512, height: 512, + stride: 2048, transport: 'shared-texture', sourceKeyedMutex: false, adapterId: '0:1234' as FrameForwardingAdapterId, + presentationAdapterId: null, handle: Buffer.alloc(8, 0x5a), metadata: JSON.stringify({ requestId: 'tile', generation: 1, revision: 0 }), + } +} +/** The presentation gate the forwarder last pushed to the receiver. */ +const gate = (): Deliverable | undefined => receiver.setDeliverable.mock.calls.at(-1)?.[0] +const open1 = (maxGeneration: number, visible = true): Deliverable => ({ connectionId: id(1), visible, maxGeneration }) +function states(rx: FrameRxId): FrameChannelState[] { + return listeners.event.mock.calls.map(([event]) => event).filter(event => event.kind === 'state' && event.rx === rx) + .map(event => (event as Extract).channel) +} +function errors(): Extract[] { + return listeners.event.mock.calls.map(([event]) => event) + .filter((event): event is Extract => event.kind === 'error') +} + +describe('channel creation', () => { + it('opens an ordered receiver under the shared window budget, attaches Desktop\'s sink, returns its credential, and publishes it idle', async () => { + expect(limits.maxBytes).not.toHaveBeenCalled() + const channel = await forwarder.channel() + expect(channel.tx).toBe(receiver.tx) + expect(createBudget).toHaveBeenCalledExactlyOnceWith(BUDGET) + expect(createReceiver).toHaveBeenCalledWith(expect.objectContaining({ + maxFrames: 3, maxBytes: BUDGET, displayAdapter: null, readbackTimeoutMs: 10000, + }), expect.any(Function)) + expect(sharedTexture.nativeSink).toHaveBeenCalledExactlyOnceWith(limits.requestTimeoutMs) + expect(receiver.attachSink).toHaveBeenCalledExactlyOnceWith(channel.rx, firstSink, limits.requestTimeoutMs) + expect(sharedTexture.adapterLuid).not.toHaveBeenCalled() + expect(states(channel.rx)).toEqual([{ state: 'idle' }]) + expect(forwarder.isOpen(channel.rx)).toBe(true) + expect(forwarder.isOpen('missing' as FrameRxId)).toBe(false) + expect(forwarder.snapshot()).toEqual([{ rx: channel.rx, sequence: 1, channel: { state: 'idle' } }]) + // The next channel reuses the window budget and asks Desktop for the sink of its current connection, which a + // disconnect replaced without a frame reaching this thread. + sharedTexture.nativeSink.mockResolvedValueOnce(secondSink) + const second = await forwarder.channel() + expect(createBudget).toHaveBeenCalledOnce() + expect(limits.maxBytes).toHaveBeenCalledOnce() + expect(sharedTexture.nativeSink).toHaveBeenCalledTimes(2) + expect(receiver.attachSink).toHaveBeenLastCalledWith(second.rx, secondSink, limits.requestTimeoutMs) + }) + it('requests Desktop\'s sink once for channels opening together, before allocating their receivers', async () => { + const requested = Promise.withResolvers() + sharedTexture.nativeSink.mockReturnValueOnce(requested.promise) + const opening = Promise.all([forwarder.channel(), forwarder.channel()]) + await vi.waitFor(() => { expect(sharedTexture.nativeSink).toHaveBeenCalledOnce() }) + await new Promise(resolve => setTimeout(resolve, 0)) + expect(createReceiver).not.toHaveBeenCalled() + requested.resolve(secondSink) + const [first, second] = await opening + expect(sharedTexture.nativeSink).toHaveBeenCalledOnce() + expect(receiver.attachSink.mock.calls).toEqual([ + [first.rx, secondSink, limits.requestTimeoutMs], [second.rx, secondSink, limits.requestTimeoutMs], + ]) + }) + it('gives Desktop\'s sink a presentation deadline of at most 30000 ms, also when it replaces the sink', async () => { + forwarder = new FrameForwarder(sharedTexture, () => bindings, { ...limits, requestTimeoutMs: 60_000 }, listeners) + const rx = await open() + expect(sharedTexture.nativeSink).toHaveBeenCalledExactlyOnceWith(60_000) + expect(receiver.attachSink).toHaveBeenCalledExactlyOnceWith(rx, firstSink, 30_000) + sharedTexture.nativeSink.mockResolvedValueOnce(secondSink) + onEvent!(frame()) + await vi.waitFor(() => { expect(receiver.attachSink).toHaveBeenLastCalledWith(rx, secondSink, 30_000) }) + }) + it('fails the channel without a receiver when Desktop provides no sink, and discards a receiver that refuses it', async () => { + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + sharedTexture.nativeSink.mockRejectedValueOnce(new Error('Desktop shared textures are unavailable')) + await expect(open()).rejects.toThrow('Desktop native frame submission is unavailable: Desktop shared textures are unavailable') + expect(createReceiver).not.toHaveBeenCalled() + // The failed request is not cached; a non-Error refusal of the sink is reported too. + receiver.attachSink.mockImplementationOnce(() => { throw 'Unsupported Desktop shared-texture sink ABI' }) + receiver.close.mockRejectedValueOnce(new Error('close failed')) + await expect(open()).rejects.toThrow('Desktop native frame submission is unavailable: Unsupported Desktop shared-texture sink ABI') + expect(log).toHaveBeenCalledWith('Native receiver teardown failed', expect.any(Error)) + expect(sharedTexture.nativeSink).toHaveBeenCalledTimes(2) + expect(receiver.close).toHaveBeenCalledOnce() + expect(forwarder.snapshot()).toEqual([]) + log.mockRestore() + }) + it('gives a Windows receiver the LUID of Chromium\'s compositor adapter that Desktop reads', async () => { + setPlatform('win32') + await open() + expect(sharedTexture.adapterLuid).toHaveBeenCalledExactlyOnceWith(limits.requestTimeoutMs) + expect(createReceiver).toHaveBeenCalledWith(expect.objectContaining({ displayAdapter: '0:1234' }), expect.any(Function)) + }) + it('asks Desktop for the Windows adapter for every channel, so a later channel follows the adapter Desktop reports', async () => { + setPlatform('win32') + await open() + // Desktop reads another adapter after its GPU process restarted, although no presented frame was invalidated. + sharedTexture.adapterLuid.mockResolvedValueOnce('0:5678') + await open() + expect(sharedTexture.adapterLuid).toHaveBeenCalledTimes(2) + expect(createReceiver.mock.calls.map(([options]) => (options as { displayAdapter: unknown }).displayAdapter)).toEqual(['0:1234', '0:5678']) + }) + it('cancels a Windows creation that closeAll overtakes while Desktop reads the adapter', async () => { + setPlatform('win32') + const reading = Promise.withResolvers() + sharedTexture.adapterLuid.mockReturnValueOnce(reading.promise) + const creation = expect(open()).rejects.toThrow('creation cancelled') + await vi.waitFor(() => { expect(sharedTexture.adapterLuid).toHaveBeenCalledOnce() }) + const closing = forwarder.closeAll() + reading.resolve('0:1234') + await creation + await closing + expect(createReceiver).not.toHaveBeenCalled() + }) + it('rejects an unidentified or unread Windows adapter before allocating native resources, and asks Desktop again', async () => { + setPlatform('win32') + sharedTexture.adapterLuid.mockResolvedValueOnce(null) + await expect(open()).rejects.toThrow('Desktop shared textures are unavailable: Electron graphics adapter could not be identified') + sharedTexture.adapterLuid.mockRejectedValueOnce(new Error('Desktop adapter reading timed out')) + await expect(open()).rejects.toThrow('Desktop adapter reading timed out') + expect(createReceiver).not.toHaveBeenCalled() + await open() + expect(sharedTexture.adapterLuid).toHaveBeenCalledTimes(3) + expect(createReceiver).toHaveBeenCalledWith(expect.objectContaining({ displayAdapter: '0:1234' }), expect.any(Function)) + }) + it('refuses channels when Desktop reports textures unsupported or the addon does not load', async () => { + sharedTexture.capabilities.mockResolvedValueOnce({ supported: false, reason: 'no-electron' }) + await expect(open()).rejects.toThrow('unavailable: no-electron') + sharedTexture.capabilities.mockResolvedValueOnce({ supported: false }) + await expect(open()).rejects.toThrow('Desktop shared textures are unavailable: unsupported') + loadFailure = new Error('frame-forwarding.node is missing') + const unloaded = new FrameForwarder(sharedTexture, () => { throw loadFailure! }, limits, listeners) + expect(await unloaded.capabilities()).toEqual({ supported: false, reason: 'receiver-unavailable: frame-forwarding.node is missing' }) + await expect(unloaded.channel()).rejects.toThrow('receiver is unavailable') + expect(createReceiver).not.toHaveBeenCalled() + expect(limits.maxBytes).not.toHaveBeenCalled() + }) + it.each(['darwin', 'win32'] as const)('reports capability on %s from Desktop and the addon', async (value) => { + setPlatform(value) + expect(await forwarder.capabilities()).toEqual({ supported: true }) + sharedTexture.capabilities.mockResolvedValueOnce({ supported: false, reason: 'desktop-says-no' }) + expect(await forwarder.capabilities()).toEqual({ supported: false, reason: 'desktop-says-no' }) + sharedTexture.capabilities.mockResolvedValueOnce({ supported: false }) + expect(await forwarder.capabilities()).toEqual({ supported: false, reason: 'desktop-shared-texture-unavailable' }) + }) + it('reports other platforms unsupported without asking Desktop', async () => { + setPlatform('linux') + expect(await forwarder.capabilities()).toEqual({ supported: false, reason: 'unsupported-platform' }) + expect(sharedTexture.capabilities).not.toHaveBeenCalled() + }) + it('cancels a creation that outlives closeAll', async () => { + const probing = Promise.withResolvers() + sharedTexture.capabilities.mockReturnValueOnce(probing.promise) + const creation = open() + const rejected = expect(creation).rejects.toThrow('creation cancelled') + const closing = forwarder.closeAll() + await expect(forwarder.channel()).rejects.toThrow('closing') + probing.resolve(desktop) + await rejected + await closing + expect(createReceiver).not.toHaveBeenCalled() + }) + it('cancels a creation that closeAll overtakes while Desktop\'s sink is requested, before allocating its receiver', async () => { + const requested = Promise.withResolvers() + sharedTexture.nativeSink.mockReturnValueOnce(requested.promise) + const creation = open() + const rejected = expect(creation).rejects.toThrow('creation cancelled') + await vi.waitFor(() => { expect(sharedTexture.nativeSink).toHaveBeenCalledOnce() }) + const closing = forwarder.closeAll() + requested.resolve(firstSink) + await rejected + await closing + expect(createReceiver).not.toHaveBeenCalled() + expect(order).toEqual([]) + }) +}) + +describe('producer connections', () => { + it('replays the kept viewport to a new connection and publishes the version it acknowledged', async () => { + const rx = await open() + expect(await forwarder.setViewport(rx, viewport(1))).toEqual({ applied: false, reason: 'no-producer' }) + const stale = { applied: false, reason: 'stale-viewport', currentVersion: 1 } + expect(await forwarder.setViewport(rx, viewport(1))).toEqual(stale) + expect(receiver.send).not.toHaveBeenCalled() + connect() + expect(await forwarder.setViewport(rx, viewport(1))).toEqual(stale) + expect(lastRequest()).toMatchObject({ connectionId: 1, version: 1 }) + expect(states(rx).at(-1)).toEqual({ state: 'connected', connectionId: 1 }) + ack() + expect(states(rx).at(-1)).toEqual({ state: 'connected', connectionId: 1, viewportVersion: 1 }) + expect(await applyViewport(rx, viewport(2))).toEqual({ applied: true, connectionId: 1 }) + expect(states(rx).at(-1)).toEqual({ state: 'connected', connectionId: 1, viewportVersion: 2 }) + }) + it('hands the channel to a successor after the previous connection drains, without letting old messages reach it', async () => { + const rx = await ready() + const pending = forwarder.setViewport(rx, viewport(2)) + const stale = lastRequest() + onEvent!({ type: 'disconnected', connectionId: id(1), text: 'connection lost' }) + expect(await pending).toEqual({ applied: false, reason: 'producer-changed' }) + expect(listeners.warn).toHaveBeenCalledWith('Native producer 1 disconnected: connection lost') + expect(states(rx).at(-1)).toEqual({ state: 'draining', connectionId: 1 }) + expect(await forwarder.setViewport(rx, viewport(3))).toEqual({ applied: false, reason: 'no-producer' }) + onEvent!({ type: 'drained', connectionId: id(2) }) + onEvent!({ type: 'drained', connectionId: id(1) }) + expect(states(rx).at(-1)).toEqual({ state: 'idle' }) + connect(2) + expect(lastRequest()).toMatchObject({ connectionId: 2, version: 3 }) + // The successor's frames pass from the replay on; the old connection's frames do not. + expect(gate()).toEqual({ connectionId: 2, visible: true, maxGeneration: 3 }) + // A late acknowledgement of the old connection's request neither confirms nor settles anything for the successor. + message(1, { type: 'viewport-applied', requestId: stale.requestId, version: 3 }) + expect(states(rx).at(-1)).toEqual({ state: 'connected', connectionId: 2 }) + onEvent!({ type: 'disconnected', connectionId: id(1) }) + ack() + expect(states(rx).at(-1)).toEqual({ state: 'connected', connectionId: 2, viewportVersion: 3 }) + expect(gate()).toEqual({ connectionId: 2, visible: true, maxGeneration: 3 }) + expect(sharedTexture.capabilities).toHaveBeenCalledWith(limits.requestTimeoutMs) + onEvent!({ type: 'disconnected', connectionId: id(2) }) + expect(listeners.warn).toHaveBeenCalledOnce() + }) + it('treats a send the addon refuses as a producer change', async () => { + const rx = await ready() + receiver.send.mockImplementationOnce(() => { throw new Error('Frame-forwarding connection is not active') }) + expect(await forwarder.setViewport(rx, viewport(2))).toEqual({ applied: false, reason: 'producer-changed' }) + }) + it('rejects a timed-out or refused viewport while the channel stays open, and still confirms a late acknowledgement', async () => { + vi.useFakeTimers() + const bounded = new FrameForwarder(sharedTexture, () => bindings, + { ...limits, requestTimeoutMs: 100, maxPendingRequests: 1 }, listeners) + const rx = (await bounded.channel()).rx + connect() + const timedOut = expect(bounded.setViewport(rx, viewport(1))).rejects.toThrow('acknowledgement timed out') + const late = lastRequest() + await expect(bounded.setViewport(rx, viewport(2))).rejects.toThrow('queue is full') + await vi.advanceTimersByTimeAsync(100) + await timedOut + expect(bounded.isOpen(rx)).toBe(true) + message(1, { type: 'viewport-applied', requestId: late.requestId, version: late.version }) + expect(states(rx).at(-1)).toEqual({ state: 'connected', connectionId: 1, viewportVersion: 1 }) + const rejected = expect(bounded.setViewport(rx, viewport(3))).rejects.toThrow('too large') + message(1, { type: 'viewport-rejected', requestId: lastRequest().requestId, error: 'too large' }) + await rejected + const unnamed = expect(bounded.setViewport(rx, viewport(4))).rejects.toThrow('Native producer rejected viewport') + message(1, { type: 'viewport-rejected', requestId: lastRequest().requestId }) + await unnamed + expect(bounded.isOpen(rx)).toBe(true) + await bounded.closeAll() + }) + it('validates viewports, requires increasing versions, and refuses closed channels', async () => { + const rx = await ready() + await expect(forwarder.setViewport('missing' as FrameRxId, viewport(2))).rejects.toThrow('channel is closed') + await expect(forwarder.setViewport(rx, { ...viewport(2), width: 0 })).rejects.toThrow() + await expect(forwarder.setViewport(rx, viewport(1))).resolves.toEqual({ applied: false, reason: 'stale-viewport', currentVersion: 1 }) + await forwarder.close(rx) + await expect(forwarder.setViewport(rx, viewport(2))).rejects.toThrow('channel is closed') + }) + it('warns when a replayed viewport fails, but not when its connection ended', async () => { + vi.useFakeTimers() + const rx = await open() + await forwarder.setViewport(rx, viewport(1)) + connect() + await vi.advanceTimersByTimeAsync(limits.requestTimeoutMs) + expect(listeners.warn).toHaveBeenCalledExactlyOnceWith('Native viewport replay failed: Native producer acknowledgement timed out') + onEvent!({ type: 'disconnected', connectionId: id(1) }) + onEvent!({ type: 'drained', connectionId: id(1) }) + connect(2) + onEvent!({ type: 'disconnected', connectionId: id(2) }) + await vi.advanceTimersByTimeAsync(0) + expect(listeners.warn).toHaveBeenCalledOnce() + }) + it('reports producer errors and invalid control messages of the current connection only', async () => { + const rx = await ready() + message(1, { type: 'error', message: 'PPT stream rendering failed' }) + message(1, { type: 'error' }) + message(1, '{') + message(1, 'null') + message(1, '[]') + message(2, { type: 'error', message: 'not current' }) + for (const value of [{ type: 'input-applied' }, { type: 'viewport-applied' }, { type: 'viewport-applied', requestId: 'missing', version: 'x' }]) + message(1, value) + expect(errors().map(({ error }) => error)).toEqual([ + 'PPT stream rendering failed', 'Native producer failed', 'Native producer sent an invalid control message', + 'Native producer sent an invalid control message', 'Native producer sent an invalid control message', + ]) + expect(errors().every(event => event.rx === rx && event.connectionId === 1 && event.source === 'producer')).toBe(true) + expect(states(rx).at(-1)).toEqual({ state: 'connected', connectionId: 1, viewportVersion: 1 }) + }) + it('reports refusals and blocked drains, and closes a channel whose listener failed', async () => { + const rx = await ready() + onEvent!({ type: 'rejected', text: 'channel-busy' }) + expect(listeners.warn).toHaveBeenCalledWith('Native producer refused: channel-busy') + onEvent!({ type: 'drain-blocked', connectionId: id(1), text: 'GPU cleanup is stalled' }) + expect(states(rx).at(-1)).toEqual({ state: 'draining', connectionId: 1, blocked: 'GPU cleanup is stalled' }) + onEvent!({ type: 'drain-blocked', connectionId: id(2), text: 'other' }) + expect(states(rx)).toHaveLength(4) + expect(listeners.warn).toHaveBeenCalledWith('Native producer 2 drain is blocked: other') + onEvent!({ type: 'failed', text: 'listener failed' }) + expect(forwarder.isOpen(rx)).toBe(false) + expect(states(rx).at(-1)).toEqual({ state: 'closed', cause: 'failed', reason: 'Native channel failed: listener failed' }) + await vi.waitFor(() => { expect(forwarder.snapshot()).toEqual([]) }) + onEvent!({ type: 'drained', connectionId: id(1) }) + // A frame of a forgotten channel returns its credit without asking Desktop for a sink. + onEvent!(frame()) + expect(receiver.release).toHaveBeenCalledExactlyOnceWith(7007) + expect(sharedTexture.nativeSink).toHaveBeenCalledOnce() + expect(states(rx).at(-1)).toEqual({ state: 'closed', cause: 'failed', reason: 'Native channel failed: listener failed' }) + }) +}) + +describe('presentation gate', () => { + it('admits each viewport\'s generation before sending it, without waiting for its acknowledgement', async () => { + const rx = await open() + expect(receiver.setDeliverable).not.toHaveBeenCalled() + await forwarder.setViewport(rx, viewport(1)) + expect(gate()).toBeNull() + // A producer's frame can reach the receiver before its acknowledgement reaches this thread. + const atSend: unknown[] = [] + receiver.send.mockImplementationOnce(() => { atSend.push(gate()) }).mockImplementationOnce(() => { atSend.push(gate()) }) + connect() + const replay = lastRequest() + const pending = forwarder.setViewport(rx, viewport(2)) + expect(atSend).toEqual([open1(1), open1(2)]) + message(1, { type: 'viewport-applied', requestId: replay.requestId, version: 1 }) + ack() + await pending + // Acknowledgements leave the gate alone, including one of a version the renderer never sent. + const pushed = receiver.setDeliverable.mock.calls.length + message(1, { type: 'viewport-applied', requestId: 'forged', version: 5 }) + expect(receiver.setDeliverable).toHaveBeenCalledTimes(pushed) + expect(gate()).toEqual(open1(2)) + await applyViewport(rx, viewport(3, false)) + expect(gate()).toEqual(open1(3, false)) + await applyViewport(rx, viewport(4)) + expect(gate()).toEqual(open1(4)) + }) + it('closes when the connection ends, drains, or the channel closes', async () => { + const rx = await ready() + onEvent!({ type: 'disconnected', connectionId: id(1) }) + expect(gate()).toBeNull() + onEvent!({ type: 'drained', connectionId: id(1) }) + expect(gate()).toBeNull() + connect(2) + expect(gate()).toEqual({ connectionId: 2, visible: true, maxGeneration: 1 }) + ack() + await forwarder.close(rx) + expect(order.slice(-2)).toEqual(['gate:null', 'close']) + }) +}) + +describe('frames delivered to JavaScript', () => { + it('returns the frame\'s credit at once and attaches a new Desktop sink to every open channel', async () => { + const first = await ready() + const onFirst = onEvent! + const other = mockReceiver('1|1|other|ai.deepseek.render.other') + createReceiver.mockImplementationOnce(() => other) + const second = (await forwarder.channel()).rx + // A closing channel receives no sink. + const closingRx = await open() + const closed = Promise.withResolvers() + receiver.close.mockReturnValueOnce(closed.promise) + const closing = forwarder.close(closingRx) + receiver.attachSink.mockClear() + // Desktop's service replaced its connection, so every later request returns the new sink. + sharedTexture.nativeSink.mockResolvedValue(secondSink) + onFirst(frame()) + expect(receiver.release).toHaveBeenCalledExactlyOnceWith(7007) + await vi.waitFor(() => { expect(other.attachSink).toHaveBeenLastCalledWith(second, secondSink, limits.requestTimeoutMs) }) + expect(receiver.attachSink.mock.calls).toEqual([[first, secondSink, limits.requestTimeoutMs]]) + closed.resolve(undefined) + await closing + expect(sharedTexture.nativeSink).toHaveBeenCalledTimes(4) + // The next channel asks Desktop again and gets the sink of its current connection. + await open() + expect(sharedTexture.nativeSink).toHaveBeenCalledTimes(5) + expect(receiver.attachSink).toHaveBeenLastCalledWith(expect.any(String), secondSink, limits.requestTimeoutMs) + }) + it('requests one sink for frames arriving while a request is outstanding, and reports a channel that refuses it', async () => { + const rx = await ready() + const requested = Promise.withResolvers() + sharedTexture.nativeSink.mockReturnValueOnce(requested.promise) + onEvent!(frame()) + onEvent!(frame({ deliveryId: 7008 })) + expect(receiver.release.mock.calls).toEqual([[7007], [7008]]) + expect(sharedTexture.nativeSink).toHaveBeenCalledTimes(2) + receiver.attachSink.mockImplementationOnce(() => { throw new Error('Unsupported Desktop shared-texture sink ABI') }) + requested.resolve(secondSink) + await vi.waitFor(() => { + expect(listeners.warn).toHaveBeenCalledExactlyOnceWith('Native channel could not attach Desktop\'s sink: Unsupported Desktop shared-texture sink ABI') + }) + expect(forwarder.isOpen(rx)).toBe(true) + }) + it('warns when Desktop provides no sink and requests again only on the next frame', async () => { + await ready() + sharedTexture.nativeSink.mockRejectedValueOnce(new Error('Desktop connection is lost')) + onEvent!(frame()) + await vi.waitFor(() => { + expect(listeners.warn).toHaveBeenCalledExactlyOnceWith('Desktop native frame submission is unavailable: Desktop connection is lost') + }) + await new Promise(resolve => setTimeout(resolve, 10)) + expect(sharedTexture.nativeSink).toHaveBeenCalledTimes(2) + onEvent!(frame({ deliveryId: 7008 })) + await vi.waitFor(() => { expect(receiver.attachSink).toHaveBeenCalledTimes(2) }) + expect(sharedTexture.nativeSink).toHaveBeenCalledTimes(3) + }) + it('requests no sink while every channel closes', async () => { + await ready() + const closing = Promise.withResolvers() + receiver.close.mockReturnValueOnce(closing.promise) + const resetting = forwarder.closeAll() + onEvent!(frame()) + expect(receiver.release).toHaveBeenCalledExactlyOnceWith(7007) + closing.resolve(undefined) + await resetting + expect(sharedTexture.nativeSink).toHaveBeenCalledOnce() + }) +}) + +describe('presentation events', () => { + it('reports the receiver\'s presentation errors with their source and request', async () => { + const rx = await ready() + onEvent!({ type: 'presentation-error', connectionId: id(1), source: 'presentation', requestId: 'tile', text: 'Native frame transfer failed (source=0:1, presentation=IOSurface): renderer import failed' }) + onEvent!({ type: 'presentation-error', connectionId: id(1), source: 'producer', text: 'Invalid native frame metadata: metadata is not valid JSON' }) + expect(errors()).toEqual([ + { kind: 'error', rx, connectionId: 1, source: 'presentation', requestId: 'tile', error: 'Native frame transfer failed (source=0:1, presentation=IOSurface): renderer import failed' }, + { kind: 'error', rx, connectionId: 1, source: 'producer', error: 'Invalid native frame metadata: metadata is not valid JSON' }, + ]) + expect(forwarder.isOpen(rx)).toBe(true) + }) + it('closes the channel as lost when Desktop invalidated a presented frame', async () => { + const rx = await ready() + onEvent!({ type: 'presentation-invalidated', connectionId: id(1), text: 'Desktop invalidated a presented frame' }) + expect(forwarder.isOpen(rx)).toBe(false) + expect(states(rx).at(-1)).toEqual({ state: 'closed', cause: 'lost', reason: 'Desktop invalidated a presented frame' }) + await vi.waitFor(() => { expect(forwarder.snapshot()).toEqual([]) }) + expect(receiver.close).toHaveBeenCalledOnce() + }) +}) + +describe('teardown', () => { + it('closes a channel once, ending its connection and rejecting its pending requests', async () => { + const rx = await ready() + const pending = expect(forwarder.setViewport(rx, viewport(2))).rejects.toThrow('Native channel closed') + const first = forwarder.close(rx) + expect(forwarder.close(rx)).toStrictEqual(first) + await first + await pending + await forwarder.close(rx) + expect(receiver.close).toHaveBeenCalledOnce() + expect(states(rx).filter(state => state.state === 'closed')).toEqual([{ state: 'closed', cause: 'closed', reason: 'Native channel closed' }]) + }) + it('ignores connection events while a channel closes', async () => { + const rx = await open() + const closing = Promise.withResolvers() + receiver.close.mockReturnValueOnce(closing.promise) + const closed = forwarder.close(rx) + connect() + onEvent!({ type: 'disconnected', connectionId: id(1) }) + onEvent!({ type: 'drained', connectionId: id(1) }) + onEvent!({ type: 'drain-blocked', connectionId: id(1), text: 'stalled' }) + expect(states(rx)).toEqual([{ state: 'idle' }, { state: 'closed', cause: 'closed', reason: 'Native channel closed' }]) + expect(forwarder.snapshot()).toEqual([{ rx, sequence: 2, channel: { state: 'closed', cause: 'closed', reason: 'Native channel closed' } }]) + closing.resolve(undefined) + await closed + const draining = await open() + connect() + onEvent!({ type: 'disconnected', connectionId: id(1) }) + const stalled = Promise.withResolvers() + receiver.close.mockReturnValueOnce(stalled.promise) + const closingDrain = forwarder.close(draining) + onEvent!({ type: 'disconnected', connectionId: id(1) }) + onEvent!({ type: 'drained', connectionId: id(1) }) + expect(states(draining).at(-1)).toEqual({ state: 'closed', cause: 'closed', reason: 'Native channel closed' }) + stalled.resolve(undefined) + await closingDrain + }) + it('contains throwing listeners and asynchronous receiver teardown failures', async () => { + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const rx = await ready() + listeners.event.mockImplementationOnce(() => { throw new Error('listener exploded') }) + listeners.warn.mockImplementationOnce(() => { throw new Error('logger exploded') }) + receiver.close.mockRejectedValueOnce(new Error('close failed')) + onEvent!({ type: 'rejected', text: 'channel-busy' }) + onEvent!({ type: 'failed', text: 'device lost' }) + await vi.waitFor(() => { expect(log).toHaveBeenCalledWith('Native receiver teardown failed', expect.any(Error)) }) + expect(log).toHaveBeenCalledWith('Native channel event listener failed', expect.any(Error)) + expect(log).toHaveBeenCalledWith('Native channel warning listener failed', expect.any(Error)) + expect(forwarder.isOpen(rx)).toBe(false) + const invalidated = await ready() + receiver.close.mockRejectedValueOnce(new Error('close failed again')) + onEvent!({ type: 'presentation-invalidated', connectionId: id(1) }) + await vi.waitFor(() => { expect(log).toHaveBeenCalledTimes(4) }) + expect(forwarder.isOpen(invalidated)).toBe(false) + log.mockRestore() + }) + it('contains native close failures and waits for a failed cleanup before accepting new channels', async () => { + await ready() + receiver.close.mockRejectedValueOnce(new Error('native close failed')) + const closing = forwarder.closeAll() + await expect(forwarder.channel()).rejects.toThrow('closing') + await expect(closing).rejects.toThrow('cleanup failed') + await open() + }) +}) + +describe('concurrent channels', () => { + it('keeps each channel\'s producer, viewports, gate, and closure to itself', async () => { + const first = await ready() + const second = mockReceiver('1|1|other|ai.deepseek.render.other') + let onSecond: ((event: FrameForwardingReceiverEvent) => void) | undefined + createReceiver.mockImplementationOnce((_options, callback) => { onSecond = callback; return second }) + const other = (await forwarder.channel()).rx + // Both channels open under the one window budget. + expect(createBudget).toHaveBeenCalledOnce() + expect(second.attachSink).toHaveBeenCalledExactlyOnceWith(other, firstSink, limits.requestTimeoutMs) + onSecond!({ type: 'connected', connectionId: id(1), pid: 5001 }) + const applying = forwarder.setViewport(other, viewport(1, false)) + const [connectionId, json] = second.send.mock.calls.at(-1)! + const { requestId } = JSON.parse(json) as { requestId: string } + onSecond!({ type: 'message', connectionId, text: JSON.stringify({ type: 'viewport-applied', requestId, version: 1 }) }) + expect(await applying).toEqual({ applied: true, connectionId: 1 }) + expect(receiver.send).toHaveBeenCalledOnce() + expect(second.setDeliverable).toHaveBeenLastCalledWith(open1(1, false)) + expect(gate()).toEqual(open1(1)) + // Closing one channel leaves the other serving its producer. + await forwarder.close(first) + expect(receiver.close).toHaveBeenCalledOnce() + expect(second.close).not.toHaveBeenCalled() + expect(forwarder.isOpen(other)).toBe(true) + expect(second.setDeliverable).toHaveBeenLastCalledWith(open1(1, false)) + }) +}) diff --git a/packages/experimental/frame-forwarding/tests/fullscreen.properties.client.spec.ts b/packages/experimental/frame-forwarding/tests/fullscreen.properties.client.spec.ts new file mode 100644 index 0000000000..462dd6bbb2 --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/fullscreen.properties.client.spec.ts @@ -0,0 +1,295 @@ +// @vitest-environment jsdom +import { brandString } from '@deepseek-ai/dsh-brand' +import fc from 'fast-check' +import { expect, test } from 'vitest' +import type { FrameFullscreenState } from '../src/client/api.ts' +import { adaptFrameForwardingBridge } from '../src/client/wire.ts' +import type { FrameRxId } from '../src/types.ts' + +const channels = ['A', 'B'] as const +type Channel = typeof channels[number] +const channel = fc.constantFrom(...channels) +const entry = fc.tuple(fc.constant('request'), channel, fc.integer({ min: 0, max: 2 }), fc.constantFrom('enter', 'refuse')) +const exit = fc.tuple(fc.constant('exit'), channel) +const reconnect = fc.tuple(fc.constant('reconnect'), channel) +const escape = fc.tuple(fc.constant('Escape')) +const channelAction = fc.oneof({ weight: 6, arbitrary: entry }, { weight: 2, arbitrary: exit }, reconnect, escape) +const pageAction = fc.oneof({ weight: 4, arbitrary: channelAction }, fc.tuple(fc.constantFrom('page enters', 'page leaves'))) +const end = fc.tuple(fc.constantFrom('close all', 'fail', 'dispose')) +type Generated = T extends fc.Arbitrary ? A : never +type Action = Generated +const busy = 'Another native channel holds fullscreen.' + +/** A private document per run. Only the scheduled continuation changes the top layer, before the DOM promise settles. */ +function fullscreenDocument(scheduler: fc.Scheduler) { + const doc = document.implementation.createHTMLDocument() + const stack: Element[] = [] + const owner = new Map() + let changed = (_previous: readonly Element[]): void => {} + const mutate = (update: () => void) => { + const previous = [...stack] + update() + doc.dispatchEvent(new Event('fullscreenchange')) + changed(previous) + } + const show = (target: Element) => { + mutate(() => { + const old = stack.indexOf(target) + if (old !== -1) stack.splice(old, 1) + stack.push(target) + }) + } + const gate = (label: string) => scheduler.schedule(Promise.resolve(), label) + let admitEntry = true, admitExit = true, entries = 0 + const make = (id: string) => { + const target = doc.createElement('div') + target.id = id + doc.body.append(target) + return target + } + const page = make('page') + const elements = new Map(channels.map(rx => [rx, Array.from({ length: 3 }, (_, i) => { + const target = make(`${rx}${i}`) + owner.set(target, rx) + target.requestFullscreen = () => { + ++entries + const accepted = admitEntry + return gate(`DOM ${accepted ? 'enter' : 'refuse'} ${target.id}`).then(() => { + if (!accepted) throw new TypeError('Entry refused') + show(target) + }) + } + return target + })])) + Object.defineProperty(doc, 'fullscreenElement', { get: () => stack.at(-1) ?? null }) + doc.exitFullscreen = () => { + const accepted = admitExit + return gate(`DOM ${accepted ? 'exit' : 'refuse exit'} ${doc.fullscreenElement?.id}`).then(() => { + if (!accepted || !stack.length) throw new TypeError('Exit refused') + mutate(() => { stack.pop() }) + }) + } + return { + doc, stack, owner, elements, entryCount: () => entries, + acceptEntry(value: boolean) { admitEntry = value }, + acceptExit(value: boolean) { admitExit = value }, + observe(listener: typeof changed) { changed = listener }, + escape() { if (stack.length) mutate(() => { stack.length = 0 }) }, + pageEnters() { show(page) }, + pageLeaves() { if (doc.fullscreenElement === page) mutate(() => { stack.pop() }) }, + } +} + +const bridgeFor = (doc: Document) => adaptFrameForwardingBridge( + { onFrame: () => () => {} }, { viewport: () => { throw Error('Unexpected viewport') } }, doc, +) +const id = (rx: Channel) => brandString(rx) + +async function checkRun(scheduler: fc.Scheduler, bursts: Action[][], terminal: Generated) { + const dom = fullscreenDocument(scheduler) + const bridge = bridgeFor(dom.doc) + // Only accepted requests in flight and the actual browser stack determine admission, never a bridge notification. + const pending = new Map(channels.map(rx => [rx, 0])) + const latest = new Map() + const detach = new Map Promise>() + const attempts = new Map(channels.map(rx => [rx, 0])) + const exitAt = new Map() + const coveredAtExit = new Set() + const work: Promise[] = [] + const issues: string[] = [] + const check = (ok: boolean, message: string) => { if (!ok) issues.push(message) } + const observeTask = (task: Promise, expected: string | undefined, label: string, done?: () => void) => { + work.push(task.then( + () => { check(expected === undefined, `${label}: expected ${expected}, resolved`) }, + (error: unknown) => { + check(error instanceof Error && error.message === expected && (expected === busy || error instanceof TypeError), + `${label}: expected ${expected ?? 'success'}, got ${String(error)}`) + }, + ).then(done)) + } + const attach = (rx: Channel) => { + latest.set(rx, { active: false, holder: false }) + detach.set(rx, bridge.attach(id(rx), { + onFrame() {}, + onEvent(event) { if (event.kind === 'fullscreen') latest.set(rx, event) }, + })) + } + const shownOwner = () => dom.owner.get(dom.stack.at(-1)!) + const states = (previous?: readonly Element[]) => { + check([...latest.values()].filter(s => s.active && s.holder).length <= 1, 'Two attached channels report holding fullscreen') + for (const [rx, state] of latest) { + const shown = dom.doc.fullscreenElement + check(state.active === (shown !== null), `${rx}: active=${state.active}, shown=${shown?.id ?? 'none'}`) + if (shown !== null) { + if (rx !== shownOwner() || !coveredAtExit.has(shown)) { + check(state.holder === (rx === shownOwner()), `${rx}: holder=${state.holder}, shown=${shown.id}`) + } + } else if (previous) { + // A channel whose element was on top since fullscreen began may hear that it ended, also after leaving that + // element; a channel with only a pending request held nothing that could end. + if (dom.owner.get(previous.at(-1)!) === rx) check(state.holder, `${rx}: no end reported for its visible fullscreen`) + if (!everTop.has(rx)) check(!state.holder, `${rx}: reported ending fullscreen it never entered`) + } + } + } + // The documented hold: a channel holds from its accepted request until fullscreen ends while none of its requests is + // pending, or until its last request settles while none of its elements has been on top since fullscreen began. The + // document reports only its top, so once a channel showed an element its hold lasts until fullscreen ends. + let hold: Channel | undefined + /** Channels with an element on top since the document entered fullscreen; only they may hear that it ended. */ + const everTop = new Set() + dom.observe((previous) => { + const top = shownOwner() + if (top !== undefined) everTop.add(top) + states(previous) + if (!dom.stack.length) { + everTop.clear() + if (hold !== undefined && pending.get(hold) === 0) hold = undefined + } + }) + for (const rx of channels) attach(rx) + + // The Fullscreen API can only pop the top. Do not require popping an unrelated page element to reach a buried one. + const pageIndex = () => dom.stack.findLastIndex(el => !dom.owner.has(el)) + // An exit pops whatever is on top when it settles, so a page element entering while a channel's exit is in flight can + // be popped in its place. The API offers no exit of one element; such an exit is not required to clear the channel. + const exitsInFlight = new Map(channels.map(rx => [rx, 0])) + const racedExit = new Set() + const leave = (rx: Channel, closing: boolean) => { + const version = attempts.get(rx)! + exitAt.set(rx, version) + for (const el of dom.stack.slice(pageIndex() + 1)) if (dom.owner.get(el) === rx) coveredAtExit.delete(el) + exitsInFlight.set(rx, exitsInFlight.get(rx)! + 1) + const call = closing ? detach.get(rx)!() : bridge.exitFullscreen(id(rx)) + if (closing) { latest.delete(rx); detach.delete(rx) } + observeTask(call, undefined, `${closing ? 'detach' : 'exit'} ${rx}`, () => { + exitsInFlight.set(rx, exitsInFlight.get(rx)! - 1) + if (version === attempts.get(rx)) { + for (const el of dom.stack.slice(0, pageIndex() + 1)) if (dom.owner.get(el) === rx) coveredAtExit.add(el) + } + }) + } + let disposed = false + const dispatch = (action: Action) => { + switch (action[0]) { + case 'request': { + const [, rx, index, outcome] = action + const blocked = hold !== undefined && hold !== rx + const target = dom.elements.get(rx)![index]! + const before = dom.entryCount() + dom.acceptEntry(outcome === 'enter') + if (!blocked) { + hold = rx + attempts.set(rx, attempts.get(rx)! + 1) + pending.set(rx, pending.get(rx)! + 1) + if (outcome === 'enter') coveredAtExit.delete(target) + } + const task = bridge.requestFullscreen(id(rx), target) + const expected = blocked ? busy : outcome === 'refuse' ? 'Entry refused' : undefined + observeTask(task, expected, `request ${target.id}`, () => { + if (blocked) return + pending.set(rx, pending.get(rx)! - 1) + if (hold === rx && pending.get(rx) === 0 && !everTop.has(rx)) hold = undefined + }) + check(dom.entryCount() === before + (blocked ? 0 : 1), `request ${target.id}: expected ${blocked ? 'bridge refusal' : 'DOM request'}`) + break + } + case 'exit': leave(action[1], false); break + case 'reconnect': leave(action[1], true); attach(action[1]); break + case 'Escape': dom.escape(); break + case 'page enters': + for (const rx of channels) if (exitsInFlight.get(rx)! > 0) racedExit.add(rx) + dom.pageEnters() + break + case 'page leaves': dom.pageLeaves(); break + case 'close all': for (const rx of channels) leave(rx, true); break + case 'fail': latest.clear(); bridge.fail('stream failed'); break + case 'dispose': latest.clear(); disposed = true; bridge.dispose(); break + } + states() + } + // Preserve call order inside each burst, not completion order. The last call can tear down in-flight work. + const rounds = bursts.map(burst => [...burst]) + if (!rounds.length) rounds.push([]) + rounds.at(-1)!.push(terminal) + try { + let raced = new Set() + for (const round of rounds) { + const calls = scheduler.scheduleSequence(round.map(action => ({ + label: action.join(' '), builder: async () => { dispatch(action) }, + }))) + await scheduler.waitIdle() + expect((await calls.task).faulty).toBe(false) + await Promise.all(work.splice(0)) + states() + for (const el of dom.stack.slice(pageIndex() + 1)) { + const rx = dom.owner.get(el)! + if (exitAt.get(rx) === attempts.get(rx) && !racedExit.has(rx)) check(coveredAtExit.has(el), `${rx}: exit left ${el.id} fullscreen`) + } + exitAt.clear() + raced = new Set(racedExit) + racedExit.clear() + expect(issues).toEqual([]) + } + // With no intervening page element this checks the entire Chromium stack, not just fullscreenElement === null. + const reachable = dom.stack.slice(pageIndex() + 1).filter(el => !raced.has(dom.owner.get(el)!)) + expect(reachable.map(el => el.id), `orphaned after ${terminal[0]}`).toEqual([]) + } finally { + if (!disposed) bridge.dispose() + await scheduler.waitIdle() + await Promise.all(work) + } +} + +// A shrink and its path replay must start at the same scheduler position. Rebuild it from immutable input for each run. +const scheduleSeed = fc.noShrink(fc.integer()) +function scheduled(run: (scheduler: fc.Scheduler, ...args: T) => Promise) { + return async (seed: number, ...args: T) => { + const scheduler = fc.sample(fc.scheduler(), { seed, numRuns: 1 })[0]! + try { await run(scheduler, ...args) } catch (error) { + const trace = scheduler.report().map(task => `${task.taskId}: ${task.label} (${task.status})`) + throw new Error(trace.join('\n'), { cause: error }) + } + } +} + +// PowerShell replay: set $env:FC_SEED and $env:FC_PATH to the reported seed and path, then rerun the spec with +// -t ''. Set just FC_SEED to explore other schedules without changing the CI sample. +const options = { + numRuns: 100, timeout: 3000, seed: Number(process.env.FC_SEED ?? 314159), + ...(process.env.FC_PATH ? { path: process.env.FC_PATH } : {}), +} +for (const [name, actions] of [['channel elements', channelAction], ['channel and page elements', pageAction]] as const) { + test(`fullscreen ownership across interleaved ${name}`, async () => { + const burst = fc.array(actions as fc.Arbitrary, { minLength: 1, maxLength: 5 }) + await fc.assert(fc.asyncProperty(scheduleSeed, fc.array(burst, { maxLength: 7 }), end, scheduled(checkRun)), options) + }) +} + +test('a refused exit retains the hold and concurrent retries preserve the page fullscreen underneath', async () => { + const indices = fc.array(fc.integer({ min: 0, max: 2 }), { minLength: 1, maxLength: 4 }) + const count = fc.integer({ min: 1, max: 3 }) + await fc.assert(fc.asyncProperty(scheduleSeed, channel, indices, count, scheduled(async (s, rx, moves, retries) => { + const dom = fullscreenDocument(s) + const bridge = bridgeFor(dom.doc) + const other = channels.find(ch => ch !== rx)! + try { + for (const ch of channels) bridge.attach(id(ch), { onFrame() {}, onEvent() {} }) + dom.pageEnters() + const page = dom.doc.fullscreenElement + await s.waitFor(Promise.all(moves.map(i => bridge.requestFullscreen(id(rx), dom.elements.get(rx)![i]!)))) + const before = [...dom.stack] + dom.acceptExit(false) + await expect(s.waitFor(bridge.exitFullscreen(id(rx)))).rejects.toThrow('Exit refused') + expect(dom.stack).toEqual(before) + await expect(s.waitFor(bridge.requestFullscreen(id(other), dom.elements.get(other)![0]!))).rejects.toThrow(busy) + dom.acceptExit(true) + await s.waitFor(Promise.all(Array.from({ length: retries }, () => bridge.exitFullscreen(id(rx))))) + expect(dom.stack.map(el => el.id)).toEqual([page!.id]) + } finally { + dom.acceptExit(true) + bridge.dispose() + await s.waitIdle() + } + })), options) +}) diff --git a/packages/experimental/frame-forwarding/tests/kit-frames-native.e2e.ts b/packages/experimental/frame-forwarding/tests/kit-frames-native.e2e.ts new file mode 100644 index 0000000000..b92d463b07 --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/kit-frames-native.e2e.ts @@ -0,0 +1,309 @@ +/** + * The installed LibreOffice Kit producer renders a two-slide deck through the built receiver and the Host forwarder, + * with Desktop's sink replaced by an in-process native sink that can hold every presented texture. Covers requested frames and + * credit return; a slideshow whose state advances while every credit is held and whose newest slide is delivered once + * credit returns; replacing the engine process, normally and after a crash, on the same channel: the replacement + * connects only after the previous engine's frames are released and receives the channel's viewport; two engines on + * two channels at once; and an engine whose viewport turns invisible returning its idle surfaces to the shared budget. + */ +import { receiverAddon } from './desktop-receiver.ts' +import { spawnSync } from 'node:child_process' +import { existsSync } from 'node:fs' +import { mkdtemp, readFile, rm } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { SharedTextureNativeSink, SharedTextureService } from '@deepseek-ai/dsh-shared-texture' +import type { EditorDocument } from '@deepseek-ai/libreoffice-kit/editor' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' +import { FrameForwarder } from '../src/host/forwarder.ts' +import { FRAME_FORWARDING_PROTOCOL_VERSION, loadFrameForwardingBindings } from '../src/host/native.ts' +import type { FrameChannel } from '../src/host/service.ts' +import type { FrameChannelState, FrameForwardingEvent, FrameForwardingFrameMetadata } from '../src/types.ts' +import { buildFakeSink, type FakeSinkAddon } from './fake-sink.ts' + +const require = createRequire(import.meta.url) +const addon = receiverAddon +const slides = fileURLToPath(new URL('./fixtures/two-slides.pptx', import.meta.url)) +const pixelSource = fileURLToPath(new URL('../../../../apps/desktop/tests/frame-forwarding/fixtures/surface-pixel.cc', import.meta.url)) +const nodeHeaders = join(dirname(process.execPath), '..', 'include', 'node') +const BLUE = 0xff2244cc, GREEN = 0xff22aa44 +const MAX_FRAMES = 3 + +async function nativeKit(): Promise { + if (process.platform !== 'darwin' || !existsSync(addon) || !existsSync(join(nodeHeaders, 'node_api.h'))) return false + // A Kit release built for another protocol version connects to no receiver of this one. + const kitSdkPath = require.resolve('@deepseek-ai/libreoffice-kit/frame-forwarding/sdk') + const kitSdk = JSON.parse(await readFile(kitSdkPath, 'utf8')) as { protocolVersion?: unknown } + if (kitSdk.protocolVersion !== FRAME_FORWARDING_PROTOCOL_VERSION) { + console.warn(`Skipping native Kit frame tests: the installed Kit speaks frame-forwarding protocol ${String(kitSdk.protocolVersion)}, ` + + `and this receiver speaks protocol ${FRAME_FORWARDING_PROTOCOL_VERSION}.`) + return false + } + const { ConversionError, discoverRuntime } = await import('@deepseek-ai/libreoffice-kit') + const runtime = await discoverRuntime().catch((_error: unknown) => undefined) + if (runtime?.backend !== 'native' || !runtime.nativePreview) return false + const { openDocument } = await import('@deepseek-ai/libreoffice-kit/editor') + let probe: EditorDocument + try { + // Native Kit discovery does not initialize the GPU. Forced Ganesh reports unavailable before loading the document. + probe = await openDocument({ bytes: new Uint8Array(await readFile(slides)), format: 'pptx', renderBackend: 'ganesh' }) + } catch (error) { + if (!(error instanceof ConversionError) || error.code !== 'unavailable') throw error + console.warn('Skipping native Kit frame tests: Ganesh GPU rendering is unavailable on this machine.', error.message) + return false + } + try { expect(probe.initialInfo.renderBackend).toBe('ganesh'); return true } + finally { await probe.close() } +} +const available = await nativeKit() + +interface Presented { + readonly metadata: FrameForwardingFrameMetadata + readonly pixel: number + release(): void +} + +let fakes: FakeSinkAddon + +/** Desktop stand-in: a native sink that holds each presented texture, records its center pixel, and releases it when the test does. */ +function desktop(read: (handle: Buffer, width: number, height: number) => number) { + const fake = fakes.create() + const released = new Set() + const pixels = new Map() + const sharedTexture = { + capabilities: async () => ({ supported: true }), + adapterLuid: async () => null, + nativeSink: async () => fake.sink as SharedTextureNativeSink, + } satisfies SharedTextureService + /** Presentations Desktop still holds, oldest first; each read returns a new array. */ + const held = (): Presented[] => fakes.presented(fake.native).filter(entry => !released.has(entry.id)).map((entry) => { + // A held texture stays valid, so its pixel is read when the test first observes it. + if (!pixels.has(entry.id)) pixels.set(entry.id, read(entry.handle, entry.width, entry.height)) + return { + metadata: JSON.parse(entry.metadata) as FrameForwardingFrameMetadata, + pixel: pixels.get(entry.id)!, + release: () => { + if (released.has(entry.id)) return + released.add(entry.id) + fakes.answer(fake.native, entry.id, 'delivered', null) + fakes.answer(fake.native, entry.id, 'settled', false) + }, + } + }) + return { sharedTexture, get held() { return held() }, total: () => fakes.presented(fake.native).length } +} + +describe.skipIf(!available)('LibreOffice Kit frames through the built receiver and the Host forwarder', () => { + let temporary = '' + let document: EditorDocument + let forwarder: FrameForwarder + let channel: FrameChannel + let host: ReturnType + let read: (handle: Buffer, width: number, height: number) => number + const events: Exclude[] = [] + const failures = (): string[] => events.flatMap(event => event.kind === 'error' ? [event.error] : []) + const state = (): FrameChannelState | undefined => events.flatMap(event => event.kind === 'state' ? [event.channel] : []).at(-1) + const open = async (): Promise => { + const { openDocument } = await import('@deepseek-ai/libreoffice-kit/editor') + return openDocument({ bytes: new Uint8Array(await readFile(slides)), format: 'pptx', renderBackend: 'ganesh' }) + } + + beforeAll(async () => { + temporary = await mkdtemp(join(tmpdir(), 'dsh-frame-forwarding-kit-')) + const library = join(temporary, 'surface-pixel.node') + const build = spawnSync('clang++', ['-arch', process.arch === 'x64' ? 'x86_64' : 'arm64', '-std=c++17', `-I${nodeHeaders}`, + '-DNAPI_VERSION=8', '-shared', '-undefined', 'dynamic_lookup', pixelSource, '-framework', 'IOSurface', '-o', library], + { encoding: 'utf8', timeout: 60_000 }) + expect(build.status, build.stdout + build.stderr).toBe(0) + fakes = buildFakeSink(temporary).fakes + const reader = require(library) as { pixel(handle: Buffer, x: number, y: number): number } + read = (handle, width, height) => reader.pixel(handle, width >> 1, height >> 1) + host = desktop(read) + forwarder = new FrameForwarder(host.sharedTexture, () => loadFrameForwardingBindings(addon), + { + maxFrames: MAX_FRAMES, maxBytes: () => 64 * 1024 * 1024, requestTimeoutMs: 10_000, maxPendingRequests: 16 }, + { event: (event) => { events.push(event) }, warn: () => {} }) + document = await open() + channel = await forwarder.channel() + // The engine process is a separate producer that receives a copy of the credential; nothing binds its PID. + await document.attachSurfaceTransport(channel.tx, { timeoutMs: 10_000 }) + await vi.waitFor(() => { expect(state()).toEqual({ state: 'connected', connectionId: 1 }) }) + }, 120_000) + afterAll(async () => { + for (const entry of [...host.held]) entry.release() + try { await document.detachSurfaceTransport() } finally { + await document.close() + await forwarder.closeAll() + await rm(temporary, { recursive: true, force: true }) + } + }, 60_000) + + it('delivers each requested frame by request identifier and regains credit when Desktop releases it', async () => { + expect(await forwarder.setViewport(channel.rx, { version: 1, width: 320, height: 240, deviceScaleFactor: 1, visible: true })) + .toEqual({ applied: true, connectionId: 1 }) + const info = await document.getInfo() + const area = { x: 0, y: 0, width: info.width, height: info.height } + // More requests than the view's credits succeed only because each released frame returns its credit. + for (let index = 0; index < MAX_FRAMES + 2; index++) { + const requestId = `tile-${String(index)}` + await document.renderSurface(area, 320, 240, { requestId, generation: 1 }) + await vi.waitFor(() => { expect(host.held.map(entry => entry.metadata.requestId)).toEqual([requestId]) }) + expect(host.held[0]).toMatchObject({ + pixel: BLUE, metadata: { rx: channel.rx, connectionId: 1, generation: 1, width: 320, height: 240 }, + }) + host.held[0]!.release() + } + expect(failures()).toEqual([]) + }, 60_000) + + it('advances slideshow state while every credit is held and delivers the newest slide once credit returns', async () => { + await document.presentation({ action: 'start', pixelWidth: 320, pixelHeight: 240, part: 0 }) + await forwarder.setViewport(channel.rx, { version: 2, width: 320, height: 240, deviceScaleFactor: 1, visible: true }) + const parts: number[] = [] + const unsubscribe = document.onEvent((event) => { if (event.kind === 'presentation') parts.push(event.part) }) + try { + await document.presentation({ action: 'stream', enabled: true, requestId: 'stream', generation: 2, frameRate: 60 }) + await vi.waitFor(() => { expect(host.held.map(entry => entry.pixel)).toEqual([BLUE]) }, { timeout: 10_000 }) + // Desktop holds every presented frame, as a stalled renderer with slow GPU release would. The slideshow submits + // its newest frame and keeps one surface out of flight, so one frame fewer than the limit is presented. + const inFlight = MAX_FRAMES - 1 + let part = 0 + const toggle = async (): Promise => { + part = 1 - part + await document.presentation({ action: part === 1 ? 'next' : 'previous' }) + } + while (host.held.length < inFlight) { + const before = host.held.length + await toggle() + await vi.waitFor(() => { expect(host.held).toHaveLength(before + 1) }, { timeout: 10_000 }) + } + const exhaustedAt = host.total() + // Without credit the slideshow still advances; an unsent newer state replaces an older one. + for (let step = 0; step < 2; step++) { + await toggle() + await vi.waitFor(() => { expect(parts.at(-1)).toBe(part) }, { timeout: 10_000 }) + } + expect(host.total()).toBe(exhaustedAt) + expect(host.held).toHaveLength(inFlight) + // Releasing one held frame, with no further command, lets the producer deliver its newest state. + host.held[0]!.release() + await vi.waitFor(() => { expect(host.total()).toBe(exhaustedAt + 1) }, { timeout: 10_000 }) + expect(host.held.at(-1)?.pixel).toBe(part === 1 ? GREEN : BLUE) + expect(host.held).toHaveLength(inFlight) + } finally { + unsubscribe() + for (const entry of [...host.held]) entry.release() + await document.presentation({ action: 'stream', enabled: false, requestId: 'stream', generation: 2 }) + await document.presentation({ action: 'stop' }) + } + expect(failures()).toEqual([]) + }, 60_000) + + it('hands the channel to a replacement engine after the previous engine\'s frames are released, normally and after a crash', async () => { + const info = await document.getInfo() + const area = { x: 0, y: 0, width: info.width, height: info.height } + await document.renderSurface(area, 320, 240, { requestId: 'held', generation: 2 }) + await vi.waitFor(() => { expect(host.held).toHaveLength(1) }) + // Normal handoff: the old engine closes its connection; its frame stays valid while Desktop holds it. + await document.detachSurfaceTransport() + await vi.waitFor(() => { expect(state()).toEqual({ state: 'draining', connectionId: 1 }) }) + const replacement = await open() + let attached = false + const attaching = replacement.attachSurfaceTransport(channel.tx, { timeoutMs: 10_000 }).then(() => { attached = true }) + await new Promise(resolve => setTimeout(resolve, 500)) + expect(attached).toBe(false) + expect(host.held[0]!.pixel).toBe(BLUE) + host.held[0]!.release() + await attaching + await document.close() + document = replacement + // The channel replays its latest viewport, so the replacement renders generation 2 without a renderer request. + await vi.waitFor(() => { expect(state()).toEqual({ state: 'connected', connectionId: 2, viewportVersion: 2 }) }) + await document.renderSurface(area, 320, 240, { requestId: 'after-handoff', generation: 2 }) + await vi.waitFor(() => { expect(host.held.map(entry => entry.metadata.requestId)).toEqual(['after-handoff']) }) + expect(host.held[0]!.metadata).toMatchObject({ connectionId: 2, generation: 2 }) + // Crash takeover: the engine process dies while Desktop holds its frame; no reauthorization is needed. + const crashed = document + const failed = new Promise((resolve) => { crashed.onEvent((event) => { if (event.kind === 'failure') resolve() }) }) + process.kill(crashed.processId, 'SIGKILL') + await failed + await vi.waitFor(() => { expect(state()).toMatchObject({ state: 'draining', connectionId: 2 }) }) + const successor = await open() + const taking = successor.attachSurfaceTransport(channel.tx, { timeoutMs: 10_000 }) + host.held[0]!.release() + await taking + await crashed.close().catch(() => {}) + document = successor + await vi.waitFor(() => { expect(state()).toEqual({ state: 'connected', connectionId: 3, viewportVersion: 2 }) }) + await document.renderSurface(area, 320, 240, { requestId: 'after-crash', generation: 2 }) + await vi.waitFor(() => { expect(host.held.map(entry => entry.metadata.connectionId)).toEqual([3]) }) + host.held[0]!.release() + expect(failures()).toEqual([]) + }, 90_000) + + it('renders two engines on two channels at once without crossing their frames', async () => { + const other = await open() + const second = await forwarder.channel() + try { + await other.attachSurfaceTransport(second.tx, { timeoutMs: 10_000 }) + await vi.waitFor(() => { expect(forwarder.snapshot().find(entry => entry.rx === second.rx)?.channel).toMatchObject({ state: 'connected' }) }) + const viewport = { version: 3, width: 320, height: 240, deviceScaleFactor: 1, visible: true } + await forwarder.setViewport(channel.rx, viewport) + await forwarder.setViewport(second.rx, { ...viewport, version: 1 }) + const info = await document.getInfo() + const area = { x: 0, y: 0, width: info.width, height: info.height } + await Promise.all([ + document.renderSurface(area, 320, 240, { requestId: 'first', generation: 3 }), + other.renderSurface(area, 320, 240, { requestId: 'second', generation: 1 }), + ]) + await vi.waitFor(() => { expect(host.held).toHaveLength(2) }) + const byRequest = Object.fromEntries(host.held.map(entry => [entry.metadata.requestId, entry])) + expect(byRequest.first).toMatchObject({ pixel: BLUE, metadata: { rx: channel.rx, generation: 3 } }) + expect(byRequest.second).toMatchObject({ pixel: BLUE, metadata: { rx: second.rx, generation: 1 } }) + for (const entry of [...host.held]) entry.release() + } finally { + await other.detachSurfaceTransport().catch(() => {}) + await other.close() + await forwarder.close(second.rx) + } + expect(failures()).toEqual([]) + }, 90_000) + + it('returns the idle surfaces of an engine whose viewport turns invisible to another channel waiting for budget', async () => { + // The window budget fits one 320x240 surface, so the second engine allocates only after the first returns its own. + const shared = desktop(read) + const tight = new FrameForwarder(shared.sharedTexture, () => loadFrameForwardingBindings(addon), + { + maxFrames: MAX_FRAMES, maxBytes: () => 450 * 1024, requestTimeoutMs: 10_000, maxPendingRequests: 16 }, + { event: () => {}, warn: () => {} }) + const hidden = await open(), visible = await open() + try { + const [first, second] = [await tight.channel(), await tight.channel()] + await hidden.attachSurfaceTransport(first.tx, { timeoutMs: 10_000 }) + await visible.attachSurfaceTransport(second.tx, { timeoutMs: 10_000 }) + const viewport = { version: 1, width: 320, height: 240, deviceScaleFactor: 1, visible: true } + await tight.setViewport(first.rx, viewport) + await tight.setViewport(second.rx, viewport) + const info = await hidden.getInfo() + const area = { x: 0, y: 0, width: info.width, height: info.height } + await hidden.renderSurface(area, 320, 240, { requestId: 'hidden', generation: 1 }) + await vi.waitFor(() => { expect(shared.held.map(entry => entry.metadata.requestId)).toEqual(['hidden']) }) + shared.held[0]!.release() + const waiting = visible.renderSurface(area, 320, 240, { requestId: 'visible', generation: 1 }) + await new Promise(resolve => setTimeout(resolve, 500)) + expect(shared.held).toEqual([]) + await tight.setViewport(first.rx, { ...viewport, version: 2, visible: false }) + await waiting + await vi.waitFor(() => { expect(shared.held.map(entry => entry.metadata.rx)).toEqual([second.rx]) }) + shared.held[0]!.release() + } finally { + for (const engine of [hidden, visible]) { + await engine.detachSurfaceTransport().catch(() => {}) + await engine.close() + } + await tight.closeAll() + } + }, 90_000) +}) diff --git a/packages/experimental/frame-forwarding/tests/malicious-producer.e2e.ts b/packages/experimental/frame-forwarding/tests/malicious-producer.e2e.ts new file mode 100644 index 0000000000..e80acd7c4e --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/malicious-producer.e2e.ts @@ -0,0 +1,202 @@ +/** Host receiver rejects hostile native packets without consuming another connection's credit or budget. */ +import { receiverAddon } from './desktop-receiver.ts' +import { spawn } from 'node:child_process' +import { once } from 'node:events' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { loadFrameForwardingBindings } from '../src/host/native.ts' +import type { FrameForwardingBindings, FrameForwardingReceiverEvent } from '../src/host/native.ts' +import { FrameForwarder } from '../src/host/forwarder.ts' +import type { SharedTextureNativeSink, SharedTextureService } from '@deepseek-ai/dsh-shared-texture' +import { buildFakeSink, type FakeSinkAddon } from './fake-sink.ts' + +type Event = FrameForwardingReceiverEvent + +describe.skipIf(process.platform !== 'darwin')('malicious producer over the receiver transport', { retry: 0 }, () => { + let temporary: string + let executable: string + let bindings: FrameForwardingBindings + let fakes: FakeSinkAddon + beforeAll(async () => { + temporary = await mkdtemp(join(tmpdir(), 'dsh-malicious-producer-')) + const built = buildFakeSink(temporary) + fakes = built.fakes + const native = fileURLToPath(new URL('../native/', import.meta.url)) + const source = fileURLToPath(new URL('../../../../apps/desktop/tests/frame-forwarding/fixtures/malicious-producer.cc', import.meta.url)) + executable = join(temporary, 'producer') + built.run('clang++', ['-std=c++17', `-I${native}`, source, join(native, 'transport.cc'), + '-framework', 'IOSurface', '-framework', 'CoreFoundation', '-lbsm', '-o', executable]) + bindings = loadFrameForwardingBindings(receiverAddon) + }, 120_000) + afterAll(async () => { if (temporary !== undefined) await rm(temporary, { recursive: true, force: true }) }) + + function peer(mode: string, tx: string) { + const child = spawn(executable, [tx, mode], { stdio: ['ignore', 'pipe', 'pipe'] }) + const exited = once(child, 'exit') + let stderr = '' + child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString() }) + return { child, exited, stderr: () => stderr, async stop() { + if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL') + await exited + } } + } + /** Await a producer exit, so a producer that hangs fails its own test instead of stalling the suite. */ + async function exited(producer: ReturnType, timeout = 30_000) { + let timer: ReturnType | undefined + try { + await Promise.race([producer.exited, new Promise((_, reject) => { + timer = setTimeout(() => { reject(new Error('the producer did not exit within its deadline')) }, timeout) + })]) + } finally { if (timer !== undefined) clearTimeout(timer) } + } + function receiver() { + const events: Event[] = [] + const value = bindings.createReceiver({ maxFrames: 3, maxBytes: 16384, budget: bindings.createBudget(16384), + displayAdapter: null, readbackTimeoutMs: 10_000 }, (event) => { + events.push(event) + if (event.type === 'message' && event.text === 'armed') value.send(event.connectionId, 'go') + }) + return { value, events, release() { + for (const event of events) if (event.type === 'frame') value.release(event.deliveryId) + }, async wait(type: Event['type']) { + await expect.poll(() => events.some(event => event.type === type)).toBe(true) + } } + } + it.each([ + ['MP-01 oversize', 'oversize', /Invalid frame-forwarding frame fields/], + ['MP-02 zero', 'zero', /Invalid frame-forwarding frame fields/], + ['MP-03 short stride', 'stride-minus', /Invalid frame-forwarding frame fields/], + ['MP-03 mismatched stride', 'stride-plus', /IOSurface format or dimensions differ/], + ['MP-04 wrong format', 'format', /IOSurface format or dimensions differ/], + ['MP-05 multiplane', 'planes', /IOSurface format or dimensions differ/], + ['MP-06 allocation over budget', 'allocation', /Invalid frame-forwarding allocation request/], + ['MP-07 allocation reuse', 'allocation-reuse', /Invalid frame-forwarding allocation request/], + ['MP-07 frame reuse', 'frame-reuse', /frame budget or identifier violated/], + ['MP-08 foreign connection', 'foreign', /packet for another connection/], + ['MP-09 deallocate in flight', 'deallocate', /in-use frame-forwarding allocation/], + ['MP-15 unterminated metadata', 'metadata', /invalid packet/], + ])('%s disconnects only the producer and returns the shared budget', async (_name, mode, diagnostic) => { + const f = receiver(); const producer = peer(mode, f.value.tx) + try { + await f.wait('disconnected') + expect(f.events.find(event => event.type === 'disconnected')?.text, producer.stderr()).toMatch(diagnostic) + expect(f.events.some(event => event.type === 'failed')).toBe(false) + if (mode !== 'frame-reuse' && mode !== 'deallocate') expect(f.events.filter(event => event.type === 'frame')).toHaveLength(0) + f.release(); await f.wait('drained') + const first = f.events.find(event => event.type === 'connected')! + const delivered = f.events.filter(event => event.type === 'frame').length + const successor = peer('valid', f.value.tx) + try { + await expect.poll(() => f.events.filter(event => event.type === 'frame').length).toBeGreaterThan(delivered) + const last = f.events.findLast(event => event.type === 'connected')! + expect(last.connectionId).toBeGreaterThan(first.connectionId) + expect(f.events.filter(event => event.type === 'failed')).toHaveLength(0) + } finally { await successor.stop(); f.release() } + } finally { await producer.stop(); f.release(); await f.value.close() } + }) + it('MP-17 an oversized Mach message to the listener leaves the channel and its producer working', async () => { + const f = receiver(); const producer = peer('valid', f.value.tx) + try { + await f.wait('frame') + const oversized = peer('mach-oversize', f.value.tx) + await oversized.exited + expect(oversized.child.exitCode, oversized.stderr()).toBe(0) + // The listener reads its port in order, so a later candidate refused as busy shows it read the oversized message + // and kept serving the channel. + const busy = peer('valid', f.value.tx) + try { + await expect.poll(() => f.events.some(event => event.type === 'rejected'), { timeout: 10_000 }).toBe(true) + expect(f.events.filter(event => event.type === 'rejected').map(event => event.type === 'rejected' && event.text)).toContain('channel-busy') + expect(f.events.some(event => event.type === 'failed' || event.type === 'disconnected')).toBe(false) + } finally { await busy.stop() } + } finally { await producer.stop(); f.release(); await f.value.close() } + }) + it.each([['MP-18 mach-move-receive', 'mach-move-receive'], ['MP-19 mach-reply-port', 'mach-reply-port'], + ['MP-20 mach-forged-notice-channel', 'mach-forged-notice-channel']])( + '%s destroys the message and keeps the connection', async (_name, mode) => { + // Each mode sends a hostile message carrying an unexpected right or forged kernel notification: a transferred + // receive right (which would leave the producer's send right alive), a send-once reply right in a protocol + // header, or forged dead-name/no-senders notices (with and without reply rights). The producer exits 0 only + // after observing every reply/transferred right destroyed and receiving the answer to the normal message behind it. + const f = receiver(); const producer = peer(mode, f.value.tx) + try { + await exited(producer) + expect(producer.child.signalCode).toBeNull() + expect(producer.child.exitCode, producer.stderr()).toBe(0) + expect(f.events.some(event => event.type === 'failed')).toBe(false) + expect(f.events.some(event => event.type === 'message' && event.text === 'smuggled')).toBe(false) + expect(f.events.some(event => event.type === 'message' && event.text === 'armed')).toBe(true) + } finally { await producer.stop(); f.release(); await f.value.close() } + }, 120_000) + it('MP-21 forged notifications with reply rights to the listener destroy the rights and keep serving', async () => { + const f = receiver(); const producer = peer('valid', f.value.tx) + try { + await f.wait('frame') + const forged = peer('mach-forged-notice-listener', f.value.tx) + await exited(forged) + expect(forged.child.signalCode).toBeNull() + expect(forged.child.exitCode, forged.stderr()).toBe(0) + const busy = peer('valid', f.value.tx) + try { + await expect.poll(() => f.events.some(event => event.type === 'rejected'), { timeout: 10_000 }).toBe(true) + expect(f.events.filter(event => event.type === 'rejected').map(event => event.type === 'rejected' && event.text)).toContain('channel-busy') + expect(f.events.some(event => event.type === 'failed' || event.type === 'disconnected')).toBe(false) + } finally { await busy.stop() } + } finally { await producer.stop(); f.release(); await f.value.close() } + }, 120_000) + it('MP-14 crash preserves the in-flight surface until release, then admits a successor', async () => { + const f = receiver(); const producer = peer('valid', f.value.tx) + try { + await f.wait('frame'); await producer.stop(); await f.wait('disconnected') + expect(f.events.some(event => event.type === 'drained')).toBe(false) + f.release(); await f.wait('drained') + expect(f.events.some(event => event.type === 'failed')).toBe(false) + } finally { await producer.stop(); f.release(); await f.value.close() } + }) + it('MP-10 credit bounds 1000 Hz submission attempts and releases every delivery', async () => { + const f = receiver(); const producer = peer('flood', f.value.tx) + const timer = setInterval(() => { f.release() }, 1) + try { + await expect.poll(() => f.events.find(event => event.type === 'message' && event.text.includes('attempts')), { timeout: 10_000 }).toBeDefined() + const report = f.events.find(event => event.type === 'message' && event.text.includes('attempts'))! + expect(report.type).toBe('message') + if (report.type !== 'message') throw new Error('Missing flood report') + const stats = JSON.parse(report.text) as { attempts: number; submitted: number } + expect(stats.attempts).toBe(1000); expect(stats.submitted).toBeGreaterThan(1); expect(stats.submitted).toBeLessThanOrEqual(1001) + expect(f.events.some(event => event.type === 'disconnected' || event.type === 'failed')).toBe(false) + await producer.stop(); f.release(); await f.wait('drained') + } finally { clearInterval(timer); await producer.stop(); f.release(); await f.value.close() } + }) + it.each(['metadata-deep', 'metadata-utf8', 'invisible'])('MP-15/16 Host drops %s without calling Desktop', async (mode) => { + const events: Event[] = [] + const errors: string[] = [] + const fake = fakes.create() + let nativeReceiver: ReturnType | undefined + const service = { + capabilities: async () => ({ supported: true }), adapterLuid: async () => null, + nativeSink: async () => fake.sink as SharedTextureNativeSink, + } satisfies SharedTextureService + const forwarder = new FrameForwarder(service, () => ({ ...bindings, createReceiver(options, listener) { + nativeReceiver = bindings.createReceiver(options, (event) => { events.push(event); listener(event) }) + return nativeReceiver + } }), { maxFrames: 3, maxBytes: () => 65536, + requestTimeoutMs: 10_000, maxPendingRequests: 8 }, { event: (event) => { if (event.kind === 'error' && event.error.startsWith('Invalid native frame metadata:')) errors.push(event.error) }, warn: () => {} }) + const channel = await forwarder.channel() + const producer = peer(mode, channel.tx) + try { + await expect.poll(() => events.find(event => event.type === 'message' && event.text === 'armed')).toBeDefined() + await forwarder.setViewport(channel.rx, { version: 1, width: 64, height: 64, deviceScaleFactor: 1, visible: mode !== 'invisible' }) + const connection = events.find(event => event.type === 'connected')! + nativeReceiver!.send(connection.connectionId, 'go') + // Every mode's metadata is invalid: the invisible producer names an empty request. + await expect.poll(() => errors.length).toBe(1) + expect(fakes.presented(fake.native)).toEqual([]); expect(forwarder.isOpen(channel.rx)).toBe(true) + expect(events.some(event => event.type === 'frame')).toBe(false) + await producer.stop() + await expect.poll(() => forwarder.snapshot()[0]?.channel.state).toBe('idle') + } finally { await producer.stop(); await forwarder.closeAll() } + }) +}) diff --git a/packages/experimental/frame-forwarding/tests/mount.client.spec.ts b/packages/experimental/frame-forwarding/tests/mount.client.spec.ts new file mode 100644 index 0000000000..1f8583972d --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/mount.client.spec.ts @@ -0,0 +1,173 @@ +// @vitest-environment jsdom +/** The Client plugin mounts its Remote, provides the renderer-side service in the Desktop document, and relays channel states. */ +import { Context } from '@deepseek-ai/cordis' +import type { TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol' +import type { SharedTextureClientExport, SharedTextureLease } from '@deepseek-ai/dsh-shared-texture/client' +import { afterEach, expect, test, vi } from 'vitest' +import * as plugin from '../src/client/mount.ts' +import type { FrameRxEvent } from '../src/client/api.ts' +import type { FrameRxId } from '../src/types.ts' + +afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); Reflect.deleteProperty(document, 'fullscreenElement') }) + +const contribution: TypertRemoteContribution = { package: '@deepseek-ai/dsh-frame-forwarding', descriptors: [] } +const rx = 'rx-1' as FrameRxId + +test('exports the mount, its injections, and the renderer-side classes at runtime', () => { + expect(Object.keys(plugin).sort()).toEqual(['inject', 'mountFrameForwarding']) + expect(plugin.inject).toEqual(['remote']) +}) + +function fixture(stream: () => AsyncIterable, textures = true) { + const order: string[] = [] + const viewport = vi.fn(async () => ({ ok: true as const, value: { applied: true, connectionId: 1 } })) + const events = vi.fn() + let consumer: ((lease: SharedTextureLease) => void) | undefined + let streamOptions: { open(signal: AbortSignal): unknown; ended(): Error } | undefined + const remote = { + frameForwarding: { viewport, events }, + $mount: vi.fn(async () => async () => { order.push('remote') }), + $stream: vi.fn((options: NonNullable) => { + streamOptions = options + return { [Symbol.asyncIterator]: () => stream()[Symbol.asyncIterator](), dispose: vi.fn(async () => { order.push('events') }) } + }), + } + const onFrame = (listener: (lease: SharedTextureLease) => void): (() => void) => { + consumer = listener + return () => { consumer = undefined } + } + Object.defineProperty(document, 'fullscreenElement', { configurable: true, value: null }) + const ctx = new Context() + if (textures) ctx.provide('sharedTexture', { onFrame } satisfies SharedTextureClientExport) + ctx.provide('remote', remote as never) + ctx.provide('remote.frameForwarding', remote.frameForwarding as never) + const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + const deliver = (lease: SharedTextureLease): void => { if (consumer === undefined) lease.release(); else consumer(lease) } + return { ctx, remote, viewport, events, order, warn, deliver, options: () => streamOptions!, consuming: () => consumer !== undefined } +} + +test('provides no service outside the Desktop document and withdraws the Remote on dispose', async () => { + const f = fixture(() => (async function* () {})(), false) + const dispose = await plugin.mountFrameForwarding(f.ctx, contribution) + expect(f.remote.$mount).toHaveBeenCalledExactlyOnceWith(contribution) + expect(f.ctx.get('frameForwarding')).toBeUndefined() + expect(f.remote.$stream).not.toHaveBeenCalled() + await dispose() + expect(f.order).toEqual(['remote']) + await f.ctx.fiber.dispose() +}) + +test('connects channels that route textures by metadata, send viewports to the Host, and follow Host channel states', async () => { + const closed = Promise.withResolvers() + const accept = vi.fn() + const f = fixture(() => (async function* () { + yield { value: { kind: 'snapshot', channels: [{ rx, sequence: 1, channel: { state: 'connected', connectionId: 1 } }] }, accept } + await closed.promise + yield { value: { kind: 'state', rx, sequence: 2, channel: { state: 'closed', cause: 'lost', reason: 'Desktop invalidated a presented frame' } }, accept } + })()) + const dispose = await plugin.mountFrameForwarding(f.ctx, contribution) + const service = f.ctx.get('frameForwarding')! + const channel = service.connect(rx) + await vi.waitFor(() => { expect(channel.connectionId).toBe(1) }) + await channel.setViewport({ version: 1, width: 4, height: 2, deviceScaleFactor: 1, visible: true }) + expect(f.viewport).toHaveBeenCalledWith(rx, expect.objectContaining({ version: 1 })) + const present = vi.fn(), failure = vi.fn() + channel.consume(present, failure) + const lease = { frame: {} as VideoFrame, metadata: { rx, connectionId: 1, requestId: 'tile', frameId: 1, generation: 1, revision: 0, width: 4, height: 2 }, release: vi.fn() } + const stray = { frame: {} as VideoFrame, metadata: { ...lease.metadata, rx: 'other' }, release: vi.fn() } + f.deliver(stray) + f.deliver(lease) + expect(present).toHaveBeenCalledExactlyOnceWith({ image: lease.frame, metadata: lease.metadata }) + await vi.waitFor(() => { expect(lease.release).toHaveBeenCalledOnce() }) + expect(stray.release).toHaveBeenCalledOnce() + const cancelled = new AbortController() + const discarded = channel.ready(cancelled.signal) + cancelled.abort() + expect(service.discardReason(await discarded.catch((error: unknown) => error))).toBe('cancelled') + expect(service.discardReason(new Error('other'))).toBeUndefined() + closed.resolve(undefined) + expect(await channel.closed).toBe('lost') + expect(service.discardReason(failure.mock.calls[0]![0])).toBe('lost') + expect(accept).toHaveBeenCalledTimes(2) + const signal = new AbortController().signal + f.options().open(signal) + expect(f.events).toHaveBeenCalledExactlyOnceWith(signal) + expect(f.options().ended().message).toBe('Frame-forwarding channel events ended.') + await channel.close() + // The Client keeps consuming Desktop's textures with no channel open, until it is disposed. + expect(f.consuming()).toBe(true) + await dispose() + expect(f.consuming()).toBe(false) + expect(f.order).toEqual(['events', 'remote']) + await f.ctx.fiber.dispose() +}) + +test('a terminal event stream failure fails every channel and every later connection while the service stays provided', async () => { + const broken = Promise.withResolvers() + const f = fixture(() => (async function* () { + yield { value: { kind: 'snapshot', channels: [{ rx, sequence: 1, channel: { state: 'connected', connectionId: 1 } }] }, accept: vi.fn() } + await broken.promise + throw new Error('stream broke') + })(), true) + // The display is never flushed, so it stays reserved without selecting a presenter. + vi.stubGlobal('requestAnimationFrame', vi.fn(() => 1)) + vi.stubGlobal('cancelAnimationFrame', vi.fn()) + vi.stubGlobal('ResizeObserver', class { disconnect = vi.fn(); observe() {} }) + vi.stubGlobal('IntersectionObserver', class { disconnect = vi.fn(); observe() {} }) + const dispose = await plugin.mountFrameForwarding(f.ctx, contribution) + const service = f.ctx.get('frameForwarding')! + const channel = service.connect(rx) + await vi.waitFor(() => { expect(channel.connectionId).toBe(1) }) + const events: FrameRxEvent[] = [] + channel.onEvent(event => events.push(event)) + const element = document.createElement('div') + document.body.append(element) + const mountFailure = vi.fn() + channel.mount(element, mountFailure) + expect(element.getAttribute('data-dsh-frame-mount')).toBe('video') + broken.resolve(undefined) + const message = 'Frame-forwarding channel events failed: stream broke' + expect(await channel.closed).toBe('failed') + expect(f.warn).toHaveBeenCalledWith(expect.objectContaining({ message: 'stream broke' })) + expect(events.at(-1)).toEqual({ kind: 'failure', error: message }) + expect(element.hasAttribute('data-dsh-frame-mount')).toBe(false) + expect(mountFailure).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ message })) + const lease = { frame: {} as VideoFrame, metadata: { rx, connectionId: 1, requestId: 'tile', frameId: 1, generation: 0, revision: 0, width: 4, height: 2 }, release: vi.fn() } + f.deliver(lease) + expect(lease.release).toHaveBeenCalledOnce() + expect(f.ctx.get('frameForwarding')).toBe(service) + const later = service.connect('rx-2' as FrameRxId) + expect(await later.closed).toBe('failed') + expect(() => later.consume(vi.fn(), vi.fn())).toThrow(message) + expect(() => later.mount(element, vi.fn())).toThrow(message) + await channel.close() + await later.close() + element.remove() + await dispose() + await f.ctx.fiber.dispose() +}) + +test('a terminal event stream failure that is not an Error fails channels with its text', async () => { + const f = fixture(() => (async function* () { throw 'stream gone' })()) + const dispose = await plugin.mountFrameForwarding(f.ctx, contribution) + await vi.waitFor(() => { expect(f.warn).toHaveBeenCalledWith('stream gone') }) + const channel = f.ctx.get('frameForwarding')!.connect(rx) + const events: FrameRxEvent[] = [] + channel.onEvent(event => events.push(event)) + expect(await channel.closed).toBe('failed') + // The channel failed while connecting, so a later subscription receives nothing. + expect(events).toEqual([]) + expect(() => channel.ready()).toThrow('Frame-forwarding channel events failed: stream gone') + await channel.close() + await dispose() + await f.ctx.fiber.dispose() +}) + +test('a failed service registration withdraws the mounted Remote contribution', async () => { + const f = fixture(() => (async function* () {})()) + f.remote.$stream.mockImplementationOnce(() => { throw new Error('stream unavailable') }) + await expect(plugin.mountFrameForwarding(f.ctx, contribution)).rejects.toThrow('stream unavailable') + expect(f.order).toEqual(['remote']) + expect(f.consuming()).toBe(false) + await f.ctx.fiber.dispose() +}) diff --git a/packages/experimental/frame-forwarding/tests/native.host.spec.ts b/packages/experimental/frame-forwarding/tests/native.host.spec.ts new file mode 100644 index 0000000000..d690faaf0f --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/native.host.spec.ts @@ -0,0 +1,145 @@ +/** + * The addon binding checks the build record, wraps the receiver's Node-API exports, reads the fields of presentation + * errors, and rejects protocol mismatches before loading the addon. + */ +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, test } from 'vitest' +import { + FRAME_FORWARDING_CAPABILITIES, FRAME_FORWARDING_PROTOCOL_VERSION, loadFrameForwardingBindings, +} from '../src/host/native.ts' +import type { FrameConnectionId } from '../src/types.ts' +import type { FrameForwardingReceiverEvent } from '../src/host/native.ts' + +const roots: string[] = [] +afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))) }) + +const platform = `${process.platform}-${process.arch}` +const current = { platform, protocolVersion: FRAME_FORWARDING_PROTOCOL_VERSION, capabilities: FRAME_FORWARDING_CAPABILITIES } +const connection = 1 as FrameConnectionId + +/** A CommonJS stand-in for the addon that records every call, with the build record the loader requires. */ +async function fakeAddon(record: object | null = current): Promise { + const root = await mkdtemp(join(tmpdir(), 'frame-forwarding-addon-')) + roots.push(root) + const file = join(root, 'frame-forwarding.cjs') + await writeFile(join(root, 'frame-forwarding.json'), JSON.stringify(record)) + await writeFile(file, ` + const calls = [] + module.exports = { + calls, + createBudget: bytes => ({ bytes }), + create: (maxFrames, maxBytes, onEvent, ...options) => { + calls.push(['create', maxFrames, maxBytes, ...options]) + module.exports.emit = onEvent + onEvent({ type: 'connected', connectionId: 1, pid: 7 }) + return { native: { id: 'native' }, tx: '1|7|secret|name' } + }, + send: (native, connectionId, json) => calls.push(['send', native.id, connectionId, json]), + release: (native, deliveryId) => { calls.push(['release', native.id, deliveryId]); return deliveryId === 1 }, + attachSink: (native, rx, sink, timeoutMs) => calls.push(['attachSink', native.id, rx, sink, timeoutMs]), + setDeliverable: (native, state) => calls.push(['setDeliverable', native.id, state]), + close: (native) => { calls.push(['close', native.id]); return Promise.resolve() }, + } + `) + return file +} + +test('the loader expects the protocol version and handshake capabilities the native sources declare', async () => { + const header = await readFile(new URL('../native/transport.h', import.meta.url), 'utf8') + expect(FRAME_FORWARDING_PROTOCOL_VERSION).toBe(2) + expect(Number(/DSH_FRAME_FORWARDING_PROTOCOL_VERSION (\d+)/u.exec(header)?.[1])).toBe(FRAME_FORWARDING_PROTOCOL_VERSION) +}) + +test.each([ + ['another platform', { ...current, platform: 'other-arch' }], + ['another protocol version', { ...current, protocolVersion: FRAME_FORWARDING_PROTOCOL_VERSION + 1 }], + ['the fixed-size packets of protocol 1', { ...current, protocolVersion: 1 }], + ['a protocol 1 receiver without transferable channels', { platform, protocolVersion: FRAME_FORWARDING_PROTOCOL_VERSION }], + ['other capabilities', { ...current, capabilities: ['transferable-tx', 'other'] }], + ['the capabilities of the 0.2.2 receiver', { ...current, capabilities: ['transferable-tx'] }], + ['capabilities that are not a list', { ...current, capabilities: 'transferable-tx' }], + ['no fields', null], +])('refuses an addon whose build record names %s', async (_name, record) => { + const path = await fakeAddon(record) + expect(() => loadFrameForwardingBindings(path)).toThrow('install a compatible Desktop build') +}) + +test('requires an absolute addon path supplied by Desktop', () => { + expect(() => loadFrameForwardingBindings('frame-forwarding.node')).toThrow('must be absolute') +}) + +test('refuses an addon without a build record', () => { + expect(() => loadFrameForwardingBindings(join(tmpdir(), 'missing-frame-forwarding', 'frame-forwarding.node'))).toThrow() +}) + +test('wraps budgets and receivers over the addon exports', async () => { + const bindings = loadFrameForwardingBindings(await fakeAddon()) + const events: FrameForwardingReceiverEvent[] = [] + const budget = bindings.createBudget(4096) + const receiver = bindings.createReceiver({ + maxFrames: 2, maxBytes: 4096, budget, displayAdapter: null, readbackTimeoutMs: 500, + }, event => events.push(event)) + expect(receiver.tx).toBe('1|7|secret|name') + expect(events).toEqual([{ type: 'connected', connectionId: 1, pid: 7 }]) + receiver.send(connection, '{"type":"viewport"}') + expect(receiver.release(1 as never)).toBe(true) + expect(receiver.release(2 as never)).toBe(false) + const first = receiver.close() + expect(receiver.close()).toBe(first) + await first + expect(() => bindings.createReceiver({ + maxFrames: 1, maxBytes: 1, budget: Object.freeze({}) as never, displayAdapter: 'd' as never, readbackTimeoutMs: 1, + }, () => {})).toThrow('budget from createBudget()') +}) + +test('passes a display adapter string and connection-scoped control through to the addon', async () => { + const path = await fakeAddon() + const bindings = loadFrameForwardingBindings(path) + // The binding and the spec share Node's CommonJS cache, so this is the instance the binding drives. + const addon = createRequire(import.meta.url)(path) as { calls: unknown[][] } + const receiver = bindings.createReceiver({ + maxFrames: 3, maxBytes: 8192, budget: bindings.createBudget(8192), displayAdapter: '0:1' as never, readbackTimeoutMs: 10, + }, () => {}) + receiver.send(4 as FrameConnectionId, '{"type":"viewport"}') + receiver.release(1 as never) + const sink = Object.freeze({ sink: true }) + receiver.attachSink('rx-1', sink, 5000) + receiver.setDeliverable({ connectionId: 4 as FrameConnectionId, visible: true, maxGeneration: 2 }) + receiver.setDeliverable(null) + await receiver.close() + expect(addon.calls).toEqual([ + ['create', 3, 8192, { bytes: 8192 }, '0:1', 10], ['send', 'native', 4, '{"type":"viewport"}'], + ['release', 'native', 1], ['attachSink', 'native', 'rx-1', sink, 5000], + ['setDeliverable', 'native', { connectionId: 4, visible: true, maxGeneration: 2 }], ['setDeliverable', 'native', null], + ['close', 'native'], + ]) +}) + +test('reads the source, request, and error of a presentation error, and passes other events unchanged', async () => { + const path = await fakeAddon() + const bindings = loadFrameForwardingBindings(path) + const addon = createRequire(import.meta.url)(path) as { emit(event: object): void } + const events: FrameForwardingReceiverEvent[] = [] + bindings.createReceiver({ + maxFrames: 1, maxBytes: 4096, budget: bindings.createBudget(4096), displayAdapter: null, readbackTimeoutMs: 10, + }, event => events.push(event)) + const error = (text: string) => { addon.emit({ type: 'presentation-error', connectionId: 1, text }) } + error('{"source":"presentation","requestId":"tile","error":"Native frame transfer failed: renderer import failed"}') + error('{"source":"producer","error":"Invalid native frame metadata: metadata is not valid JSON"}') + error('{"source":"producer","requestId":7,"error":"unnamed request"}') + // Text the receiver did not write as presentation-error JSON is reported as a presentation failure. + for (const text of ['not json', 'null', '{"source":"desktop","error":"x"}', '{"source":"producer","error":1}', '{"error":"x"}', '{"source":"producer"}']) + error(text) + addon.emit({ type: 'presentation-invalidated', connectionId: 1, text: 'Desktop invalidated a presented frame' }) + expect(events.slice(1)).toEqual([ + { type: 'presentation-error', connectionId: 1, source: 'presentation', requestId: 'tile', text: 'Native frame transfer failed: renderer import failed' }, + { type: 'presentation-error', connectionId: 1, source: 'producer', text: 'Invalid native frame metadata: metadata is not valid JSON' }, + { type: 'presentation-error', connectionId: 1, source: 'producer', text: 'unnamed request' }, + ...['not json', 'null', '{"source":"desktop","error":"x"}', '{"source":"producer","error":1}', '{"error":"x"}', '{"source":"producer"}'] + .map(text => ({ type: 'presentation-error', connectionId: 1, source: 'presentation', text })), + { type: 'presentation-invalidated', connectionId: 1, text: 'Desktop invalidated a presented frame' }, + ]) +}) diff --git a/packages/experimental/frame-forwarding/tests/receiver-native.e2e.ts b/packages/experimental/frame-forwarding/tests/receiver-native.e2e.ts new file mode 100644 index 0000000000..4838a71ede --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/receiver-native.e2e.ts @@ -0,0 +1,328 @@ +/** + * The built receiver addon serves producer processes built from test fixtures over one transferable channel: a + * copied credential connects without PID binding, a successor takes over after the previous connection drains, mixed + * builds are refused, a trimmed producer returns its idle allocation to the shared budget, crashed and graceful + * reconnects leave no dead name behind, a successor that dies before ready loses its place, and close settles without + * libuv handles. + */ +import { receiverAddon } from './desktop-receiver.ts' +import { spawn, spawnSync, type ChildProcess } from 'node:child_process' +import { once } from 'node:events' +import { existsSync } from 'node:fs' +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { loadFrameForwardingBindings } from '../src/host/native.ts' +import type { FrameForwardingBindings, FrameForwardingReceiver, FrameForwardingReceiverEvent } from '../src/host/native.ts' +import type { FrameConnectionId } from '../src/types.ts' + +const addon = receiverAddon +const native = fileURLToPath(new URL('../native/', import.meta.url)) +const fixtures = fileURLToPath(new URL('../../../../apps/desktop/tests/frame-forwarding/fixtures/', import.meta.url)) +const fixture = fileURLToPath(new URL('../../../../apps/desktop/tests/frame-forwarding/fixtures/producer.cc', import.meta.url)) +type Event = FrameForwardingReceiverEvent +/** Dead names of the process running the receiver, and their references, from `fixtures/mach-port-census.cc`. */ +interface PortCensus { deadNames: number; deadNameRefs: number } + +/** One receiver whose events are read in order; a channel failure fails the read. */ +function channel(bindings: FrameForwardingBindings, readbackTimeoutMs = 10_000, budget = bindings.createBudget(16384)) { + const queued: Event[] = [] + const waiters: ((event: Event) => void)[] = [] + const receiver = bindings.createReceiver({ + maxFrames: 1, maxBytes: 16384, budget, displayAdapter: null, readbackTimeoutMs, + }, (event) => { const waiter = waiters.shift(); if (waiter === undefined) queued.push(event); else waiter(event) }) + const next = async (type: T): Promise> => { + for (;;) { + const event = queued.shift() ?? await new Promise((resolve) => { waiters.push(resolve) }) + if (event.type === 'failed' && type !== 'failed') throw new Error(event.text) + if (event.type === type) return event as Extract + } + } + return { receiver, next, queued } +} +const connection = (value: number) => value as FrameConnectionId + +// macOS needs only the Xcode command-line tools. Run `pnpm --filter @deepseek-ai/dsh-desktop run build:native` first. +describe.skipIf(process.platform !== 'darwin')('built frame-forwarding receiver', () => { + let temporary = '' + let producer = '' + let newerProducer = '' + let olderProducer = '' + let legacyProducer = '' + let duplicatingProducer = '' + let bindings: FrameForwardingBindings + let census = (): PortCensus => { throw new Error('the Mach port census addon is not built') } + const children: ChildProcess[] = [] + const frameworks = ['-framework', 'IOSurface', '-framework', 'CoreFoundation', '-lbsm'] + const arch = ['-arch', process.arch === 'x64' ? 'x86_64' : 'arm64', '-std=c++17'] + /** Build the producer with changed protocol declarations, each `[file, from, to]`, in its own source directory. */ + async function variant(name: string, ...changes: [file: string, from: string, to: string][]): Promise { + const root = join(temporary, name) + await mkdir(root) + for (const file of ['transport.h', 'transport.cc', 'fixture-client.cc']) { + const directory = file === 'fixture-client.cc' ? fixtures : native + let source = await readFile(join(directory, file), 'utf8') + for (const [target, from, to] of changes) { + if (target !== file) continue + expect(source).toContain(from) + source = source.replaceAll(from, to) + } + await writeFile(join(root, file), source) + } + const output = join(root, 'producer') + const build = spawnSync('clang++', [...arch, `-I${root}`, `-I${fixtures}`, `-I${native}`, fixture, + join(root, 'fixture-client.cc'), join(root, 'transport.cc'), ...frameworks, '-o', output], { encoding: 'utf8', timeout: 60_000 }) + expect(build.error).toBeUndefined() + expect(build.signal).toBeNull() + expect(build.status, build.stdout + build.stderr).toBe(0) + return output + } + function start(path: string, receiver: FrameForwardingReceiver) { + const child = spawn(path, [receiver.tx], { stdio: ['ignore', 'ignore', 'pipe'] }) + children.push(child) + let stderr = '' + child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString() }) + return { child, exited: once(child, 'exit'), stderr: () => stderr } + } + /** True while `candidate` is still waiting for ready after `timeout`; false once it was refused and exited. */ + async function waits(candidate: ReturnType, timeout = 300): Promise { + let timer: ReturnType | undefined + try { + return await Promise.race([candidate.exited.then(() => false), + new Promise((resolve) => { timer = setTimeout(() => { resolve(true) }, timeout) })]) + } finally { if (timer !== undefined) clearTimeout(timer) } + } + beforeAll(async () => { + temporary = await mkdtemp(join(tmpdir(), 'dsh-office-frame-forwarding-')) + producer = await variant('current') + expect(existsSync(addon), 'run build:native before native e2e').toBe(true) + newerProducer = await variant('protocol-v3', ['transport.h', + '#define DSH_FRAME_FORWARDING_PROTOCOL_VERSION 2', '#define DSH_FRAME_FORWARDING_PROTOCOL_VERSION 3']) + // A protocol 1 producer, such as Kit 0.2.3's, names version 1 in a hello the size of the whole fixed packet. + olderProducer = await variant('protocol-v1', ['transport.h', + '#define DSH_FRAME_FORWARDING_PROTOCOL_VERSION 2', '#define DSH_FRAME_FORWARDING_PROTOCOL_VERSION 1'], + ['transport.cc', 'offsetof(MachMessage, text) + aligned_text', 'offsetof(MachMessage, trailer)']) + // A producer of an earlier build declares no transferable channel in its hello. + legacyProducer = await variant('pid-bound', ['fixture-client.cc', 'hello_transferable | hello_producer_local_handles;', '0;']) + // A 0.2.2 producer declares transferable channels but sends Windows handles it duplicated into the receiver. + duplicatingProducer = await variant('duplicating', ['fixture-client.cc', 'hello_transferable | hello_producer_local_handles;', 'hello_transferable;']) + // The census addon counts this process's dead names, which no API of the receiver exposes. + const censusHeaders = dirname(createRequire(import.meta.url).resolve('node-api-headers/package.json')) + const censusOutput = join(temporary, 'mach-port-census.node') + const censusBuild = spawnSync('clang++', [...arch, `-I${join(censusHeaders, 'include')}`, '-DNAPI_VERSION=8', + '-shared', '-undefined', 'dynamic_lookup', fileURLToPath(new URL('../../../../apps/desktop/tests/frame-forwarding/fixtures/mach-port-census.cc', import.meta.url)), + '-o', censusOutput], { encoding: 'utf8', timeout: 60_000 }) + expect(censusBuild.error).toBeUndefined() + expect(censusBuild.signal).toBeNull() + expect(censusBuild.status, censusBuild.stdout + censusBuild.stderr).toBe(0) + const loadedCensus = createRequire(import.meta.url)(censusOutput) as { count: () => PortCensus } + census = () => loadedCensus.count() + bindings = loadFrameForwardingBindings(addon) + }, 180_000) + afterAll(async () => { + await Promise.all(children.map(async (child) => { + if (child.exitCode !== null || child.signalCode !== null) return + const exited = once(child, 'exit') + child.kill() + await exited + })) + if (temporary) await rm(temporary, { recursive: true, force: true }) + }) + + it('delivers a frame from the test producer, returns its credit, and drains after the producer exits', async () => { + const { receiver, next } = channel(bindings) + const process = start(producer, receiver) + try { + expect(await next('connected')).toEqual({ type: 'connected', connectionId: 1, pid: process.child.pid }) + const frame = await next('frame') + const { connectionId, width, height, transport } = frame + expect({ connectionId, width, height, transport, handle: frame.handle.length }) + .toEqual({ connectionId: 1, width: 64, height: 64, transport: 'shared-texture', handle: 8 }) + receiver.send(connection(1), 'ack') + expect(JSON.parse((await next('message')).text)).toEqual({ applied: 1 }) + expect(receiver.release(frame.deliveryId)).toBe(true) + expect(receiver.release(frame.deliveryId)).toBe(false) + receiver.send(connection(1), 'exit') + await process.exited + expect(await next('disconnected')).toEqual({ type: 'disconnected', connectionId: 1 }) + expect(await next('drained')).toEqual({ type: 'drained', connectionId: 1 }) + expect(() => { receiver.send(connection(1), 'ack') }).toThrow('not active') + } finally { + await receiver.close() + } + }, 30_000) + + it('lets a successor process connect with the same credential only after the crashed producer\'s frame is released', async () => { + const { receiver, next, queued } = channel(bindings) + try { + const first = start(producer, receiver) + await next('connected') + const held = await next('frame') + first.child.kill('SIGKILL') + await first.exited + expect((await next('disconnected')).text).toMatch(/connection lost/i) + const busy = start(producer, receiver) + const successor = start(producer, receiver) + // One candidate waits for the drain; the other is refused while the channel drains. + const refused = (await next('rejected')).text + expect(refused).toBe('channel-busy') + expect(queued.some(event => event.type === 'connected')).toBe(false) + expect(receiver.release(held.deliveryId)).toBe(true) + await next('drained') + const takeover = await next('connected') + expect(takeover.connectionId).toBe(2) + expect([busy.child.pid, successor.child.pid]).toContain(takeover.pid) + const frame = await next('frame') + expect(frame).toMatchObject({ connectionId: 2, frameId: held.frameId }) + expect(frame.deliveryId).toBeGreaterThan(held.deliveryId) + expect(receiver.release(held.deliveryId)).toBe(false) + receiver.release(frame.deliveryId) + receiver.send(connection(2), 'exit') + } finally { + await receiver.close() + } + }, 30_000) + + it.each([['crashed', 'crash'], ['graceful', 'goodbye']] as const)( + 'leaves no dead name behind across repeated %s reconnects', + async (_label, mode) => { + const { receiver, next } = channel(bindings) + try { + const before = census() + const cycles = 20 + for (let cycle = 0; cycle < cycles; ++cycle) { + const process = start(producer, receiver) + const connected = await next('connected') + const frame = await next('frame') + if (mode === 'crash') { + process.child.kill('SIGKILL') + await process.exited + expect((await next('disconnected')).text).toMatch(/connection lost/i) + expect(receiver.release(frame.deliveryId)).toBe(true) + } else { + expect(receiver.release(frame.deliveryId)).toBe(true) + receiver.send(connection(connected.connectionId), 'exit') + await process.exited + expect(await next('disconnected')).toEqual({ type: 'disconnected', connectionId: connected.connectionId }) + } + await next('drained') + } + const after = census() + // Connection liveness watches `MACH_NOTIFY_NO_SENDERS` on the receiver's own port rather than + // `MACH_NOTIFY_DEAD_NAME` on the peer's port, so releasing the channel drops the peer port's single reference + // with no queued dead-name notification references left behind. + expect(after.deadNames - before.deadNames).toBe(0) + expect(after.deadNameRefs - before.deadNameRefs).toBe(0) + } finally { + await receiver.close() + } + }, 120_000) + + it('drops a waiting successor that dies before ready, and admits the next candidate in its place', async () => { + const { receiver, next } = channel(bindings) + try { + const crashed = start(producer, receiver) + await next('connected') + const held = await next('frame') + crashed.child.kill('SIGKILL') + await crashed.exited + expect((await next('disconnected')).text).toMatch(/connection lost/i) + // While the crashed connection drains, one candidate waits for it and the other is refused as busy. + const first = start(producer, receiver) + const second = start(producer, receiver) + expect((await next('rejected')).text).toBe('channel-busy') + const refused = await Promise.race([first.exited.then(() => first), second.exited.then(() => second)]) + const waiting = refused === first ? second : first + expect(refused.child.exitCode).toBe(3) + // A candidate still waiting for ready arms no notice, so the listener reads its reply port's type on every + // accept timeout (100 ms). Until the dead candidate is dropped, a new candidate is refused as busy. + waiting.child.kill('SIGKILL') + await waiting.exited + let successor: ReturnType | undefined + const deadline = Date.now() + 10_000 + while (successor === undefined && Date.now() < deadline) { + const candidate = start(producer, receiver) + if (await waits(candidate)) successor = candidate + else expect(candidate.stderr()).toContain('channel-busy') + } + if (successor === undefined) throw new Error('no candidate took the dead successor\'s place') + expect(receiver.release(held.deliveryId)).toBe(true) + await next('drained') + const takeover = await next('connected') + expect(takeover.pid).toBe(successor.child.pid) + const frame = await next('frame') + expect(receiver.release(frame.deliveryId)).toBe(true) + receiver.send(connection(takeover.connectionId), 'exit') + } finally { + await receiver.close() + } + }, 60_000) + + it('refuses producers of other builds: other protocol versions, a producer without transferable channels, and one that sends receiver handles', async () => { + const { receiver, next } = channel(bindings) + try { + const newer = start(newerProducer, receiver) + expect((await next('rejected')).text).toBe('protocol-mismatch: producer version 3, receiver version 2') + // The receiver names both versions; the newer producer cannot read the protocol 2 refusal itself. + expect(await newer.exited).toEqual([3, null]) + const older = start(olderProducer, receiver) + expect((await next('rejected')).text).toBe('protocol-mismatch: producer version 1, receiver version 2') + expect(await older.exited).toEqual([3, null]) + const legacy = start(legacyProducer, receiver) + expect((await next('rejected')).text).toBe('transferable-tx-required') + expect(await legacy.exited).toEqual([3, null]) + expect(legacy.stderr()).toContain('requires a transferable TX producer') + const duplicating = start(duplicatingProducer, receiver) + expect((await next('rejected')).text).toBe('producer-local-handles-required') + expect(await duplicating.exited).toEqual([3, null]) + expect(duplicating.stderr()).toContain('names only its own handles') + } finally { + await receiver.close() + } + }, 30_000) + + it('returns a trimmed producer\'s idle allocation to the shared budget, which another channel then receives', async () => { + const budget = bindings.createBudget(16384) + const hidden = channel(bindings, 10_000, budget), visible = channel(bindings, 10_000, budget) + try { + start(producer, hidden.receiver) + await hidden.next('connected') + const frame = await hidden.next('frame') + expect(hidden.receiver.release(frame.deliveryId)).toBe(true) + start(producer, visible.receiver) + await visible.next('connected') + // The idle allocation of the first channel holds the whole budget, so the second producer gets no surface. + visible.receiver.send(connection(1), 'ack') + await visible.next('message') + expect(visible.queued.some(event => event.type === 'frame')).toBe(false) + hidden.receiver.send(connection(1), 'trim') + expect(JSON.parse((await hidden.next('message')).text)).toEqual({ trimmed: 1 }) + const delivered = await visible.next('frame') + expect(visible.receiver.release(delivered.deliveryId)).toBe(true) + // The trimmed producer stays connected and allocates again for its next frame. + expect(hidden.queued.some(event => event.type === 'disconnected')).toBe(false) + visible.receiver.send(connection(1), 'exit') + hidden.receiver.send(connection(1), 'exit') + } finally { + await Promise.all([hidden.receiver.close(), visible.receiver.close()]) + } + }, 30_000) + + it('withdraws the credential on close, so a producer started afterwards cannot connect', async () => { + const { receiver } = channel(bindings, 1000) + await expect(receiver.close()).resolves.toBeUndefined() + await expect(receiver.close()).resolves.toBeUndefined() + const late = start(producer, receiver) + expect(await late.exited).toEqual([3, null]) + }, 30_000) + + it('lets a process exit while a receiver is still open', () => { + const script = `import { createRequire } from 'node:module'; const b = createRequire(import.meta.url)(${JSON.stringify(addon)}); + b.create(1, 16384, () => {}, b.createBudget(16384), '', 1000); setTimeout(() => process.exit(0), 50)` + const result = spawnSync(process.execPath, ['--input-type=module', '-e', script], { encoding: 'utf8', timeout: 20_000 }) + expect(result.status, result.stderr).toBe(0) + }) +}) diff --git a/packages/experimental/frame-forwarding/tests/rx.client.spec.ts b/packages/experimental/frame-forwarding/tests/rx.client.spec.ts new file mode 100644 index 0000000000..cfa7dc92d5 --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/rx.client.spec.ts @@ -0,0 +1,605 @@ +/** + * Newest-first streams across producer switches, readiness, frame release, and the + * channel's fullscreen requests and state, without a GPU. + */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { brandString } from '@deepseek-ai/dsh-brand' +import type { FrameChannelState, FrameConnectionId, FrameForwardingViewport, FrameRxId, FrameViewportResult } from '../src/types.ts' +import { FrameRx } from '../src/client/rx.ts' +import { FrameDiscardedError, FrameFailureError } from '../src/client/errors.ts' +import type { FrameForwardingBridge, FrameForwardingFrameLease, FrameRxEvent } from '../src/client/api.ts' + +const rx = brandString('rx') +const channels = new Set() +const viewport = (version: number) => ({ version, width: 2, height: 2, deviceScaleFactor: 1, visible: true }) +const connected = (connectionId: number, viewportVersion?: number): FrameChannelState => ({ + state: 'connected', connectionId: connectionId as FrameConnectionId, ...viewportVersion === undefined ? {} : { viewportVersion }, +}) +/** @param initial - State the bridge already knows when the channel connects; null for none. */ +function fixture(initial: FrameChannelState | null = connected(1)) { + let arrive: (lease: FrameForwardingFrameLease) => void = () => {} + let report: (event: FrameRxEvent) => void = () => {} + const detach = vi.fn(async () => {}) + const bridge = { + attach(_rx, { onFrame, onEvent }) { + arrive = onFrame + report = onEvent + if (initial !== null) report({ kind: 'state', channel: initial }) + return detach + }, + setViewport: vi.fn(async (_rx: FrameRxId, _viewport: FrameForwardingViewport): Promise => + ({ applied: true, connectionId: 1 as FrameConnectionId })), + apply: vi.fn(), + requestFullscreen: vi.fn(async (_rx: FrameRxId, _element: Element) => {}), + exitFullscreen: vi.fn(async (_rx: FrameRxId) => {}), + fail: vi.fn(), + dispose: vi.fn(), + } satisfies FrameForwardingBridge + const channel = new FrameRx(rx, bridge) + channels.add(channel) + const lease = (requestId: string, options: { generation?: number; connectionId?: number } = {}) => ({ + metadata: { + rx, connectionId: (options.connectionId ?? 1) as FrameConnectionId, requestId, generation: options.generation ?? 0, + revision: 1, frameId: 1, width: 2, height: 2, + }, + frame: {} as VideoFrame, + release: vi.fn(), + }) + return { + channel, + bridge, detach, + lease, + state: (state: FrameChannelState) => { report({ kind: 'state', channel: state }) }, + event: (event: FrameRxEvent) => { report(event) }, + receive: (frame: FrameForwardingFrameLease) => { arrive(frame) }, + } +} +const reason = (error: unknown): unknown => error instanceof FrameDiscardedError ? error.reason : error +afterEach(async () => { + await Promise.all([...channels].map(channel => channel.close())) + channels.clear() +}) + +describe('producer connections', () => { + it('keeps frames of a later connection until its state arrives, and drops them on a viewport change', async () => { + const f = fixture() + const third = f.lease('stream', { connectionId: 3 }) + f.receive(third) + f.state(connected(2)) + expect(third.release).not.toHaveBeenCalled() + await f.channel.setViewport(viewport(1)) + expect(third.release).toHaveBeenCalledOnce() + }) + it('releases early frames of a connection whose first reported state is draining, and keeps a later connection\'s', () => { + const f = fixture() + const ended = f.lease('tile', { connectionId: 2 }) + const later = f.lease('tile', { connectionId: 3 }) + f.receive(ended) + f.receive(later) + f.state({ state: 'draining', connectionId: 2 as FrameConnectionId }) + expect(ended.release).toHaveBeenCalledOnce() + expect(later.release).not.toHaveBeenCalled() + }) + it('ignores errors of an earlier connection and reports the current one\'s other errors to the stream', async () => { + const f = fixture() + const failure = vi.fn() + f.state(connected(2)) + f.channel.consume(vi.fn(), failure) + f.event({ kind: 'error', connectionId: 1 as FrameConnectionId, source: 'producer', error: 'old stream failed' }) + f.event({ kind: 'error', connectionId: 2 as FrameConnectionId, source: 'producer', error: 'PPT stream rendering failed' }) + f.event({ kind: 'error', connectionId: 2 as FrameConnectionId, source: 'presentation', requestId: 'stream', error: 'frame transfer failed' }) + expect(failure.mock.calls).toEqual([ + [new FrameFailureError('producer', 'PPT stream rendering failed')], [new FrameFailureError('presentation', 'frame transfer failed')], + ]) + expect(failure.mock.calls.map(([error]) => (error as FrameFailureError).source)).toEqual(['producer', 'presentation']) + }) + it('resolves readiness once a producer acknowledged the latest viewport', async () => { + const f = fixture(null) + let ready: FrameConnectionId | undefined + const waiting = f.channel.ready().then((connectionId) => { ready = connectionId }) + f.state(connected(1)) + await waiting + expect(ready).toBe(1) + f.bridge.setViewport.mockResolvedValueOnce({ applied: false, reason: 'no-producer' }) + await f.channel.setViewport(viewport(1)) + const afterViewport = f.channel.ready() + f.state(connected(1, 0)) + f.state({ state: 'draining', connectionId: 1 as FrameConnectionId }) + f.state(connected(2)) + expect(await Promise.race([afterViewport, Promise.resolve('pending')])).toBe('pending') + f.state(connected(2, 1)) + expect(await afterViewport).toBe(2) + expect(await f.channel.ready()).toBe(2) + }) + it('cancels and fails readiness waits', async () => { + const f = fixture(null) + const aborted = new AbortController(); aborted.abort() + expect(await f.channel.ready(aborted.signal).catch(reason)).toBe('cancelled') + const controller = new AbortController() + const cancelled = f.channel.ready(controller.signal).catch(reason) + controller.abort() + expect(await cancelled).toBe('cancelled') + const lost = f.channel.ready().catch(reason) + f.state({ state: 'closed', cause: 'lost', reason: 'Desktop invalidated a presented frame' }) + expect(await lost).toBe('lost') + const g = fixture(null) + const closing = g.channel.ready().catch(reason) + await g.channel.close() + expect(await closing).toBe('closed') + }) + it('rejects a viewport whose connection ended before acknowledging it, and keeps one without a producer', async () => { + const f = fixture() + f.bridge.setViewport.mockResolvedValueOnce({ applied: false, reason: 'producer-changed' }) + expect(await f.channel.setViewport(viewport(1)).catch(reason)).toBe('producer-changed') + // A producer change does not hold back the next viewport. + f.bridge.setViewport.mockResolvedValueOnce({ applied: false, reason: 'no-producer' }) + await f.channel.setViewport(viewport(2)) + expect(f.bridge.setViewport.mock.calls.map(([, value]) => value.version)).toEqual([1, 2]) + }) +}) + +describe('channel lifetime', () => { + it('releases later frames on close, and completes after lent frames are released', async () => { + const f = fixture() + const using = Promise.withResolvers() + f.channel.consume(() => using.promise, vi.fn()) + const lease = f.lease('lent') + f.receive(lease) + let closed = false + const closing = f.channel.close().then(() => { closed = true }) + const late = f.lease('late') + f.receive(late) + expect(late.release).toHaveBeenCalledOnce() + await Promise.resolve() + expect(closed).toBe(false) + expect(lease.release).not.toHaveBeenCalled() + using.resolve(undefined) + await closing + expect(lease.release).toHaveBeenCalledOnce() + await f.channel.close() + expect(f.detach).toHaveBeenCalledOnce() + expect(() => f.channel.consume(vi.fn(), vi.fn())).toThrow('Native channel closed.') + }) + it('ends routing when the Host closes the channel, reporting the closure to readiness and the stream', async () => { + const f = fixture() + const failure = vi.fn() + f.channel.consume(vi.fn(), failure) + f.state({ state: 'closed', cause: 'closed', reason: 'Native channel closed' }) + expect(reason(failure.mock.calls[0]![0])).toBe('closed') + expect(await f.channel.closed).toBe('closed') + f.state(connected(2)) + expect(f.channel.connectionId).toBeUndefined() + expect(() => f.channel.ready()).toThrow('Native channel closed.') + const late = f.lease('late') + f.receive(late) + expect(late.release).toHaveBeenCalledOnce() + }) + it('settles closed once, with the cause that ended routing', async () => { + const lost = fixture() + lost.state({ state: 'closed', cause: 'lost', reason: 'Desktop invalidated a presented frame' }) + expect(() => lost.channel.ready()).toThrow('Native channel lost.') + await lost.channel.close() + expect(await lost.channel.closed).toBe('lost') + // A receiver failure is a transport failure, not a discarded frame. + const failed = fixture() + failed.state({ state: 'closed', cause: 'failed', reason: 'Native channel failed: listener failed' }) + expect(() => failed.channel.ready()).toThrow('Native channel failed: listener failed') + expect(await failed.channel.closed).toBe('failed') + const consumer = fixture() + consumer.event({ kind: 'failure', error: 'consumer exploded' }) + expect(await consumer.channel.closed).toBe('failed') + const owner = fixture() + await owner.channel.close() + expect(await owner.channel.closed).toBe('closed') + }) + it('rejects later operations after a renderer-side failure', async () => { + const f = fixture() + f.event({ kind: 'failure', error: 'consumer exploded' }) + expect(() => f.channel.consume(vi.fn(), vi.fn())).toThrow('consumer exploded') + const late = f.lease('late') + f.receive(late) + expect(late.release).toHaveBeenCalledOnce() + }) + it('requires increasing viewport versions and reports a viewport the Host refuses', async () => { + const f = fixture() + expect(() => f.channel.setViewport(viewport(0))).toThrow('must increase') + f.bridge.setViewport.mockResolvedValueOnce({ applied: false, reason: 'stale-viewport', currentVersion: 3 }) + await expect(f.channel.setViewport(viewport(1))).rejects.toThrow('must increase') + expect(() => f.channel.setViewport(viewport(1))).toThrow('must increase') + }) + it('sends the next viewport after one the producer did not acknowledge, and becomes ready with it', async () => { + const f = fixture() + const unacknowledged = Promise.withResolvers() + f.bridge.setViewport.mockReturnValueOnce(unacknowledged.promise) + const timedOut = f.channel.setViewport(viewport(1)) + const resized = f.channel.setViewport(viewport(2)) + unacknowledged.reject(new Error('Native producer acknowledgement timed out')) + await expect(timedOut).rejects.toThrow('timed out') + await resized + expect(f.bridge.setViewport.mock.calls.map(([, sent]) => sent.version)).toEqual([1, 2]) + const ready = f.channel.ready() + f.state(connected(1, 2)) + expect(await ready).toBe(1) + }) + it('sends no queued viewport after close, so a reconnected consumer keeps the viewport it set', async () => { + const f = fixture() + const acknowledged = Promise.withResolvers() + f.bridge.setViewport.mockReturnValueOnce(acknowledged.promise) + const sent = f.channel.setViewport(viewport(1)) + const hidden = f.channel.setViewport({ ...viewport(2), visible: false }).catch((error: unknown) => error) + await vi.waitFor(() => { expect(f.bridge.setViewport).toHaveBeenCalledOnce() }) + await f.channel.close() + acknowledged.resolve({ applied: true, connectionId: 1 as FrameConnectionId }) + await sent + expect(reason(await hidden)).toBe('closed') + expect(f.bridge.setViewport.mock.calls.map(([, queued]) => queued.version)).toEqual([1]) + }) +}) + +describe('continuous frames', () => { + it('presents the newest frame next and holds at most one waiting frame behind a slow consumer', async () => { + const f = fixture() + const painting = Promise.withResolvers() + const presented: string[] = [] + f.channel.consume(async (frame) => { + presented.push(frame.metadata.requestId) + if (presented.length === 1) await painting.promise + }, vi.fn()) + const first = f.lease('first') + f.receive(first) + const arrivals = Array.from({ length: 20 }, (_, index) => f.lease(String(index))) + for (const lease of arrivals) f.receive(lease) + const held = [first, ...arrivals].filter(lease => lease.release.mock.calls.length === 0) + expect(held).toEqual([first, arrivals[19]]) + painting.resolve(undefined) + await vi.waitFor(() => { expect(arrivals[19]!.release).toHaveBeenCalledOnce() }) + expect(presented).toEqual(['first', '19']) + expect(first.release).toHaveBeenCalledOnce() + }) + it('keeps presenting across a producer switch once the successor\'s state arrives', async () => { + const f = fixture() + const presented: number[] = [] + f.channel.consume((frame) => { presented.push(frame.metadata.connectionId) }, vi.fn()) + f.receive(f.lease('stream')) + f.state({ state: 'draining', connectionId: 1 as FrameConnectionId }) + const stale = f.lease('stream') + f.receive(stale) + const early = f.lease('stream', { connectionId: 2 }) + f.receive(early) + f.state(connected(2)) + await vi.waitFor(() => { expect(early.release).toHaveBeenCalledOnce() }) + expect(stale.release).toHaveBeenCalledOnce() + expect(presented).toEqual([1, 2]) + }) + it('releases the waiting frame on unsubscribe and the presented one only after its callback settles', async () => { + const f = fixture() + const painting = Promise.withResolvers() + const remove = f.channel.consume(() => painting.promise, vi.fn()) + const active = f.lease('active'), waiting = f.lease('waiting') + f.receive(active) + f.receive(waiting) + remove(); remove() + expect(waiting.release).toHaveBeenCalledOnce() + expect(active.release).not.toHaveBeenCalled() + const replacement = vi.fn() + const detach = f.channel.consume(replacement, vi.fn()) + const next = f.lease('replacement') + f.receive(next) + expect(replacement).not.toHaveBeenCalled() + painting.resolve(undefined) + await vi.waitFor(() => { expect(active.release).toHaveBeenCalledOnce() }) + expect(replacement).toHaveBeenCalledExactlyOnceWith({ image: next.frame, metadata: next.metadata }) + expect(next.release).toHaveBeenCalledOnce() + detach() + const after = f.lease('after') + f.receive(after) + expect(after.release).toHaveBeenCalledOnce() + }) + it('reports consumer errors, contains failure-listener exceptions, and keeps presenting later frames', async () => { + const f = fixture() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const failure = vi.fn(() => { throw new Error('listener failed') }) + const paint = vi.fn<() => void>().mockImplementationOnce(() => { throw 'paint failed' }) + .mockImplementationOnce(() => { throw new Error('canvas lost') }) + f.channel.consume(paint, failure) + const first = f.lease('first') + f.receive(first) + await vi.waitFor(() => { expect(first.release).toHaveBeenCalledOnce() }) + expect(failure).toHaveBeenCalledWith(new Error('paint failed')) + const second = f.lease('second') + f.receive(second) + await vi.waitFor(() => { expect(second.release).toHaveBeenCalledOnce() }) + expect(failure).toHaveBeenLastCalledWith(new Error('canvas lost')) + f.event({ kind: 'failure', error: 'consumer exploded' }) + expect(failure).toHaveBeenLastCalledWith(new Error('consumer exploded')) + expect(log).toHaveBeenCalledTimes(3) + log.mockRestore() + }) + it('allows one stream consumer at a time', () => { + const f = fixture() + const remove = f.channel.consume(vi.fn(), vi.fn()) + expect(() => f.channel.consume(vi.fn(), vi.fn())).toThrow('already has a frame consumer') + remove() + }) +}) + +describe('channel event subscriptions', () => { + it('replays known state, and fullscreen without replaying historical errors', () => { + const f = fixture() + const log = vi.spyOn(console, 'debug').mockImplementation(() => {}) + f.event({ kind: 'fullscreen', active: true, holder: true }) + f.event({ kind: 'error', connectionId: 1 as FrameConnectionId, source: 'producer', error: 'earlier' }) + const seen: FrameRxEvent[] = [] + f.channel.onEvent(event => seen.push(event)) + expect(seen).toEqual([ + { kind: 'state', channel: connected(1) }, { kind: 'fullscreen', active: true, holder: true }, + { kind: 'content', submittedGeneration: undefined }, + ]) + log.mockRestore() + }) + it('does not synthesize channel state before it is known', () => { + const f = fixture(null) + const seen: FrameRxEvent[] = [] + f.channel.onEvent(event => seen.push(event)) + expect(seen).toEqual([{ kind: 'fullscreen', active: false, holder: false }, { kind: 'content', submittedGeneration: undefined }]) + }) + it('isolates subscriptions including repeated listener identity, exceptions and idempotent disposal', () => { + const f = fixture() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const throwing = f.channel.onEvent(() => { throw new Error('event listener failed') }) + const listener = vi.fn() + const first = f.channel.onEvent(listener) + const second = f.channel.onEvent(listener) + listener.mockClear() + first(); first() + f.state({ state: 'idle' }) + expect(listener).toHaveBeenCalledExactlyOnceWith({ kind: 'state', channel: { state: 'idle' } }) + expect(log).toHaveBeenCalledWith('Native channel event listener failed', expect.objectContaining({ message: 'event listener failed' })) + second(); second(); throwing() + f.state(connected(2)) + expect(listener).toHaveBeenCalledOnce() + log.mockRestore() + }) + it('delivers all event kinds in arrival order to every observer, including reentrant events', () => { + const f = fixture() + const first: FrameRxEvent[] = [], second: FrameRxEvent[] = [] + const staleError = { kind: 'error', connectionId: 9 as FrameConnectionId, source: 'producer', error: 'old connection' } as const + f.channel.onEvent((event) => { + first.push(event) + if (event.kind === 'fullscreen' && event.active) f.event(staleError) + }) + f.channel.onEvent(event => second.push(event)) + first.length = 0; second.length = 0 + const fullscreen = { kind: 'fullscreen', active: true, holder: false } as const + f.event(fullscreen) + const failure = { kind: 'failure', error: 'Client disposed' } as const + f.event(failure) + expect(first).toEqual([fullscreen, staleError, failure]) + expect(second).toEqual(first) + }) + it('replays a reentrant subscription after previously queued state changes', () => { + const f = fixture() + const late: FrameRxEvent[] = [] + f.channel.onEvent((event) => { + if (event.kind !== 'fullscreen' || !event.active) return + f.state(connected(2)) + f.channel.onEvent(value => late.push(value)) + }) + f.event({ kind: 'fullscreen', active: true, holder: true }) + expect(late).toEqual([{ kind: 'state', channel: connected(2) }, { kind: 'fullscreen', active: true, holder: true }, + { kind: 'content', submittedGeneration: undefined }]) + }) + it.each(['closed', 'lost', 'failed', 'disposed'] as const)('ends subscriptions after %s and ignores late events', (cause) => { + const f = fixture() + const listener = vi.fn() + const fullscreen = vi.fn() + const remove = f.channel.onEvent(listener) + f.channel.onFullscreen(fullscreen) + listener.mockClear() + const terminal: FrameRxEvent = cause === 'disposed' ? { kind: 'failure', error: 'Client disposed' } + : { kind: 'state', channel: { state: 'closed', cause, reason: 'ended' } } + f.event(terminal) + expect(listener).toHaveBeenCalledExactlyOnceWith(terminal) + f.event({ kind: 'fullscreen', active: true, holder: false }) + f.state(connected(2)) + const late = vi.fn() + f.channel.onEvent(late)() + f.channel.onFullscreen(late)() + remove(); remove() + expect(listener).toHaveBeenCalledOnce() + expect(fullscreen).not.toHaveBeenCalled() + expect(late).not.toHaveBeenCalled() + }) + it('reports local closure once, including reentrant close from a terminal listener', async () => { + const f = fixture() + const first: FrameRxEvent[] = [], second: FrameRxEvent[] = [] + let reentrant: Promise | undefined + f.channel.onEvent((event) => { + first.push(event) + if (event.kind === 'state' && event.channel.state === 'closed') reentrant = f.channel.close() + }) + f.channel.onEvent(event => second.push(event)) + first.length = 0; second.length = 0 + const closed = f.channel.close() + await closed + expect(reentrant).toBe(closed) + expect(f.detach).toHaveBeenCalledOnce() + expect(first).toEqual([{ kind: 'state', channel: { state: 'closed', cause: 'closed', reason: 'Native channel closed.' } }]) + expect(second).toEqual(first) + f.event({ kind: 'fullscreen', active: true, holder: false }) + expect(second).toEqual(first) + }) + it('stops initial replay when its listener closes the channel', async () => { + const f = fixture() + const events: FrameRxEvent[] = [] + let closing: Promise | undefined + f.channel.onEvent((event) => { + events.push(event) + if (event.kind === 'state' && event.channel.state === 'connected') closing = f.channel.close() + }) + await closing + expect(events).toEqual([ + { kind: 'state', channel: connected(1) }, + { kind: 'state', channel: { state: 'closed', cause: 'closed', reason: 'Native channel closed.' } }, + ]) + expect(f.detach).toHaveBeenCalledOnce() + }) + it('shares fullscreen changes with onFullscreen without adding replay to that method', () => { + const f = fixture() + const every: FrameRxEvent[] = [] + const fullscreen: { active: boolean; holder: boolean }[] = [] + f.channel.onEvent(event => every.push(event)) + const remove = f.channel.onFullscreen(state => fullscreen.push(state)) + expect(fullscreen).toEqual([]) + every.length = 0 + f.event({ kind: 'fullscreen', active: true, holder: false }) + f.event({ kind: 'fullscreen', active: false, holder: false }) + expect(every).toEqual(fullscreen.map(state => ({ kind: 'fullscreen', ...state }))) + expect(f.channel.fullscreen).toEqual(fullscreen.at(-1)) + remove(); remove() + f.event({ kind: 'fullscreen', active: true, holder: true }) + expect(fullscreen).toHaveLength(2) + }) +}) + +describe('fullscreen', () => { + it('requests and leaves fullscreen for its channel, and refuses requests once closed or failed', async () => { + const f = fixture() + const view = {} as Element + await f.channel.requestFullscreen(view) + expect(f.bridge.requestFullscreen).toHaveBeenCalledWith(rx, view) + await f.channel.exitFullscreen() + expect(f.bridge.exitFullscreen).toHaveBeenCalledWith(rx) + f.event({ kind: 'failure', error: 'paint failed' }) + await expect(f.channel.requestFullscreen(view)).rejects.toThrow('paint failed') + const closed = fixture() + await closed.channel.close() + expect(reason(await closed.channel.requestFullscreen(view).catch((error: unknown) => error))).toBe('closed') + expect(f.bridge.requestFullscreen).toHaveBeenCalledOnce() + }) + + it('keeps the latest fullscreen state, reports changes to its observers, and contains a failing observer', async () => { + const f = fixture() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + expect(f.channel.fullscreen).toEqual({ active: false, holder: false }) + const seen: unknown[] = [] + f.channel.onFullscreen(() => { throw new Error('observer failed') }) + const remove = f.channel.onFullscreen(state => seen.push(state)) + f.event({ kind: 'fullscreen', active: true, holder: false }) + expect(f.channel.fullscreen).toEqual({ active: true, holder: false }) + remove() + f.event({ kind: 'fullscreen', active: false, holder: false }) + expect(seen).toEqual([{ active: true, holder: false }]) + expect(log).toHaveBeenCalledWith('Native fullscreen listener failed', expect.objectContaining({ message: 'observer failed' })) + const after = vi.fn() + f.channel.onFullscreen(after) + await f.channel.close() + f.event({ kind: 'fullscreen', active: true, holder: false }) + expect(after).not.toHaveBeenCalled() + log.mockRestore() + }) +}) + +it('exposes and replays the latest viewport while ordering reentrant viewport requests', async () => { + const f = fixture() + expect(f.channel.viewport).toBeUndefined() + let nested: Promise | undefined + const events: FrameRxEvent[] = [] + f.channel.onEvent((event) => { + events.push(event) + if (event.kind === 'viewport' && event.viewport.version === 1) { + expect(f.bridge.setViewport).not.toHaveBeenCalled() + expect(f.channel.viewport).toEqual(viewport(1)) + nested = f.channel.setViewport(viewport(2)) + } + }) + await f.channel.setViewport(viewport(1)); await nested + expect(f.bridge.setViewport.mock.calls.map(call => call[1].version)).toEqual([1, 2]) + expect(f.channel.viewport).toEqual(viewport(2)) + const replay: FrameRxEvent[] = [] + f.channel.onEvent(event => replay.push(event)) + expect(replay.map(event => event.kind)).toEqual(['state', 'viewport', 'fullscreen', 'content']) + expect(replay[1]).toEqual({ kind: 'viewport', viewport: viewport(2) }) + expect(events.filter(event => event.kind === 'viewport').map(event => event.viewport.version)).toEqual([1, 2]) +}) + +it('replays displayed generation and coalesces repeated and reentrant content reports', () => { + const f = fixture() + const seen: FrameRxEvent[] = [] + f.channel.onEvent((event) => { + seen.push(event) + if (event.kind === 'content' && event.submittedGeneration === 2) { + f.event({ kind: 'content', submittedGeneration: 2 }) + } + }) + f.event({ kind: 'content', submittedGeneration: 2 }) + f.event({ kind: 'content', submittedGeneration: 2 }) + expect(seen.filter(event => event.kind === 'content')).toEqual([ + { kind: 'content', submittedGeneration: undefined }, { kind: 'content', submittedGeneration: 2 }, + ]) + const replay: FrameRxEvent[] = [] + f.channel.onEvent(event => replay.push(event)) + expect(replay.at(-1)).toEqual({ kind: 'content', submittedGeneration: 2 }) + f.event({ kind: 'content', submittedGeneration: undefined }) + expect(seen.at(-1)).toEqual({ kind: 'content', submittedGeneration: undefined }) +}) + +it('requires a mount for either content setter', () => { + const f = fixture() + expect(() => { f.channel.setContentView({ x: 0, y: 0, scale: 1 }) }).toThrow('Frame content requires mount.') + expect(() => { f.channel.setContentView(undefined) }).toThrow('Frame content requires mount.') + expect(() => f.channel.setContentWindow({ x: 0, y: 0, width: 1, height: 1 })).toThrow('Frame content requires mount.') +}) + +it('applies bridge viewport announcements and replays them to later subscribers', () => { + const f = fixture() + f.event({ kind: 'viewport', viewport: viewport(7) }) + expect(f.channel.viewport).toEqual(viewport(7)) + const seen: FrameRxEvent[] = [] + f.channel.onEvent(event => seen.push(event)) + expect(seen).toContainEqual({ kind: 'viewport', viewport: viewport(7) }) +}) + +it('skips an event listener removed by an earlier listener in the same delivery', () => { + const f = fixture() + let remove = () => {} + f.channel.onEvent((event) => { if (event.kind === 'fullscreen' && event.active) remove() }) + const later = vi.fn() + remove = f.channel.onEvent(later) + later.mockClear() + f.event({ kind: 'fullscreen', active: true, holder: false }) + expect(later).not.toHaveBeenCalled() +}) + +it('does not apply queued state announcements after reentrant close', async () => { + const f = fixture() + let closing: Promise | undefined + f.channel.onEvent((event) => { + if (event.kind !== 'fullscreen' || !event.active) return + f.state(connected(2)) + closing = f.channel.close() + }) + f.event({ kind: 'fullscreen', active: true, holder: false }) + await closing + expect(f.channel.connectionId).toBeUndefined() + await expect(f.channel.closed).resolves.toBe('closed') +}) + +it('releases a queued stream frame on viewport change while retaining the running frame', async () => { + const f = fixture() + const writing = Promise.withResolvers() + const present = vi.fn(() => writing.promise) + f.channel.consume(present, vi.fn()) + const first = f.lease(''), queued = f.lease('') + try { + f.receive(first); f.receive(queued) + await f.channel.setViewport(viewport(1)) + expect(queued.release).toHaveBeenCalledOnce() + expect(first.release).not.toHaveBeenCalled() + } finally { + writing.resolve(undefined) + await f.channel.close() + } + expect(first.release).toHaveBeenCalledOnce() + expect(present).toHaveBeenCalledOnce() +}) diff --git a/packages/experimental/frame-forwarding/tests/service.host.spec.ts b/packages/experimental/frame-forwarding/tests/service.host.spec.ts new file mode 100644 index 0000000000..21020cb5c6 --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/service.host.spec.ts @@ -0,0 +1,386 @@ +/** The frame-forwarding Host service exposes channels to Host plugins and drives them from the renderer through its Remote. */ +import { receiverAddon } from './desktop-receiver.ts' +import { totalmem } from 'node:os' +import { Context } from '@deepseek-ai/cordis' +import { brandString } from '@deepseek-ai/dsh-brand' +import { remoteMethods } from '@deepseek-ai/dsh-typert-protocol' +import { afterEach, expect, test, vi } from 'vitest' +import { windowBudget } from '../src/config.ts' +import FrameForwarding, { + type FrameConnectionId, type FrameForwardingEvent, type FrameRxId, +} from '../src/index.ts' + +/** The forwarder has its own specs; the service sees only its operations and its listeners. */ +const forwarder = vi.hoisted(() => ({ + constructions: [] as { sharedTexture: unknown; load: () => unknown; limits: { maxBytes(): number } }[], + listeners: undefined as { event(event: unknown): void; warn(message: string): void } | undefined, + snapshot: [] as unknown[], + methods: { + capabilities: vi.fn(async (): Promise<{ supported: boolean; reason?: string }> => ({ supported: true })), + channel: vi.fn(async () => ({ tx: 'tx', rx: 'rx-1' })), + isOpen: vi.fn(() => true), + setViewport: vi.fn(async () => ({ applied: true, connectionId: 1 })), + close: vi.fn(async () => {}), + closeAll: vi.fn(async () => {}), + }, +})) +vi.mock('../src/host/forwarder.ts', () => ({ + FrameForwarder: class { + constructor(sharedTexture: unknown, load: () => unknown, limits: { maxBytes(): number }, listeners: typeof forwarder.listeners) { + forwarder.constructions.push({ sharedTexture, load, limits }) + forwarder.listeners = listeners + } + capabilities = forwarder.methods.capabilities + channel = forwarder.methods.channel + isOpen = forwarder.methods.isOpen + setViewport = forwarder.methods.setViewport + close = forwarder.methods.close + closeAll = forwarder.methods.closeAll + snapshot = () => forwarder.snapshot + }, +})) + +const load = vi.hoisted(() => vi.fn(() => ({ loaded: true }))) +vi.mock('../src/host/native.ts', () => ({ loadFrameForwardingBindings: load })) + +afterEach(() => { + vi.clearAllMocks() + forwarder.constructions.length = 0 + forwarder.listeners = undefined + forwarder.snapshot = [] +}) + +async function fixture(options: { desktop?: boolean; receiver?: boolean; config?: Record } = {}) { + const ctx = new Context() + if (options.receiver !== false) ctx.provide('desktopFrameReceiver', { path: receiverAddon }) + const claim = { capabilities: vi.fn(), nativeSink: vi.fn(), adapterLuid: vi.fn(), release: vi.fn() } + const sharedTexture = { claim: vi.fn(() => claim) } + if (options.desktop !== false) ctx.provide('sharedTexture', sharedTexture as never) + const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + await ctx.plugin(FrameForwarding, FrameForwarding.Config(options.config ?? {})).await() + const service = ctx.get('frameForwarding') as FrameForwarding + return { ctx, service, sharedTexture, claim, warn, dispose: () => ctx.fiber.dispose() } +} +const rx = brandString('rx-1') +/** Resolve the window budget the plugin handed to its `index`-th forwarder construction. */ +const budgetOf = (index: number): number => forwarder.constructions[index]!.limits.maxBytes() +const state = (channel: string, sequence: number, connectionId?: number): FrameForwardingEvent => connectionId === undefined + ? { kind: 'state', rx: brandString(channel), sequence, channel: { state: 'idle' } } + : { kind: 'state', rx: brandString(channel), sequence, channel: { state: 'connected', connectionId: connectionId as FrameConnectionId } } +function subscribe(service: FrameForwarding) { + const controller = new AbortController() + const received: FrameForwardingEvent[] = [] + const done = (async () => { + for await (const event of service.events(controller.signal)) received.push(event) + })() + return { received, done, cancel: () => { controller.abort() } } +} + +test('resolves native layer limits and rejects invalid configuration', () => { + expect(FrameForwarding.Config({})).toMatchObject({ maxFrames: 3 }) + expect(() => FrameForwarding.Config({ maxFrames: 2 })).toThrow() +}) + +test('publishes only the renderer operations as Remote methods', async () => { + const f = await fixture() + try { + expect(f.service.typertRemote).toMatchObject({ serviceKey: 'frameForwarding', namespace: 'frameForwarding' }) + expect(remoteMethods(f.service).map(({ method, mode }) => [method, mode ?? 'unary'])).toEqual([['viewport', 'unary'], ['events', 'stream']]) + } finally { await f.dispose() } +}) + +test('builds one forwarder over the Desktop service with the configured limits and forwards consumer operations', async () => { + const f = await fixture({ config: { maxFrames: 4, maxBytes: 8192, requestTimeoutMs: 500, maxPendingRequests: 9 } }) + try { + forwarder.methods.isOpen.mockReturnValueOnce(false) + expect(f.service.isOpen(rx)).toBe(false) + expect(await f.service.capabilities()).toEqual({ supported: true }) + expect(await f.service.channel()).toEqual({ tx: 'tx', rx: 'rx-1' }) + expect(f.service.isOpen(rx)).toBe(true) + expect(await f.service.viewport(rx, { version: 1, width: 4, height: 2, deviceScaleFactor: 2, visible: true })) + .toEqual({ applied: true, connectionId: 1 }) + await f.service.close(rx) + await f.service.close(brandString('unknown')) + expect(forwarder.constructions).toMatchObject([{ + sharedTexture: f.claim, limits: { maxFrames: 4, requestTimeoutMs: 500, maxPendingRequests: 9 }, + }]) + expect(budgetOf(0)).toBe(8192) + expect(f.warn).not.toHaveBeenCalled() + expect(load).not.toHaveBeenCalled() + expect(forwarder.constructions[0]!.load()).toEqual({ loaded: true }) + expect(load).toHaveBeenCalledExactlyOnceWith(receiverAddon) + expect(forwarder.methods.isOpen).toHaveBeenCalledWith(rx) + expect(forwarder.methods.setViewport).toHaveBeenCalledWith(rx, expect.objectContaining({ version: 1 })) + expect(forwarder.methods.close.mock.calls).toEqual([[rx], ['unknown']]) + forwarder.listeners!.warn('Native producer refused: channel-busy') + expect(f.warn).toHaveBeenCalledWith('Native producer refused: channel-busy') + } finally { await f.dispose() } + expect(forwarder.methods.closeAll).toHaveBeenCalledOnce() + expect(f.claim.release).toHaveBeenCalledOnce() + expect(forwarder.methods.closeAll.mock.invocationCallOrder[0]).toBeLessThan(f.claim.release.mock.invocationCallOrder[0]!) +}) + +test('sizes the window budget at half of physical memory by default and reduces a larger budget to physical memory with a warning', async () => { + const f = await fixture() + try { + expect(budgetOf(0)).toBe(Math.max(256 * 1024 ** 2, Math.floor(totalmem() / 2))) + expect(f.warn).not.toHaveBeenCalled() + } finally { await f.dispose() } + const large = await fixture({ config: { maxBytes: totalmem() + 1 } }) + try { + expect(budgetOf(1)).toBe(totalmem()) + expect(large.warn).toHaveBeenCalledExactlyOnceWith( + `Frame forwarding maxBytes ${totalmem() + 1} exceeds the ${totalmem()} bytes of physical memory; the window budget is ${totalmem()} bytes.`, + ) + } finally { await large.dispose() } + expect(windowBudget('auto', 16 * 1024 ** 3)).toBe(8 * 1024 ** 3) + expect(windowBudget('auto', 300 * 1024 ** 2)).toBe(256 * 1024 ** 2) + expect(windowBudget('auto', 200 * 1024 ** 2)).toBe(200 * 1024 ** 2) + expect(windowBudget(16 * 1024 ** 3, 16 * 1024 ** 3)).toBe(16 * 1024 ** 3) + expect(windowBudget(16 * 1024 ** 3 + 1, 16 * 1024 ** 3)).toBe(16 * 1024 ** 3) +}) + +test('claims Desktop shared textures once the Desktop Host provides them and releases the claim when they go away', async () => { + const f = await fixture({ desktop: false }) + try { + expect(await f.service.capabilities()).toEqual({ supported: false, reason: 'desktop-shared-texture-unavailable' }) + const provided = f.ctx.provide('sharedTexture', f.sharedTexture as never) + await vi.waitFor(() => { expect(forwarder.constructions).toHaveLength(1) }) + expect(f.sharedTexture.claim).toHaveBeenCalledOnce() + expect(await f.service.capabilities()).toEqual({ supported: true }) + await f.service.channel() + provided() + await vi.waitFor(() => { expect(f.claim.release).toHaveBeenCalledOnce() }) + expect(forwarder.methods.closeAll).toHaveBeenCalledOnce() + expect(await f.service.capabilities()).toEqual({ supported: false, reason: 'desktop-shared-texture-unavailable' }) + expect(f.service.isOpen(rx)).toBe(false) + } finally { await f.dispose() } +}) + +test('starts with a late Desktop receiver and releases channels when the provider leaves', async () => { + const f = await fixture({ receiver: false }) + try { + expect(await f.service.capabilities()).toEqual({ supported: false, reason: 'receiver-unavailable' }) + await expect(f.service.channel()).rejects.toThrow('Desktop frame receiver is unavailable') + const remove = f.ctx.provide('desktopFrameReceiver', { path: receiverAddon }) + await vi.waitFor(() => { expect(f.sharedTexture.claim).toHaveBeenCalledOnce() }) + await f.service.channel() + remove() + await vi.waitFor(() => { expect(f.claim.release).toHaveBeenCalledOnce() }) + expect(forwarder.methods.closeAll).toHaveBeenCalledOnce() + } finally { await f.dispose() } +}) + +test('reports the shared textures claimed when another consumer holds their claim', async () => { + const ctx = new Context() + ctx.provide('desktopFrameReceiver', { path: receiverAddon }) + const sharedTexture = { claim: vi.fn(() => { throw new Error('Desktop shared textures are already claimed') }) } + ctx.provide('sharedTexture', sharedTexture as never) + const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + const fiber = ctx.plugin(FrameForwarding, FrameForwarding.Config({})) + await fiber.await() + try { + const service = ctx.get('frameForwarding')! + expect(await service.capabilities()).toEqual({ supported: false, reason: 'desktop-shared-texture-claimed' }) + await expect(service.channel()).rejects.toThrow('claimed by another consumer') + expect(warn).toHaveBeenCalledWith(expect.objectContaining({ message: 'Desktop shared textures are already claimed' })) + expect(forwarder.constructions).toEqual([]) + } finally { await ctx.fiber.dispose() } +}) + +test('a channel closes with the scope that opened it, and an explicit close ends that binding', async () => { + const f = await fixture() + try { + const frames = (scope: Context) => scope.get('frameForwarding')! + const owner = f.ctx.plugin(async (scope) => { await frames(scope).channel() }) + await owner.await() + expect(forwarder.methods.close).not.toHaveBeenCalled() + await owner.dispose() + expect(forwarder.methods.close.mock.calls).toEqual([[rx]]) + forwarder.methods.channel.mockResolvedValueOnce({ tx: 'tx', rx: 'rx-2' }) + const closing = f.ctx.plugin(async (scope) => { + const { rx: opened } = await frames(scope).channel() + await frames(scope).close(opened) + }) + await closing.await() + await closing.dispose() + expect(forwarder.methods.close.mock.calls).toEqual([[rx], ['rx-2']]) + // A scope disposed while its channel opens cannot own it, so the channel closes and the call rejects. + const opening = Promise.withResolvers<{ tx: string; rx: string }>() + forwarder.methods.channel.mockReturnValueOnce(opening.promise) + let late: Promise | undefined + const gone = f.ctx.plugin((scope) => { late = frames(scope).channel() }) + await gone.await() + await gone.dispose() + opening.resolve({ tx: 'tx', rx: 'rx-3' }) + await expect(late).rejects.toThrow('inactive') + expect(forwarder.methods.close.mock.calls).toEqual([[rx], ['rx-2'], ['rx-3']]) + } finally { await f.dispose() } +}) + +test('reports unsupported without Desktop shared textures and refuses channels, while close stays idempotent', async () => { + const f = await fixture({ desktop: false }) + try { + expect(await f.service.capabilities()).toEqual({ supported: false, reason: 'desktop-shared-texture-unavailable' }) + await expect(f.service.channel()).rejects.toThrow('Desktop shared textures are unavailable.') + await expect(f.service.viewport(rx, { version: 1, width: 1, height: 1, deviceScaleFactor: 1, visible: true })).rejects.toThrow('unavailable') + await f.service.close(rx) + const events = subscribe(f.service) + await vi.waitFor(() => { expect(events.received).toEqual([{ kind: 'snapshot', channels: [] }]) }) + events.cancel() + await events.done + expect(forwarder.constructions).toEqual([]) + } finally { await f.dispose() } +}) + +test('starts every subscription with a snapshot and replaces an earlier renderer', async () => { + const f = await fixture() + try { + const empty = subscribe(f.service) + await vi.waitFor(() => { expect(empty.received).toEqual([{ kind: 'snapshot', channels: [] }]) }) + await f.service.channel() + forwarder.snapshot = [{ rx: 'rx-1', sequence: 1, channel: { state: 'idle' } }] + const first = subscribe(f.service) + await empty.done + await vi.waitFor(() => { expect(first.received).toHaveLength(1) }) + expect(first.received[0]).toEqual({ kind: 'snapshot', channels: forwarder.snapshot }) + forwarder.listeners!.event(state('rx-1', 2, 1)) + await vi.waitFor(() => { expect(first.received).toHaveLength(2) }) + expect(first.received[1]).toEqual(state('rx-1', 2, 1)) + const second = subscribe(f.service) + await first.done + second.cancel() + await second.done + forwarder.listeners!.event(state('rx-1', 3)) + } finally { await f.dispose() } +}) + +test('keeps the newest state per channel and resynchronizes with a snapshot when unread events exceed the limit', async () => { + const f = await fixture({ config: { maxQueuedEvents: 2 } }) + try { + await f.service.channel() + const events = subscribe(f.service) + const error: FrameForwardingEvent = { kind: 'error', rx, connectionId: 1 as FrameConnectionId, source: 'producer', error: 'stream failed' } + // The stream already took its snapshot; these wait unread. + forwarder.listeners!.event(state('rx-1', 1)) + forwarder.listeners!.event(state('rx-1', 2, 1)) + forwarder.listeners!.event(error) + // The forwarder publishes after it updated its channels, so the replacing snapshot holds every newest state. + forwarder.snapshot = [ + { rx: 'rx-1', sequence: 2, channel: { state: 'connected', connectionId: 1 } }, { rx: 'rx-2', sequence: 3, channel: { state: 'idle' } }, + ] + forwarder.listeners!.event(state('rx-2', 3)) + forwarder.listeners!.event(state('rx-2', 4, 2)) + await vi.waitFor(() => { expect(events.received).toHaveLength(3) }) + events.cancel() + await events.done + expect(events.received).toEqual([{ kind: 'snapshot', channels: [] }, { kind: 'snapshot', channels: forwarder.snapshot }, state('rx-2', 4, 2)]) + const limited = await fixture({ config: { maxQueuedEvents: 1 } }) + try { + await limited.service.channel() + forwarder.snapshot = [] + const one = subscribe(limited.service) + forwarder.listeners!.event(state('rx-1', 1)) + forwarder.snapshot = [{ rx: 'rx-1', sequence: 1, channel: { state: 'idle' } }, { rx: 'rx-2', sequence: 2, channel: { state: 'idle' } }] + forwarder.listeners!.event(state('rx-2', 2)) + await vi.waitFor(() => { expect(one.received).toHaveLength(2) }) + one.cancel() + await one.done + expect(one.received).toEqual([{ kind: 'snapshot', channels: [] }, { kind: 'snapshot', channels: forwarder.snapshot }]) + } finally { await limited.dispose() } + } finally { await f.dispose() } +}) + +test('a resynchronizing snapshot keeps the unread closures of channels the forwarder already forgot', async () => { + const f = await fixture({ config: { maxQueuedEvents: 2 } }) + try { + const events = subscribe(f.service) + const error: FrameForwardingEvent = { kind: 'error', rx, connectionId: 1 as FrameConnectionId, source: 'producer', error: 'stream failed' } + const failed = { rx: brandString('rx-failed'), sequence: 1, channel: { state: 'closed', cause: 'failed', reason: 'Native channel failed: device lost' } } as const + const closed = { rx, sequence: 3, channel: { state: 'closed', cause: 'closed', reason: 'Native channel closed' } } as const + // rx-failed published its closure and completed its teardown before the renderer read the closure. + forwarder.listeners!.event({ kind: 'state', ...failed }) + forwarder.listeners!.event(error) + forwarder.snapshot = [{ rx: 'rx-1', sequence: 2, channel: { state: 'idle' } }] + forwarder.listeners!.event(state('rx-1', 2)) + // rx-1 is still closing, so the forwarder's snapshot already carries its closure; the earlier snapshot carries rx-failed's. + forwarder.snapshot = [closed] + forwarder.listeners!.event({ kind: 'state', ...closed }) + forwarder.listeners!.event(error) + await vi.waitFor(() => { expect(events.received).toHaveLength(2) }) + events.cancel() + await events.done + expect(events.received).toEqual([{ kind: 'snapshot', channels: [] }, { kind: 'snapshot', channels: [closed, failed] }]) + } finally { await f.dispose() } +}) + +const closure = (channel: string, sequence: number) => + ({ rx: brandString(channel), sequence, channel: { state: 'closed', cause: 'closed', reason: 'Native channel closed' } }) as const + +test('a resynchronizing snapshot keeps every current channel and only the newest forgotten closures', async () => { + const f = await fixture({ config: { maxQueuedEvents: 2 } }) + try { + const events = subscribe(f.service) + const live = { rx: brandString('rx-live'), sequence: 1, channel: { state: 'idle' } } as const + // An unread renderer sees ten channels open and close; each closure is still closing when it is published. + for (let index = 1; index <= 10; index++) { + const closing = closure(`rx-${index}`, index + 1) + forwarder.snapshot = [live, closing] + forwarder.listeners!.event({ kind: 'state', ...closing }) + } + await vi.waitFor(() => { expect(events.received).toHaveLength(3) }) + events.cancel() + await events.done + // Without the bound the snapshot would carry all nine closures preceding the last one. + expect(events.received).toEqual([ + { kind: 'snapshot', channels: [] }, + { kind: 'snapshot', channels: [live, closure('rx-9', 10), closure('rx-7', 8), closure('rx-8', 9)] }, + { kind: 'state', ...closure('rx-10', 11) }, + ]) + } finally { await f.dispose() } +}) + +test('a resynchronizing snapshot keeps the newest closure of a channel that several unread events carry', async () => { + const f = await fixture({ config: { maxQueuedEvents: 3 } }) + try { + const events = subscribe(f.service) + const error: FrameForwardingEvent = { kind: 'error', rx, connectionId: 1 as FrameConnectionId, source: 'producer', error: 'stream failed' } + for (let index = 0; index < 3; index++) forwarder.listeners!.event(error) + forwarder.snapshot = [closure('rx-a', 5), closure('rx-b', 6)] + forwarder.listeners!.event(state('rx-live', 7)) + forwarder.listeners!.event({ kind: 'state', ...closure('rx-a', 8) }) + forwarder.listeners!.event({ kind: 'state', ...closure('rx-b', 2) }) + forwarder.snapshot = [{ rx: 'rx-live', sequence: 9, channel: { state: 'idle' } }] + forwarder.listeners!.event(state('rx-live', 9)) + await vi.waitFor(() => { expect(events.received).toHaveLength(2) }) + events.cancel() + await events.done + expect(events.received[1]).toEqual({ kind: 'snapshot', channels: [...forwarder.snapshot, closure('rx-b', 6), closure('rx-a', 8)] }) + } finally { await f.dispose() } +}) + +test('a channel the forwarder closed itself releases the scope that opened it', async () => { + const f = await fixture() + try { + const owner = f.ctx.plugin(async (scope) => { await scope.get('frameForwarding')!.channel() }) + await owner.await() + forwarder.methods.close.mockRejectedValueOnce(new Error('receiver teardown failed')) + forwarder.listeners!.event({ kind: 'state', rx, sequence: 5, channel: { state: 'closed', cause: 'lost', reason: 'Desktop invalidated a presented frame' } }) + expect(forwarder.methods.close.mock.calls).toEqual([[rx]]) + await owner.dispose() + expect(forwarder.methods.close.mock.calls).toEqual([[rx]]) + // A closed state without an owner, such as one the owner's own close published, changes nothing. + forwarder.listeners!.event({ kind: 'state', rx, sequence: 6, channel: { state: 'closed', cause: 'closed', reason: 'Native channel closed' } }) + expect(forwarder.methods.close.mock.calls).toEqual([[rx]]) + } finally { await f.dispose() } +}) + +test('disposal ends the renderer stream and logs a failed receiver cleanup', async () => { + const f = await fixture() + const events = subscribe(f.service) + await f.service.channel() + forwarder.methods.closeAll.mockRejectedValueOnce(new Error('cleanup failed')) + await f.dispose() + await events.done + expect(f.warn).toHaveBeenCalledWith(expect.objectContaining({ message: 'cleanup failed' })) +}) diff --git a/packages/experimental/frame-forwarding/tests/wire.client.spec.ts b/packages/experimental/frame-forwarding/tests/wire.client.spec.ts new file mode 100644 index 0000000000..50400445e8 --- /dev/null +++ b/packages/experimental/frame-forwarding/tests/wire.client.spec.ts @@ -0,0 +1,644 @@ +// @vitest-environment jsdom +/** + * Leases stay with their consumer across subscription and channel teardown; frames route by metadata and states by + * sequence; the document's fullscreen element is held by one channel and reported to every channel. + */ +import { afterEach, expect, test, vi } from 'vitest' +import { brandString } from '@deepseek-ai/dsh-brand' +import type { SharedTextureClientExport, SharedTextureLease } from '@deepseek-ai/dsh-shared-texture/client' +import type { FrameChannelState, FrameConnectionId, FrameRxId } from '../src/types.ts' +import type { FrameChannelReceiver, FrameForwardingFrameLease, FrameRxEvent } from '../src/client/api.ts' +import { FrameRx } from '../src/client/rx.ts' +import { adaptFrameForwardingBridge, type FrameForwardingRemote } from '../src/client/wire.ts' + +const rx = brandString('rx') +const other = brandString('other') +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllGlobals() + Reflect.deleteProperty(document, 'fullscreenElement') + Reflect.deleteProperty(document, 'exitFullscreen') +}) +/** jsdom has no Fullscreen API; this document shows one element fullscreen and reports each change as Chromium does. */ +function fullscreenDocument() { + let current: Element | null = null + const change = (element: Element | null): void => { + current = element + document.dispatchEvent(new Event('fullscreenchange')) + } + Object.defineProperty(document, 'fullscreenElement', { configurable: true, get: () => current }) + const exit = vi.fn(async () => { change(null) }) + Object.defineProperty(document, 'exitFullscreen', { configurable: true, value: exit }) + const element = () => { + const target = document.createElement('div') + return Object.assign(target, { requestFullscreen: vi.fn(async () => { change(target) }) }) + } + return { change, exit, element } +} +function fixture() { + const fullscreen = fullscreenDocument() + let consumer: ((lease: SharedTextureLease) => void) | undefined + const textures = { + onFrame: vi.fn((listener) => { + consumer = listener + return () => { if (consumer === listener) consumer = undefined } + }), + } satisfies SharedTextureClientExport + const remote = { + viewport: vi.fn(async () => ({ ok: true, value: { applied: true, connectionId: 1 as FrameConnectionId } })), + } + // Like the preload, a texture without a consumer is released at once. + const deliver = (lease: SharedTextureLease): void => { if (consumer === undefined) lease.release(); else consumer(lease) } + const bridge = adaptFrameForwardingBridge(textures, remote, document) + return { + textures, remote, fullscreen, bridge, deliver, + attach: (id: FrameRxId, callbacks: Partial = {}) => + bridge.attach(id, { onFrame: vi.fn(), onEvent: vi.fn(), ...callbacks }), + consuming: () => consumer !== undefined, + } +} +const metadata = (revision = 1, id: FrameRxId | string = rx) => + ({ rx: id, connectionId: 1, requestId: String(revision), frameId: revision, generation: 1, revision, width: 2, height: 2 }) +function texture(revision = 1, id: FrameRxId | string = rx) { + return { frame: {} as VideoFrame, metadata: metadata(revision, id), release: vi.fn() } satisfies SharedTextureLease +} +const connected = (connectionId: number): FrameChannelState => ({ state: 'connected', connectionId: connectionId as FrameConnectionId }) +const states = (events: FrameRxEvent[]) => events.filter(event => event.kind === 'state').map(event => event.channel) + +test('forwards viewports to the Host with its outcome and surfaces its rejection', async () => { + const f = fixture(), viewport = { version: 1, width: 2, height: 2, deviceScaleFactor: 1, visible: true } + expect(await f.bridge.setViewport(rx, viewport)).toEqual({ applied: true, connectionId: 1 }) + expect(f.remote.viewport).toHaveBeenCalledWith(rx, viewport) + f.remote.viewport.mockResolvedValueOnce({ ok: false, error: { message: 'Native viewport version must increase' } } as never) + await expect(f.bridge.setViewport(rx, viewport)).rejects.toThrow('must increase') +}) + +test('delivers shared frames by channel and preserves owned leases after unsubscribe and close', async () => { + const f = fixture(), delivered: FrameForwardingFrameLease[] = [], lease = texture() + const remove = f.attach(rx, { onFrame: value => delivered.push(value) }) + f.deliver(lease) + expect(delivered).toMatchObject([{ frame: lease.frame, metadata: lease.metadata }]) + await remove() + expect(lease.release).not.toHaveBeenCalled() + delivered[0]!.release() + expect(lease.release).toHaveBeenCalledOnce() +}) + +test('a replacement connected in the close listener keeps routing events and frames for the same rx', async () => { + const f = fixture(), present = vi.fn() + f.bridge.apply({ kind: 'state', rx, sequence: 1, channel: connected(1) }) + const first = new FrameRx(rx, f.bridge) + let next: FrameRx | undefined + first.onEvent((event) => { + if (event.kind === 'state' && event.channel.state === 'closed') next = new FrameRx(rx, f.bridge) + }) + await first.close() + if (!next) throw new Error('The close listener did not reconnect') + expect(next.connectionId).toBe(1) + next.consume(present, vi.fn()) + f.bridge.apply({ kind: 'state', rx, sequence: 2, channel: connected(2) }) + const lease = texture() + Object.assign(lease.metadata, { connectionId: 2, generation: 0 }) + f.deliver(lease) + expect(next.connectionId).toBe(2) + await next.close() + expect(present).toHaveBeenCalledExactlyOnceWith({ image: lease.frame, metadata: lease.metadata }) + expect(lease.release).toHaveBeenCalledOnce() +}) + +test('contains a throwing consumer, releases its lease and reports the failure to the channel', () => { + const f = fixture(), events: FrameRxEvent[] = [], lease = texture() + f.attach(rx, { onFrame() { throw new Error('paint failed') }, onEvent: event => events.push(event) }) + expect(() => { f.deliver(lease) }).not.toThrow() + expect(lease.release).toHaveBeenCalledOnce() + expect(events).toEqual([{ kind: 'failure', error: 'paint failed' }]) + const after = texture(2) + f.deliver(after) + expect(after.release).toHaveBeenCalledOnce() +}) + +test('a failed obsolete consumer cannot drop its replacement', async () => { + const f = fixture(), replacement = vi.fn(), lease = texture(), unrouted = texture() + const remove = f.attach(rx, { onFrame() { + void remove() + f.deliver(unrouted) + f.attach(rx, { onFrame: replacement }) + throw new Error('old consumer failed') + } }) + f.deliver(lease) + await remove() + expect(lease.release).toHaveBeenCalledOnce() + expect(unrouted.release).toHaveBeenCalledOnce() + const fresh = texture(2) + f.deliver(fresh) + expect(replacement).toHaveBeenCalledWith(expect.objectContaining({ frame: fresh.frame })) + fresh.release() +}) + +test('applies channel states in sequence order and gives a late observer the latest one', () => { + const f = fixture(), events: FrameRxEvent[] = [] + f.bridge.apply({ kind: 'state', rx, sequence: 2, channel: connected(1) }) + const detach = f.attach(rx, { onEvent: event => events.push(event) }) + f.bridge.apply({ kind: 'state', rx, sequence: 1, channel: { state: 'idle' } }) + f.bridge.apply({ kind: 'state', rx, sequence: 2, channel: { state: 'idle' } }) + f.bridge.apply({ kind: 'state', rx, sequence: 3, channel: { state: 'draining', connectionId: 1 as FrameConnectionId } }) + f.bridge.apply({ kind: 'error', rx, connectionId: 1 as FrameConnectionId, source: 'producer', error: 'stream failed' }) + f.bridge.apply({ kind: 'error', rx, connectionId: 1 as FrameConnectionId, source: 'presentation', requestId: 'tile', error: 'transfer failed' }) + f.bridge.apply({ kind: 'state', rx: other, sequence: 4, channel: { state: 'idle' } }) + expect(events).toEqual([ + { kind: 'state', channel: connected(1) }, + { kind: 'state', channel: { state: 'draining', connectionId: 1 } }, + { kind: 'error', connectionId: 1, source: 'producer', error: 'stream failed' }, + { kind: 'error', connectionId: 1, source: 'presentation', requestId: 'tile', error: 'transfer failed' }, + ]) + void detach() + f.bridge.apply({ kind: 'state', rx, sequence: 5, channel: { state: 'idle' } }) + expect(events).toHaveLength(4) +}) + +test('a snapshot replaces every known state and reports channels that closed meanwhile as lost', () => { + const f = fixture(), seen: FrameRxEvent[] = [], gone: FrameRxEvent[] = [] + f.bridge.apply({ kind: 'state', rx, sequence: 9, channel: connected(1) }) + f.bridge.apply({ kind: 'state', rx: other, sequence: 10, channel: { state: 'idle' } }) + f.attach(rx, { onEvent: event => seen.push(event) }) + const detach = f.attach(other, { onEvent: event => gone.push(event) }) + // A new subscription numbers its states afresh. + f.bridge.apply({ kind: 'snapshot', channels: [{ rx, sequence: 1, channel: connected(2) }] }) + f.bridge.apply({ kind: 'state', rx, sequence: 2, channel: { state: 'draining', connectionId: 2 as FrameConnectionId } }) + expect(states(seen)).toEqual([connected(1), connected(2), { state: 'draining', connectionId: 2 }]) + expect(states(gone)).toEqual([ + { state: 'idle' }, { state: 'closed', cause: 'lost', reason: 'Native channel closed while the renderer was not subscribed' }, + ]) + const late: FrameRxEvent[] = [] + void detach() + f.attach(other, { onEvent: event => late.push(event) }) + expect(late).toEqual([]) +}) + +test('a snapshot reports the closure it carries to an observer that never received the channel state', () => { + const f = fixture(), seen: FrameRxEvent[] = [] + f.attach(rx, { onEvent: event => seen.push(event) }) + const failed = { state: 'closed', cause: 'failed', reason: 'Native channel failed: device lost' } as const + f.bridge.apply({ kind: 'snapshot', channels: [{ rx, sequence: 4, channel: failed }] }) + expect(states(seen)).toEqual([failed]) +}) + +const closedState = { state: 'closed', cause: 'closed', reason: 'Native channel closed' } as const + +test('forgets a closed channel once its consumer detaches, but keeps an open one for its next consumer', async () => { + const f = fixture(), seen: FrameRxEvent[] = [], late: FrameRxEvent[] = [], open: FrameRxEvent[] = [] + f.bridge.apply({ kind: 'state', rx, sequence: 1, channel: connected(1) }) + const detach = f.attach(rx, { onEvent: event => seen.push(event) }) + f.bridge.apply({ kind: 'state', rx, sequence: 2, channel: closedState }) + expect(states(seen)).toEqual([connected(1), closedState]) + await detach() + f.attach(rx, { onEvent: event => late.push(event) }) + expect(late).toEqual([]) + // A closure that arrived before any consumer still reaches the first one, which forgets it on detaching. + f.bridge.apply({ kind: 'snapshot', channels: [{ rx: other, sequence: 3, channel: closedState }] }) + const detachOther = f.attach(other, { onEvent: event => open.push(event) }) + expect(states(open)).toEqual([closedState]) + await detachOther() + open.length = 0 + f.attach(other, { onEvent: event => open.push(event) }) + expect(open).toEqual([]) +}) + +test('keeps only the newest closures of channels no consumer attached, while attached and open channels stay', async () => { + const f = fixture(), id = (index: number) => brandString(`rx-${index}`) + const replay = (channel: FrameRxId): FrameChannelState[] => { + const events: FrameRxEvent[] = [] + void f.attach(channel, { onEvent: event => events.push(event) })() + return states(events) + } + f.bridge.apply({ kind: 'state', rx: other, sequence: 1, channel: connected(1) }) + const attached: FrameRxEvent[] = [] + f.attach(rx, { onEvent: event => attached.push(event) }) + f.bridge.apply({ kind: 'state', rx, sequence: 2, channel: closedState }) + for (let index = 0; index < 100; index++) f.bridge.apply({ kind: 'state', rx: id(index), sequence: 3 + index, channel: closedState }) + expect(states(attached)).toEqual([closedState]) + expect(replay(id(35))).toEqual([]) + expect(replay(id(36))).toEqual([closedState]) + expect(replay(id(99))).toEqual([closedState]) + expect(replay(other)).toEqual([connected(1)]) + // A snapshot with more closures than the bound keeps its newest ones too. + f.bridge.apply({ kind: 'snapshot', channels: Array.from({ length: 70 }, (_, index) => ({ rx: id(index), sequence: index, channel: closedState })) }) + expect(replay(id(5))).toEqual([]) + expect(replay(id(6))).toEqual([closedState]) + // The attached closure outlived the bound: the snapshot that omits it reports it vanished. + expect(states(attached)).toEqual([ + closedState, { state: 'closed', cause: 'lost', reason: 'Native channel closed while the renderer was not subscribed' }, + ]) +}) + +test('a bridge whose texture subscription fails observes nothing, and duplicate frame consumers are rejected', () => { + const f = fixture() + const listen = vi.spyOn(document, 'addEventListener') + const taken = { onFrame: () => { throw new Error('Shared textures already have a consumer') } } satisfies SharedTextureClientExport + expect(() => adaptFrameForwardingBridge(taken, f.remote, document)).toThrow('already have a consumer') + expect(listen).not.toHaveBeenCalled() + const remove = f.attach(rx) + expect(() => f.attach(rx)).toThrow('already has') + void remove() + f.attach(rx) +}) + +test.each([ + ['a non-object', 'nothing'], + ['null', null], + ['a non-string channel', { ...metadata(), rx: 7 }], + ['an empty channel', { ...metadata(), rx: '' }], + ['a missing connection', { ...metadata(), connectionId: undefined }], + ['connection zero', { ...metadata(), connectionId: 0 }], + ['a non-string request', { ...metadata(), requestId: 7 }], + ['a negative frame', { ...metadata(), frameId: -1 }], + ['a fractional generation', { ...metadata(), generation: 1.5 }], + ['a missing revision', { ...metadata(), revision: undefined }], + ['a string width', { ...metadata(), width: '2' }], + ['an infinite height', { ...metadata(), height: Infinity }], + ['an unknown channel', metadata(1, 'unknown')], +])('releases a texture whose metadata is %s', (_name, value) => { + const f = fixture(), consume = vi.fn() + f.attach(rx, { onFrame: consume }) + const lease = { frame: {} as VideoFrame, metadata: value, release: vi.fn() } + f.deliver(lease) + expect(lease.release).toHaveBeenCalledOnce() + expect(consume).not.toHaveBeenCalled() +}) + +test('delivers only the frame fields and contains a non-Error consumer failure', () => { + const f = fixture(), events: FrameRxEvent[] = [], delivered: FrameForwardingFrameLease[] = [] + f.attach(rx, { onFrame(lease) { delivered.push(lease); throw 'paint failed' }, onEvent: event => events.push(event) }) + const lease = { ...texture(), metadata: { ...metadata(), sourceKeyedMutex: true, tileKey: 'a' } } + f.deliver(lease) + expect(delivered[0]?.metadata).toEqual(metadata()) + expect(lease.release).toHaveBeenCalledOnce() + expect(events).toEqual([{ kind: 'failure', error: 'paint failed' }]) +}) + +test('the bridge keeps one texture subscription from creation until disposal, with or without channels', () => { + const f = fixture(), first = vi.fn(), second = vi.fn() + expect(f.consuming()).toBe(true) + const unrouted = texture() + f.deliver(unrouted) + expect(unrouted.release).toHaveBeenCalledOnce() + const removeFirst = f.attach(rx, { onFrame: first }) + f.attach(other, { onFrame: second }) + void removeFirst() + const lease = texture(1, other) + f.deliver(lease) + expect(second).toHaveBeenCalledOnce() + expect(first).not.toHaveBeenCalled() + lease.release() + const events: FrameRxEvent[] = [] + f.attach(rx, { onEvent: event => events.push(event) }) + f.bridge.dispose() + expect(f.consuming()).toBe(false) + expect(f.textures.onFrame).toHaveBeenCalledOnce() + f.fullscreen.change(document.body) + expect(events).toEqual([{ kind: 'failure', error: 'Frame-forwarding Client disposed.' }]) +}) + +test('a failed bridge fails every known channel once and every later subscription at once', async () => { + const f = fixture(), seen: FrameRxEvent[] = [], gone: FrameRxEvent[] = [], delivered: FrameForwardingFrameLease[] = [] + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const failure = { kind: 'failure', error: 'events failed' } as const + f.bridge.apply({ kind: 'snapshot', channels: [{ rx, sequence: 1, channel: connected(1) }] }) + f.attach(rx, { onFrame: lease => delivered.push(lease), onEvent: event => seen.push(event) }) + f.attach(other, { onEvent: (event) => { gone.push(event); throw new Error('listener failed') } }) + const held = texture() + f.deliver(held) + f.bridge.fail('events failed') + f.bridge.fail('failed again') + expect(seen).toEqual([{ kind: 'state', channel: connected(1) }, failure]) + expect(gone).toEqual([failure]) + expect(log).toHaveBeenCalledWith('Native channel listener failed', expect.objectContaining({ message: 'listener failed' })) + // A delivered lease stays with its holder; later textures have no consumer and are released. + expect(held.release).not.toHaveBeenCalled() + delivered[0]!.release() + const late = texture(2) + f.deliver(late) + expect(late.release).toHaveBeenCalledOnce() + const replacement = vi.fn() + const later: FrameRxEvent[] = [] + const remove = f.attach(rx, { onFrame: replacement, onEvent: event => later.push(event) }) + void remove() + const after = texture(3) + f.deliver(after) + expect(after.release).toHaveBeenCalledOnce() + expect(replacement).not.toHaveBeenCalled() + // Host events no longer reach any channel, and the forgotten states are not replayed. + f.bridge.apply({ kind: 'state', rx, sequence: 2, channel: { state: 'idle' } }) + expect(later).toEqual([failure]) + expect(seen).toHaveLength(2) + await expect(f.bridge.setViewport(rx, { version: 1, width: 2, height: 2, deviceScaleFactor: 1, visible: true })) + .rejects.toThrow('events failed') + expect(f.remote.viewport).not.toHaveBeenCalled() + f.bridge.dispose() + expect(f.consuming()).toBe(false) + expect(seen).toHaveLength(2) +}) + +test('failing a disposed bridge changes nothing', async () => { + const f = fixture(), events: FrameRxEvent[] = [] + f.bridge.apply({ kind: 'state', rx, sequence: 1, channel: connected(1) }) + f.bridge.dispose() + f.bridge.fail('events failed') + f.attach(rx, { onEvent: event => events.push(event) }) + expect(events).toEqual([{ kind: 'state', channel: connected(1) }]) + await f.bridge.setViewport(rx, { version: 1, width: 2, height: 2, deviceScaleFactor: 1, visible: true }) + expect(f.remote.viewport).toHaveBeenCalledOnce() +}) + +test('reports fullscreen to every channel with its holder and gives a late observer the current state', async () => { + const f = fixture(), seen: FrameRxEvent[] = [], covered: FrameRxEvent[] = [] + f.attach(other, { onEvent: event => covered.push(event) }) + const view = f.fullscreen.element() + await f.bridge.requestFullscreen(rx, view) + f.attach(rx, { onEvent: event => seen.push(event) }) + expect(view.requestFullscreen).toHaveBeenCalledOnce() + const late: FrameRxEvent[] = [] + const lateRx = brandString('late') + f.bridge.apply({ kind: 'snapshot', channels: [{ rx: lateRx, sequence: 1, channel: connected(1) }] }) + f.attach(lateRx, { onEvent: event => late.push(event) }) + expect(late).toEqual([{ kind: 'state', channel: connected(1) }, { kind: 'fullscreen', active: true, holder: false }]) + // Fullscreen another element took over covers its former holder too. + f.fullscreen.change(document.body) + f.fullscreen.change(null) + // Fullscreen that no channel requested covers every channel. + f.fullscreen.change(document.body) + f.fullscreen.change(null) + expect(seen).toEqual([ + { kind: 'fullscreen', active: true, holder: true }, + { kind: 'fullscreen', active: true, holder: false }, + { kind: 'fullscreen', active: false, holder: true }, + { kind: 'fullscreen', active: true, holder: false }, + { kind: 'fullscreen', active: false, holder: false }, + ]) + expect(covered.map(event => event.kind === 'fullscreen' && event.holder)).toEqual([false, false, false, false, false]) +}) + +test('leaves every element a holder stacked by moving its fullscreen, so another channel can take it', async () => { + const f = fixture() + // Chromium keeps an earlier fullscreen element below a later one, and each exit reveals the element below it. + const stack: Element[] = [] + const show = () => { f.fullscreen.change(stack.at(-1) ?? null) } + const stacked = () => { + const target = f.fullscreen.element() + target.requestFullscreen.mockImplementation(async () => { + if (stack.includes(target)) stack.splice(stack.indexOf(target), 1) + stack.push(target) + show() + }) + return target + } + f.fullscreen.exit.mockImplementation(async () => { stack.pop(); show() }) + const events: FrameRxEvent[] = [] + f.attach(rx, { onEvent: event => events.push(event) }) + const first = stacked(), moved = stacked(), second = f.fullscreen.element() + await f.bridge.requestFullscreen(rx, first) + await f.bridge.requestFullscreen(rx, moved) + await f.bridge.exitFullscreen(rx) + expect(f.fullscreen.exit).toHaveBeenCalledTimes(2) + expect(document.fullscreenElement).toBeNull() + // The revealed earlier element stays the channel's own while the exit continues. + expect(events.filter(event => event.kind === 'fullscreen').map(event => event.kind === 'fullscreen' && [event.active, event.holder])) + .toEqual([[true, true], [true, true], [true, true], [false, true]]) + await f.bridge.requestFullscreen(other, second) + expect(document.fullscreenElement).toBe(second) +}) + +test('an exit or failure during a refused fullscreen move leaves the element that stays fullscreen', async () => { + for (const end of ['exit', 'fail'] as const) { + const f = fixture() + const view = f.fullscreen.element(), removed = f.fullscreen.element(), second = f.fullscreen.element() + await f.bridge.requestFullscreen(rx, view) + const refused = Promise.withResolvers() + removed.requestFullscreen.mockReturnValueOnce(refused.promise) + const moving = f.bridge.requestFullscreen(rx, removed) + let ending = Promise.resolve() + if (end === 'exit') ending = f.bridge.exitFullscreen(rx) + else f.bridge.fail('renderer failed') + refused.reject(new TypeError('Element is not connected')) + await expect(moving).rejects.toThrow('not connected') + await ending + await vi.waitFor(() => { expect(document.fullscreenElement).toBeNull() }) + if (end === 'exit') await f.bridge.requestFullscreen(other, second) + f.bridge.dispose() + } +}) + +test('one channel holds fullscreen at a time, and a refused entry frees it', async () => { + const f = fixture() + const view = f.fullscreen.element(), second = f.fullscreen.element() + view.requestFullscreen.mockRejectedValueOnce(new TypeError('Permissions check failed')) + await expect(f.bridge.requestFullscreen(rx, view)).rejects.toThrow('Permissions check failed') + await f.bridge.requestFullscreen(other, second) + await expect(f.bridge.requestFullscreen(rx, view)).rejects.toThrow('Another native channel holds fullscreen.') + // The holder may move its fullscreen to another of its elements. + await f.bridge.requestFullscreen(other, view) + expect(document.fullscreenElement).toBe(view) + await f.bridge.exitFullscreen(other) + await f.bridge.requestFullscreen(rx, view) + // A failed re-entry of the holder leaves a newer entry in place. + const retry = f.fullscreen.element() + const refused = Promise.withResolvers() + retry.requestFullscreen.mockReturnValueOnce(refused.promise) + const failing = f.bridge.requestFullscreen(rx, retry) + await f.bridge.requestFullscreen(rx, view) + refused.reject(new TypeError('refused')) + await expect(failing).rejects.toThrow('refused') + await expect(f.bridge.requestFullscreen(other, second)).rejects.toThrow('Another native channel holds fullscreen.') + // A refused move keeps the holder of the element that stays fullscreen, so the channel can still leave it. + const removed = f.fullscreen.element() + removed.requestFullscreen.mockRejectedValueOnce(new TypeError('Element is not connected')) + await expect(f.bridge.requestFullscreen(rx, removed)).rejects.toThrow('not connected') + expect(document.fullscreenElement).toBe(view) + await expect(f.bridge.requestFullscreen(other, second)).rejects.toThrow('Another native channel holds fullscreen.') + await f.bridge.exitFullscreen(rx) + expect(document.fullscreenElement).toBeNull() +}) + +test('a request refused while an earlier one is pending keeps the hold for the entry that completes', async () => { + const f = fixture(), events: FrameRxEvent[] = [] + const detach = f.attach(rx, { onEvent: event => events.push(event) }) + const view = f.fullscreen.element(), refused = f.fullscreen.element(), second = f.fullscreen.element() + const entering = Promise.withResolvers() + view.requestFullscreen.mockImplementationOnce(async () => { await entering.promise; f.fullscreen.change(view) }) + const entry = f.bridge.requestFullscreen(rx, view) + refused.requestFullscreen.mockRejectedValueOnce(new TypeError('Permissions check failed')) + await expect(f.bridge.requestFullscreen(rx, refused)).rejects.toThrow('Permissions check failed') + await expect(f.bridge.requestFullscreen(other, second)).rejects.toThrow('Another native channel holds fullscreen.') + entering.resolve(undefined) + await entry + expect(events).toEqual([{ kind: 'fullscreen', active: true, holder: true }]) + // Closing the channel leaves the fullscreen its pending entry took. + await detach() + expect(f.fullscreen.exit).toHaveBeenCalledOnce() + expect(document.fullscreenElement).toBeNull() +}) + +test('fullscreen that ends while a request is pending stays held until that request settles', async () => { + for (const enters of [true, false]) { + const f = fixture() + const view = f.fullscreen.element(), moved = f.fullscreen.element(), second = f.fullscreen.element() + await f.bridge.requestFullscreen(rx, view) + const settling = Promise.withResolvers() + moved.requestFullscreen.mockImplementationOnce(async () => { + await settling.promise + if (!enters) throw new TypeError('Element is not connected') + f.fullscreen.change(moved) + }) + const moving = f.bridge.requestFullscreen(rx, moved).then(() => 'entered', (error: unknown) => (error as Error).message) + // Escape leaves fullscreen before the move settles. + f.fullscreen.change(null) + await expect(f.bridge.requestFullscreen(other, second)).rejects.toThrow('Another native channel holds fullscreen.') + settling.resolve(undefined) + expect(await moving).toBe(enters ? 'entered' : 'Element is not connected') + await f.bridge.exitFullscreen(rx) + expect(f.fullscreen.exit).toHaveBeenCalledTimes(enters ? 1 : 0) + // The hold ends with the request's fullscreen, so another channel can take it. + await f.bridge.requestFullscreen(other, second) + expect(document.fullscreenElement).toBe(second) + } +}) + +test('a channel whose entry is still pending hears no end of fullscreen that another element held', async () => { + const f = fixture(), events: FrameRxEvent[] = [] + f.attach(rx, { onEvent: event => events.push(event) }) + const view = f.fullscreen.element() + f.fullscreen.change(document.body) + const entering = Promise.withResolvers() + view.requestFullscreen.mockImplementationOnce(async () => { await entering.promise; f.fullscreen.change(view) }) + const entry = f.bridge.requestFullscreen(rx, view) + // The page leaves its own fullscreen before the channel's entry completes. + f.fullscreen.change(null) + entering.resolve(undefined) + await entry + expect(events.filter(event => event.kind === 'fullscreen')).toEqual([ + { kind: 'fullscreen', active: true, holder: false }, + { kind: 'fullscreen', active: false, holder: false }, + { kind: 'fullscreen', active: true, holder: true }, + ]) +}) + +test('exits of one channel run one at a time, so a second exit leaves the page fullscreen below its element', async () => { + const f = fixture(), stack: Element[] = [document.body] + const show = () => { f.fullscreen.change(stack.at(-1) ?? null) } + show() + const view = f.fullscreen.element() + view.requestFullscreen.mockImplementation(async () => { stack.push(view); show() }) + await f.bridge.requestFullscreen(rx, view) + // Chromium settles an exit after the call returns, so both exits would see the channel's element on top. + const exiting = Promise.withResolvers() + f.fullscreen.exit.mockImplementation(async () => { await exiting.promise; stack.pop(); show() }) + const first = f.bridge.exitFullscreen(rx), second = f.bridge.exitFullscreen(rx) + await vi.waitFor(() => { expect(f.fullscreen.exit).toHaveBeenCalled() }) + expect(f.fullscreen.exit).toHaveBeenCalledOnce() + exiting.resolve(undefined) + await first + await second + expect(f.fullscreen.exit).toHaveBeenCalledOnce() + expect(document.fullscreenElement).toBe(document.body) +}) + +test('a refused request keeps the hold of a channel whose element another element covers', async () => { + const f = fixture(), stack: Element[] = [] + const show = () => { f.fullscreen.change(stack.at(-1) ?? null) } + const view = f.fullscreen.element(), refused = f.fullscreen.element(), second = f.fullscreen.element() + view.requestFullscreen.mockImplementation(async () => { stack.push(view); show() }) + f.fullscreen.exit.mockImplementation(async () => { stack.pop(); show() }) + await f.bridge.requestFullscreen(rx, view) + // The page shows its own element above the channel's, and the document reports only the page element. + stack.push(document.body) + show() + refused.requestFullscreen.mockRejectedValueOnce(new TypeError('Permissions check failed')) + await expect(f.bridge.requestFullscreen(rx, refused)).rejects.toThrow('Permissions check failed') + await expect(f.bridge.requestFullscreen(other, second)).rejects.toThrow('Another native channel holds fullscreen.') + // Once the page leaves, the channel still owns the element it revealed and can leave it. + stack.pop() + show() + await f.bridge.exitFullscreen(rx) + expect(document.fullscreenElement).toBeNull() +}) + +test('exits only the fullscreen its channel holds, after a pending entry, and tolerates an exit Chromium performed', async () => { + const f = fixture() + await f.bridge.exitFullscreen(rx) + const view = f.fullscreen.element() + const entering = Promise.withResolvers() + view.requestFullscreen.mockImplementationOnce(async () => { await entering.promise; f.fullscreen.change(view) }) + const entry = f.bridge.requestFullscreen(rx, view) + const exit = f.bridge.exitFullscreen(rx) + await f.bridge.exitFullscreen(other) + expect(f.fullscreen.exit).not.toHaveBeenCalled() + entering.resolve(undefined) + await entry + await exit + expect(f.fullscreen.exit).toHaveBeenCalledOnce() + expect(document.fullscreenElement).toBeNull() + await f.bridge.exitFullscreen(rx) + expect(f.fullscreen.exit).toHaveBeenCalledOnce() + // Escape leaves fullscreen before the requested exit runs. + await f.bridge.requestFullscreen(rx, view) + f.fullscreen.exit.mockImplementationOnce(async () => { throw new TypeError('Document not active') }) + vi.spyOn(document, 'fullscreenElement', 'get').mockReturnValueOnce(view).mockReturnValue(null) + await f.bridge.exitFullscreen(rx) + vi.restoreAllMocks() + // An exit Chromium refuses while the element stays fullscreen fails visibly. + f.fullscreen.change(null) + await f.bridge.requestFullscreen(rx, view) + f.fullscreen.exit.mockRejectedValueOnce(new TypeError('exit refused')) + await expect(f.bridge.exitFullscreen(rx)).rejects.toThrow('exit refused') + // Fullscreen another element took over is not the holder's to exit. + f.fullscreen.change(document.body) + await f.bridge.exitFullscreen(rx) + expect(document.fullscreenElement).toBe(document.body) +}) + +test('closing the holding channel or disposing the bridge leaves its fullscreen', async () => { + const f = fixture(), log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const view = f.fullscreen.element() + const detach = f.attach(rx) + await f.bridge.requestFullscreen(rx, view) + const detachOther = f.attach(other) + await detachOther() + expect(document.fullscreenElement).toBe(view) + await detach() + expect(document.fullscreenElement).toBeNull() + const detachAgain = f.attach(rx) + await f.bridge.requestFullscreen(rx, view) + f.fullscreen.exit.mockRejectedValueOnce(new TypeError('exit refused')) + await detachAgain() + expect(log).toHaveBeenCalledWith('Native channel fullscreen exit failed', expect.objectContaining({ message: 'exit refused' })) + f.fullscreen.exit.mockRejectedValueOnce(new TypeError('exit refused')) + f.bridge.dispose() + await vi.waitFor(() => { expect(log).toHaveBeenCalledTimes(2) }) + const idle = fixture() + idle.bridge.dispose() + expect(idle.fullscreen.exit).not.toHaveBeenCalled() +}) + +test('a failed bridge leaves the holder\'s fullscreen after its pending entry and refuses later requests', async () => { + const f = fixture(), log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const view = f.fullscreen.element() + const entering = Promise.withResolvers() + view.requestFullscreen.mockImplementationOnce(async () => { await entering.promise; f.fullscreen.change(view) }) + const entry = f.bridge.requestFullscreen(rx, view) + f.bridge.fail('events failed') + expect(f.fullscreen.exit).not.toHaveBeenCalled() + entering.resolve(undefined) + await entry + await vi.waitFor(() => { expect(f.fullscreen.exit).toHaveBeenCalledOnce() }) + expect(document.fullscreenElement).toBeNull() + await expect(f.bridge.requestFullscreen(rx, view)).rejects.toThrow('events failed') + expect(view.requestFullscreen).toHaveBeenCalledOnce() + // A refused exit is logged; the failed bridge holds no fullscreen afterwards. + const refused = fixture(), shown = refused.fullscreen.element() + await refused.bridge.requestFullscreen(rx, shown) + refused.fullscreen.exit.mockRejectedValueOnce(new TypeError('exit refused')) + refused.bridge.fail('events failed') + await vi.waitFor(() => { expect(log).toHaveBeenCalledWith('Native channel fullscreen exit failed', expect.objectContaining({ message: 'exit refused' })) }) + await refused.bridge.exitFullscreen(rx) + expect(refused.fullscreen.exit).toHaveBeenCalledOnce() +}) diff --git a/packages/experimental/frame-forwarding/tsconfig.client.json b/packages/experimental/frame-forwarding/tsconfig.client.json new file mode 100644 index 0000000000..7a57966dc5 --- /dev/null +++ b/packages/experimental/frame-forwarding/tsconfig.client.json @@ -0,0 +1,32 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo" + }, + "include": [ + "src/client", + "src/types.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../shared-texture/shared-texture/tsconfig.client.json" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../util/values" + } + ] +} diff --git a/packages/experimental/frame-forwarding/tsconfig.host.json b/packages/experimental/frame-forwarding/tsconfig.host.json new file mode 100644 index 0000000000..109c0a60ca --- /dev/null +++ b/packages/experimental/frame-forwarding/tsconfig.host.json @@ -0,0 +1,34 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo" + }, + "include": [ + "src/index.ts", + "src/config.ts", + "src/host", + "src/types.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../util/values" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../../shared-texture/shared-texture/tsconfig.host.json" + } + ] +} diff --git a/packages/experimental/frame-forwarding/tsconfig.json b/packages/experimental/frame-forwarding/tsconfig.json new file mode 100644 index 0000000000..50e319b64e --- /dev/null +++ b/packages/experimental/frame-forwarding/tsconfig.json @@ -0,0 +1,11 @@ +{ + "files": [], + "references": [ + { + "path": "tsconfig.host.json" + }, + { + "path": "tsconfig.client.json" + } + ] +} diff --git a/packages/experimental/frame-forwarding/tsdown.config.ts b/packages/experimental/frame-forwarding/tsdown.config.ts new file mode 100644 index 0000000000..e7db6146dc --- /dev/null +++ b/packages/experimental/frame-forwarding/tsdown.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'tsdown' +import { clientBundle } from '../../client/tsdown.client.ts' + +const bundle = clientBundle(import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }) +export default defineConfig(options => bundle(options).map(config => config.platform === 'browser' ? { + ...config, + inputOptions: { ...config.inputOptions, resolve: { ...config.inputOptions?.resolve, mainFields: ['browser', 'module', 'main'] } }, +} : config)) diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md index 4f5ce16f31..1a083a12f0 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md @@ -259,6 +259,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo | `@deepseek-ai/dsh-experimental-translator` | yes | Machine translation with reusable Session results | | `@deepseek-ai/dsh-experimental-worktree` | yes | Creates a named Git worktree and changes the calling Session working directory | | `@deepseek-ai/dsh-forge-gitlab` | yes | GitLab provider for the experimental forge registry, read and written through the GitLab CLI on the host | +| `@deepseek-ai/dsh-frame-forwarding` | yes | Experimental native frame forwarding: transferable channels whose producer processes present frames through Desktop shared textures | | `@deepseek-ai/dsh-hooks-claude-code` | yes | Bridge plugin: run a Claude Code hooks.json / settings hook config on the DeepSeek Harness interception seams | | `@deepseek-ai/dsh-hooks-codex` | yes | Bridge plugin: run a Codex hooks.json hook config on the DeepSeek Harness interception seams | | `@deepseek-ai/dsh-im` | yes | Platform-neutral IM host: intake, message store, im/message waterfall, hosted sessions, send funnel and output renderers | diff --git a/packages/shared-texture/shared-texture/README.i18n.yaml b/packages/shared-texture/shared-texture/README.i18n.yaml index db93f0048d..d78a89d722 100644 --- a/packages/shared-texture/shared-texture/README.i18n.yaml +++ b/packages/shared-texture/shared-texture/README.i18n.yaml @@ -18,8 +18,8 @@ en: bbff250eba0f1b89 zh: b20a47f82d8ab6e0 /deepseek-ai-dsh-shared-texture/use-this-package/host-service-deepseek-ai-dsh-shared-texture: - en: 84dba03e7be89b8d - zh: 5bc384b906539a40 + en: 5d61a7959554dcf3 + zh: 50eb7b56eaae1d44 /deepseek-ai-dsh-shared-texture/use-this-package/client-plugin-deepseek-ai-dsh-shared-texture-client: en: 4bbc5bbf7e542e56 zh: 6248dc219b321843 diff --git a/packages/shared-texture/shared-texture/README.md b/packages/shared-texture/shared-texture/README.md index d37cd62ecd..b5fbec37de 100644 --- a/packages/shared-texture/shared-texture/README.md +++ b/packages/shared-texture/shared-texture/README.md @@ -27,7 +27,7 @@ Use `@deepseek-ai/dsh-shared-texture` to present or receive shared GPU-backed fr ### Host service (`@deepseek-ai/dsh-shared-texture`) -A presentation host subclasses `SharedTexture`, implements `claim(): SharedTextureClaim`, and owns exclusive-claim concurrency control and native transport; Desktop Host is the provider. Consumers read `ctx.get('sharedTexture')`, which is absent in Hosts that do not present shared textures, and call `claim()` to obtain `capabilities(timeoutMs)`, `nativeSink(timeoutMs)`, `adapterLuid(timeoutMs)`, and `release()`. The Host entry's `apply` does nothing, because the Loader mounts the package only to deliver its Client half. +A presentation host subclasses `SharedTexture`, implements `claim(): SharedTextureClaim`, and owns exclusive-claim concurrency control and native transport; Desktop Host is the provider. Consumers read `ctx.get('sharedTexture')`, which is absent in Hosts that do not present shared textures, and call `claim()` to obtain `capabilities(timeoutMs)`, `nativeSink(timeoutMs)`, `adapterLuid(timeoutMs)`, and `release()`. The Host entry's `apply` does nothing, because the Loader mounts the package only to deliver its Client half. Desktop Host provides the absolute path of the preinstalled receiver as `desktopFrameReceiver.path`. ### Client plugin (`@deepseek-ai/dsh-shared-texture/client`) diff --git a/packages/shared-texture/shared-texture/README.zh.md b/packages/shared-texture/shared-texture/README.zh.md index fddcf2c495..5c57b9aafa 100644 --- a/packages/shared-texture/shared-texture/README.zh.md +++ b/packages/shared-texture/shared-texture/README.zh.md @@ -27,7 +27,7 @@ kind: "package-reference" ### Host 服务(`@deepseek-ai/dsh-shared-texture`) -呈现宿主继承 `SharedTexture` 并实现 `claim(): SharedTextureClaim`,自行负责独占认领的并发控制与原生传输;目前的提供方是 Desktop Host。消费方通过 `ctx.get('sharedTexture')` 读取服务(不呈现共享纹理的 Host 中没有这个服务),再调用 `claim()` 获取 `capabilities(timeoutMs)`、`nativeSink(timeoutMs)`、`adapterLuid(timeoutMs)` 与 `release()`。Host 入口的 `apply` 什么也不做,因为 Loader 挂载本包只是为了送出它的 Client 半边。 +呈现宿主继承 `SharedTexture` 并实现 `claim(): SharedTextureClaim`,自行负责独占认领的并发控制与原生传输;目前的提供方是 Desktop Host。消费方通过 `ctx.get('sharedTexture')` 读取服务(不呈现共享纹理的 Host 中没有这个服务),再调用 `claim()` 获取 `capabilities(timeoutMs)`、`nativeSink(timeoutMs)`、`adapterLuid(timeoutMs)` 与 `release()`。Host 入口的 `apply` 什么也不做,因为 Loader 挂载本包只是为了送出它的 Client 半边。Desktop Host 通过 `desktopFrameReceiver.path` 提供预装接收器的绝对路径。 ### Client 插件(`@deepseek-ai/dsh-shared-texture/client`) diff --git a/packages/shared-texture/shared-texture/src/index.ts b/packages/shared-texture/shared-texture/src/index.ts index 689a52bcbd..daa1a19016 100644 --- a/packages/shared-texture/shared-texture/src/index.ts +++ b/packages/shared-texture/shared-texture/src/index.ts @@ -71,6 +71,8 @@ export interface SharedTextureClaim extends SharedTextureService { declare module '@deepseek-ai/cordis' { interface Context { + /** Absolute path to the receiver addon preinstalled by Desktop for this Host. */ + desktopFrameReceiver: { readonly path: string } /** * Host shared-texture service; absent in Hosts that do not present shared textures, so read it with * `ctx.get('sharedTexture')`. One consumer holds a claim at a time. diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bfc297f736..d1425da2b7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -12234,6 +12234,40 @@ importers: specifier: workspace:* version: link:../../session/working-directory + packages/experimental/frame-forwarding: + dependencies: + '@deepseek-ai/dsh-brand': + specifier: workspace:* + version: link:../../util/brand + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol + '@deepseek-ai/dsh-util-values': + specifier: workspace:* + version: link:../../util/values + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery + zod: + specifier: 4.6.6 + version: 4.6.6 + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-api-remotes': + specifier: workspace:* + version: link:../../api/remotes + '@deepseek-ai/dsh-shared-texture': + specifier: workspace:* + version: link:../../shared-texture/shared-texture + '@deepseek-ai/libreoffice-kit': + specifier: 0.2.3 + version: 0.2.3 + node-api-headers: + specifier: 1.9.0 + version: 1.9.0 + packages/experimental/hook-protocol: devDependencies: '@deepseek-ai/cordis': @@ -22898,12 +22932,24 @@ packages: resolution: {integrity: sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==} engines: {node: '>=20.19.0'} + '@deepseek-ai/libreoffice-kit-darwin-arm64@0.2.3': + resolution: {integrity: sha512-0dfiEQR6SqAQjh9hxyY8x77Sj3r+AGC+Xn2A/zF+bag9g40leYPL/c2UirSqYR6xUwE9a/5YgWFIHjw1eOh+3A==} + engines: {node: '>=22.19.0'} + cpu: [arm64] + os: [darwin] + '@deepseek-ai/libreoffice-kit-darwin-arm64@0.2.4': resolution: {integrity: sha512-j7ubpGbUrLvQailTkV4c4mwuMweStBsqW//BkIfD65ytW2rLrfRGhzHIO2wcg9Vq4kB+xv2VgQATc+mOVO0DjQ==} engines: {node: '>=22.19.0'} cpu: [arm64] os: [darwin] + '@deepseek-ai/libreoffice-kit-darwin-x64@0.2.3': + resolution: {integrity: sha512-vq0Fp7MTlZwV/yxLpmvQmx1uiiozLTjjODmgrOa9WC5WhrSQYZ+M1OiQKI0qbPAjpMZVBzcZvxlAGnDiTrG4jA==} + engines: {node: '>=22.19.0'} + cpu: [x64] + os: [darwin] + '@deepseek-ai/libreoffice-kit-darwin-x64@0.2.4': resolution: {integrity: sha512-MR82Kj/1Pb8C98kDRM8CX+5aHvdo07ocupQV1rWlNA/b7UdO97nEy03wc267dCnLoH2G4lNmw5O6hRzphQ7kzw==} engines: {node: '>=22.19.0'} @@ -22924,18 +22970,39 @@ packages: os: [linux] libc: [glibc] + '@deepseek-ai/libreoffice-kit-wasm@0.2.3': + resolution: {integrity: sha512-g81zHATxolq/HKRglfrSO2gQgj4RZ//nJo98BcTIs9l8GPU4STNcWwplx5CE6Iy/20lZFbwT9jvGw1Key9xZmg==} + engines: {node: '>=22.19.0'} + + '@deepseek-ai/libreoffice-kit-win32-arm64@0.2.3': + resolution: {integrity: sha512-cAQ0hRZ/8jt8Dudn7vYdpd5OeWpg0AOHzXqgn6UkkPXmQt1/+HCdc4MZbAM927I+c3lwJyLN1fyKIMW5iXCYpg==} + engines: {node: '>=22.19.0'} + cpu: [arm64] + os: [win32] + '@deepseek-ai/libreoffice-kit-win32-arm64@0.2.4': resolution: {integrity: sha512-VfUkoflQSSHfEXPOYy1+6rYBITBoOXkR7E9wFvT7K1a0TknJhAaJfCmqRD+AeTN6Lz+AhzVZP2hfq7QCF9ZeCA==} engines: {node: '>=22.19.0'} cpu: [arm64] os: [win32] + '@deepseek-ai/libreoffice-kit-win32-x64@0.2.3': + resolution: {integrity: sha512-GMW+m/09Ts0m4gRUjIckeRN48OVYgJI7aLG1uoUHcG3LRPDsKnsyeRo+BSQn8rh4CmWtJg5c6qtl0uSW7b9zEg==} + engines: {node: '>=22.19.0'} + cpu: [x64] + os: [win32] + '@deepseek-ai/libreoffice-kit-win32-x64@0.2.4': resolution: {integrity: sha512-EbiIjU6pJGO+q2AlVved985IenoPCkIzcM8850nmxarq3BuY8TBAIVUaHlP1cypaQd+mJ3H8gTvANF6Wdptwpg==} engines: {node: '>=22.19.0'} cpu: [x64] os: [win32] + '@deepseek-ai/libreoffice-kit@0.2.3': + resolution: {integrity: sha512-MbpucYPrZpeec/smy7u8Z066JeQU6lMVK6A1oysUv1R/OATDvtlVmrsIlfcIz6bVbfJVpgregIK86dOdat9qdA==} + engines: {node: '>=22.19.0'} + hasBin: true + '@deepseek-ai/libreoffice-kit@0.2.4': resolution: {integrity: sha512-M2K0fTAKcyM8rGW9iMnZsbuQoHeVtAEwKhrDN1TppOlAufBO9BJte8egddEKHEir4CjwN7Cakpy8p7zSov3dlQ==} engines: {node: '>=22.19.0'} @@ -30946,9 +31013,15 @@ snapshots: '@csstools/css-tokenizer@4.0.0': {} + '@deepseek-ai/libreoffice-kit-darwin-arm64@0.2.3': + optional: true + '@deepseek-ai/libreoffice-kit-darwin-arm64@0.2.4': optional: true + '@deepseek-ai/libreoffice-kit-darwin-x64@0.2.3': + optional: true + '@deepseek-ai/libreoffice-kit-darwin-x64@0.2.4': optional: true @@ -30958,12 +31031,34 @@ snapshots: '@deepseek-ai/libreoffice-kit-linux-x64-glibc@0.2.4': optional: true + '@deepseek-ai/libreoffice-kit-wasm@0.2.3': + optional: true + + '@deepseek-ai/libreoffice-kit-win32-arm64@0.2.3': + optional: true + '@deepseek-ai/libreoffice-kit-win32-arm64@0.2.4': optional: true + '@deepseek-ai/libreoffice-kit-win32-x64@0.2.3': + optional: true + '@deepseek-ai/libreoffice-kit-win32-x64@0.2.4': optional: true + '@deepseek-ai/libreoffice-kit@0.2.3': + dependencies: + fflate: 0.8.2 + fontkit: 2.0.4 + saxes: 6.0.0 + optionalDependencies: + '@deepseek-ai/libreoffice-kit-darwin-arm64': 0.2.3 + '@deepseek-ai/libreoffice-kit-darwin-x64': 0.2.3 + '@deepseek-ai/libreoffice-kit-wasm': 0.2.3 + '@deepseek-ai/libreoffice-kit-win32-arm64': 0.2.3 + '@deepseek-ai/libreoffice-kit-win32-x64': 0.2.3 + koffi: 3.1.1 + '@deepseek-ai/libreoffice-kit@0.2.4': dependencies: fflate: 0.8.2 diff --git a/scripts/experimental-package-policy.ts b/scripts/experimental-package-policy.ts index 436cfb5d39..68690cfb42 100644 --- a/scripts/experimental-package-policy.ts +++ b/scripts/experimental-package-policy.ts @@ -16,6 +16,7 @@ export const EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS: Readonly = { * or names itself here. Client-face keys (the projection analyzes the host * face only) name the package README that owns their surface. * - * Two categories remain, and neither is a projection gap a scanning rule could + * Three categories remain, and none is a projection gap a scanning rule could * close. An OPTIONAL key (`key?: X`) is a value the launcher or boot code * installs before the tree mounts, which the analyzer skips by rule because no * plugin provides it and `inject` cannot reach it. A client-face key belongs to * the browser Context, which this host-face program never sees; the browser * surface has its own generated catalog (`scripts/gen-client-catalog.ts`, served - * to a model as `cordis_runtime_inspect what:"client"`). + * to a model as `cordis_runtime_inspect what:"client"`). An experimental + * service whose package README is its only documentation until it stabilizes + * declares its key outside the package's top-level modules, so neither a + * subsystems page nor the model-visible runtime catalog publishes it. */ export const SERVICE_WALK_EXEMPTIONS: Record = { + desktopFrameReceiver: 'internal Desktop receiver for the experimental frame-forwarding plugin — packages/experimental/frame-forwarding/README.md owns its availability and lifecycle', timeline: 'experimental session data service internal to the bundle — packages/experimental/timeline/README.md owns its behavior', contextMenus: 'client-side interface-typed menu registry — packages/client/ui-context-menu/README.md owns the API', fileActions: 'client-side interface-typed file actions — packages/client/ui-file-actions/README.md owns the API', @@ -247,6 +251,7 @@ export const SERVICE_WALK_EXEMPTIONS: Record = { sidebarRightTabs: 'client-side right-Sidebar tab-type registry — packages/client/ui-sidebar-right/README.md owns the API', forgeChanges: 'client-side changes view face for other plugins — docs/subsystems/forge.md#extension-api owns the API', documentPreviews: 'client-side document renderer registry — docs/subsystems/sidebar-right.md owns the API', + frameForwarding: 'experimental Desktop service whose package README is its only documentation until it stabilizes — packages/experimental/frame-forwarding/README.md owns the API', } /** diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 283197399d..f4d8fc215d 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -331,6 +331,7 @@ const SERVICE_ROLES: ServiceRole[] = [ pkg: 'shared-texture', title: 'Shared-texture presentation', mode: 'seam', + consumers: ['frame-forwarding'], note: 'Desktop Host implements the exclusive Host claim that submits GPU-backed frames to Desktop; the Client half of the package provides the Desktop preload bridge as the Client service. Consumers never touch Mach ports, Win32 handles, or Electron.', }, { diff --git a/scripts/release/families.spec.ts b/scripts/release/families.spec.ts index 2d7d992498..4cafe79500 100644 --- a/scripts/release/families.spec.ts +++ b/scripts/release/families.spec.ts @@ -83,6 +83,7 @@ describe('release families', () => { '@deepseek-ai/dsh-forge-gitlab', '@deepseek-ai/dsh-experimental-forge-session', '@deepseek-ai/dsh-experimental-forge', + '@deepseek-ai/dsh-frame-forwarding', '@deepseek-ai/dsh-hook-protocol', '@deepseek-ai/dsh-hooks-claude-code', '@deepseek-ai/dsh-hooks-codex', diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index 6ddbf625a7..a2a5624588 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -60,6 +60,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/client/ui-file-actions': { kind: 'none', reason: 'Explicit user file saves and clipboard operations add no model input.' }, 'packages/client/ui-entry-customization': { kind: 'none', reason: 'Controls browser launchers and prepares a reviewable Creator draft without submitting model input.' }, 'packages/experimental/client-ui-cot-translation': { kind: 'indirect', reason: 'The translator owns optional paid queries; normal Session activation delegates startup context to the preset.' }, + 'packages/experimental/frame-forwarding': { kind: 'none', reason: 'Native frame transport between Host plugins and the Desktop renderer; it contributes no model context or Session events.' }, 'packages/experimental/cot-translation-bundle': { kind: 'indirect', reason: 'The GUI consumer delegates paid query prompts to the translator and normal activation context to the Session preset.' }, 'packages/client/product-analytics': { kind: 'none', reason: 'Desktop analytics observes selected interactions without contributing model context or Session events.' }, 'packages/experimental/speech-to-text': { kind: 'none', reason: 'Routes transient recognition without adding model requests or Session events.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index 80729488a2..336da56173 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -82,6 +82,9 @@ "@deepseek-ai/dsh-client-product-analytics": ["./packages/client/product-analytics/src/index.ts"], "@deepseek-ai/dsh-client-product-analytics/types": ["./packages/client/product-analytics/src/events.ts"], "@deepseek-ai/dsh-client-product-analytics/client": ["./packages/client/product-analytics/src/client/index.ts"], + "@deepseek-ai/dsh-frame-forwarding": ["./packages/experimental/frame-forwarding/src/index.ts"], + "@deepseek-ai/dsh-frame-forwarding/client": ["./packages/experimental/frame-forwarding/src/client/index.ts"], + "@deepseek-ai/dsh-frame-forwarding/types": ["./packages/experimental/frame-forwarding/src/types.ts"], "@deepseek-ai/dsh-otel": ["./packages/telemetry/otel/src"], "@deepseek-ai/dsh-client-ui-account-notifications": ["./packages/client/ui-account-notifications/src/index.ts"], "@deepseek-ai/dsh-client-ui-account-notifications/client": ["./packages/client/ui-account-notifications/src/client/index.ts"], diff --git a/tsconfig.client.json b/tsconfig.client.json index 168fde3a44..e01310cbbd 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -66,6 +66,7 @@ { "path": "./packages/experimental/client-ui-cot-translation/tsconfig.client.json" }, { "path": "./packages/client/product-analytics/tsconfig.client.json" }, { "path": "./packages/shared-texture/shared-texture/tsconfig.client.json" }, + { "path": "./packages/experimental/frame-forwarding/tsconfig.client.json" }, { "path": "./apps/desktop/tsconfig.client.json" }, { "path": "./packages/util/atomic-write" }, { "path": "./packages/experimental/client-ui-voice-input" }, diff --git a/tsconfig.host.json b/tsconfig.host.json index e3099e7468..ce2f962f9e 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -358,6 +358,7 @@ { "path": "./packages/experimental/session-titles-bundle" }, { "path": "./packages/experimental/translator" }, { "path": "./packages/client/product-analytics/tsconfig.host.json" }, + { "path": "./packages/experimental/frame-forwarding/tsconfig.host.json" }, { "path": "./packages/telemetry/otel" }, { "path": "./packages/experimental/speech-to-text" }, { "path": "./packages/experimental/speech-to-text-sensevoice" }, diff --git a/vitest.config.ts b/vitest.config.ts index 658369380f..650b955f49 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -402,6 +402,8 @@ export default defineConfig({ // The forge panel entry imports its generated Remote contribution, which exists only in lib; // forge-panel.e2e.ts exercises the built entry, while source tests cover mountForgePanel. 'packages/experimental/client-ui-forge/src/client/index.ts', + // The frame-forwarding entry imports its generated Remote contribution the same way; source tests cover mountFrameForwarding. + 'packages/experimental/frame-forwarding/src/client/index.ts', // Slash/command/input round: per-file gaps deferred with the same // client-lane debt. TODO(gui): cover and remove with the lane above. 'packages/client/ui-commands/src/index.ts',