mirror of
https://ghproxy.cflmy.top/https://github.com/deepseek-ai/deepseek-harness.git
synced 2026-11-29 08:39:35 +08:00
feat(frame-forwarding): video-frame forwarding support (#8440)
* fix(desktop): hide the Windows menu entries while the document is fullscreen Frame forwarding offers plugins the Fullscreen API; the Application and Edit caption entries now stay hidden during fullscreen and return when it ends. * feat(desktop): build declared native addons for development and packaging * feat(frame-forwarding): receive native frames and submit them to the Desktop sink * feat(frame-forwarding): route Host channels to video mounts in the Client Keep the producer interface internal while Office integration evolves. Include channel lifecycle, receiver integration and video presentation tests. Co-authored-by: imccyu <276526105+imccyu@users.noreply.github.com> * test(frame-forwarding): cover wire packet and endpoint parsing with fuzz tests * refactor(desktop): preinstall the native frame receiver * build(desktop): compile the preinstalled receiver from the plugin workspace * refactor(frame-forwarding): load the preinstalled receiver inside the plugin * refactor(desktop): pass the frame receiver path as a Host argument --------- Co-authored-by: imccyu <276526105+imccyu@users.noreply.github.com>
This commit is contained in:
1 parent
dad92aacba
commit
f7cb4926dc
142 files changed
+15484
-63
No files matched your search
+37
@@ -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
|
||||
@@ -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 `<HighPart>:<LowPart>` 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 delivLine truncated
|
||||
|
||||
## 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.
|
||||
@@ -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 停止,并发查询共用一次读取,失败的读取不保留。答案是小写十六进制的 `<HighPart>:<LowPart>`,与帧转发接收器表示 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 已构建时经 DesktoLine truncated
|
||||
|
||||
## 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 通过自己的引擎接入。
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -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 会换页而不是失败。
|
||||
@@ -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<void> {
|
||||
}
|
||||
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<void> {
|
||||
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<void> {
|
||||
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 })
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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 提供,选中的只读文本提供“复制”命令。
|
||||
|
||||
|
||||
@@ -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/<platform>-<arch>/`.
|
||||
* 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/<platform>-<arch>/`.
|
||||
* 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'))
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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`,即可同时覆盖原生解压路径及其失败报告。从仓库根目录运行以下命令。它验证 目录替换与回滚和两种文件占用替换方式;不属于单元测试通道。
|
||||
|
||||
@@ -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<void> {
|
||||
const packageManager = process.env.npm_execpath
|
||||
if (packageManager === undefined || packageManager === '') {
|
||||
@@ -99,6 +109,12 @@ async function main(): Promise<void> {
|
||||
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'),
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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<string, string>
|
||||
/** 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<NativePackageBuild, 'name' | 'root' | 'build'>, 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
|
||||
@@ -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 <build> --arch <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: ["<relative>.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}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<void> {
|
||||
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))
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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<DesktopHostReady> {
|
||||
async start(frameReceiverPath?: string): Promise<DesktopHostReady> {
|
||||
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),
|
||||
|
||||
@@ -539,6 +539,8 @@ async function main(): Promise<void> {
|
||||
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<void> {
|
||||
}, [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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -19,12 +19,16 @@ vi.mock('node:child_process', async (importOriginal) => {
|
||||
vi.mock('node:fs', async importOriginal => ({
|
||||
...await importOriginal<typeof import('node:fs')>(),
|
||||
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'],
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 <tx> 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 <tx> 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, `<ms since start> <word> <details>`. With signal=PREFIX, each word also
|
||||
// creates the empty file PREFIX.<word>, so a test whose JavaScript thread is blocked can still observe progress.
|
||||
#include "fixture-client.h"
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#if defined(_WIN32)
|
||||
#include <windows.h>
|
||||
#include <d3d11.h>
|
||||
#endif
|
||||
|
||||
static const auto started = std::chrono::steady_clock::now();
|
||||
static std::map<std::string, std::string> options;
|
||||
static long long elapsed() {
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(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<dsh_frame_forwarding_event>();
|
||||
const auto submit_frames = [&] {
|
||||
std::vector<uint32_t> 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<uint64_t>(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<long>(json.size()) - 2;
|
||||
if (pad > 0) json.append(static_cast<size_t>(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;
|
||||
}
|
||||
@@ -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 <node_api.h>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#include "shared-texture-sink.h"
|
||||
#if defined(_WIN32)
|
||||
#define NOMINMAX
|
||||
#include <d3d11.h>
|
||||
#include <dxgi.h>
|
||||
#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<int> refs{1}, retains{0}, releases{0};
|
||||
std::mutex mutex;
|
||||
std::vector<Presented> presented;
|
||||
/** Requests that have not settled, by identifier. */
|
||||
std::map<std::string, dsh_shared_texture_callbacks_v2> 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<FakeSink*>(data);
|
||||
}
|
||||
|
||||
void retain(void* ctx) {
|
||||
auto fake = static_cast<FakeSink*>(ctx);
|
||||
fake->retains++; fake->refs++;
|
||||
}
|
||||
void release(void* ctx) {
|
||||
auto fake = static_cast<FakeSink*>(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<FakeSink*>(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<std::mutex> 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<dsh_shared_texture_sink_v2*>(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<std::mutex> 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<uint32_t>(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<std::mutex> 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<std::mutex> 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<std::mutex> 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<void**>(&dxgi))) && SUCCEEDED(dxgi->GetAdapter(&adapter))
|
||||
&& SUCCEEDED(adapter->GetDesc(&desc))) {
|
||||
std::ostringstream id;
|
||||
id << std::hex << static_cast<uint32_t>(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)
|
||||
@@ -0,0 +1,309 @@
|
||||
#include "transport.h"
|
||||
#include "fixture-client.h"
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
#include <limits>
|
||||
#include <chrono>
|
||||
#if defined(__APPLE__)
|
||||
#include <CoreFoundation/CoreFoundation.h>
|
||||
#include <IOSurface/IOSurface.h>
|
||||
#include <unistd.h>
|
||||
#else
|
||||
#define NOMINMAX
|
||||
#include <windows.h>
|
||||
#include <d3d11_1.h>
|
||||
#include <dxgi1_2.h>
|
||||
#include <wrl/client.h>
|
||||
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<ID3D11Texture2D> texture;
|
||||
ComPtr<IDXGIKeyedMutex> keyed_mutex;
|
||||
HANDLE handle = nullptr;
|
||||
~dsh_frame_forwarding_surface() { if (handle) CloseHandle(handle); }
|
||||
#endif
|
||||
};
|
||||
struct dsh_frame_forwarding_client {
|
||||
std::unique_ptr<Channel> channel;
|
||||
std::mutex pool_mutex;
|
||||
std::vector<std::unique_ptr<dsh_frame_forwarding_surface>> surfaces;
|
||||
uint32_t max_frames = 0;
|
||||
uint64_t max_bytes = 0, next_allocation = 1;
|
||||
std::string error;
|
||||
std::atomic<bool> stopped{false};
|
||||
#if defined(_WIN32)
|
||||
ComPtr<ID3D11Device> device;
|
||||
ComPtr<ID3D11DeviceContext> 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<uintptr_t>(surface->surface);
|
||||
#else
|
||||
auto resource = reinterpret_cast<uintptr_t>(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<dsh_frame_forwarding_client>();
|
||||
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<bool()>(cancelled) : std::function<bool()>{});
|
||||
Packet packet; packet.kind = hello; std::strcpy(packet.token, endpoint.token.c_str());
|
||||
#if defined(_WIN32)
|
||||
if (device) {
|
||||
client->device = static_cast<ID3D11Device*>(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<std::mutex> 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<size_t>(width) * 4);
|
||||
uint64_t required_bytes = IOSurfaceAlignProperty(kIOSurfaceAllocSize, row_bytes * height);
|
||||
const uint64_t page_bytes = static_cast<uint64_t>(getpagesize());
|
||||
required_bytes = (required_bytes + page_bytes - 1) / page_bytes * page_bytes;
|
||||
#else
|
||||
uint64_t required_bytes = static_cast<uint64_t>(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<dsh_frame_forwarding_surface>();
|
||||
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<uint32_t>(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<IDXGIResource1> 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<uint64_t>(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<size_t>(surface->width) * 4 || stride > UINT32_MAX) return 0;
|
||||
auto client = surface->owner; std::lock_guard<std::mutex> 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<unsigned char*>(IOSurfaceGetBaseAddress(surface->surface));
|
||||
for (uint32_t row = 0; row < surface->height; ++row)
|
||||
std::memcpy(target + static_cast<size_t>(row) * surface->stride, static_cast<const unsigned char*>(pixels) + static_cast<size_t>(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<UINT>(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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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;
|
||||
}
|
||||
@@ -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);
|
||||
@@ -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 <node_api.h>
|
||||
#include <mach/mach.h>
|
||||
#include <cstdint>
|
||||
|
||||
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<vm_address_t>(names), name_count * sizeof(mach_port_name_t));
|
||||
vm_deallocate(mach_task_self(), reinterpret_cast<vm_address_t>(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<double>(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;
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
/** Test-only hostile peer. Uses the receiver transport, deliberately bypassing the producer API's validation. */
|
||||
#include "transport.h"
|
||||
#include <CoreFoundation/CoreFoundation.h>
|
||||
#include <IOSurface/IOSurface.h>
|
||||
#include <mach/mach.h>
|
||||
#include <mach/notify.h>
|
||||
#include <servers/bootstrap.h>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <chrono>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
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<uintptr_t>(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<unsigned long long>(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<uint32_t>(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<mach_msg_size_t>(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<IOSurfaceRef> 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<unsigned long long>(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<unsigned long long>(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<unsigned long long>(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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
#include "fixture-client.h"
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
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 <metadata>` submits its metadata and reports `{"submitted":<frame>}` 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<uint32_t> 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;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// Test-only reader of one BGRA pixel from a Host-local IOSurfaceRef handle delivered by the receiver.
|
||||
#include <IOSurface/IOSurface.h>
|
||||
#include <node_api.h>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
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<IOSurfaceRef>(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<const uint8_t*>(IOSurfaceGetBaseAddress(surface)) + static_cast<size_t>(y) * IOSurfaceGetBytesPerRow(surface);
|
||||
uint32_t bgra;
|
||||
std::memcpy(&bgra, row + static_cast<size_t>(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;
|
||||
}
|
||||
@@ -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
|
||||
@@ -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\|<pid>\|<token>\|<name>` 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 `<work>/artifacts-<target>/`. Minimize it with:
|
||||
|
||||
```
|
||||
<work>/<target>-fuzzer -minimize_crash=1 -timeout=10 -rss_limit_mb=2048 <work>/artifacts-<target>/crash-<hash>
|
||||
```
|
||||
@@ -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\|<pid>\|<token>\|<name>` 形式解析回来;被接受的连接标识符不超过 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-*` 的名字写入 `<work>/artifacts-<target>/`。用下面的命令把它最小化:
|
||||
|
||||
```
|
||||
<work>/<target>-fuzzer -minimize_crash=1 -timeout=10 -rss_limit_mb=2048 <work>/artifacts-<target>/crash-<hash>
|
||||
```
|
||||
@@ -0,0 +1,186 @@
|
||||
/**
|
||||
* Write the seed corpus of the frame-forwarding wire parser with the production encoder.
|
||||
*
|
||||
* Usage: `corpus-gen <output directory> [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 <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#if defined(_WIN32)
|
||||
#include <direct.h>
|
||||
#else
|
||||
#include <sys/stat.h>
|
||||
#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<size_t>(text_size) + 3u) & ~size_t{3} : text_size;
|
||||
std::vector<char> 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 <output directory> [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;
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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|<pid>|<token>|<name>` 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 <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <exception>
|
||||
#include <string>
|
||||
|
||||
#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<const char*>(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<unsigned long long>(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;
|
||||
}
|
||||
@@ -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 <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
#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<const char*>(std::memchr(left.text, 0, sizeof(left.text)));
|
||||
const auto* right_end = static_cast<const char*>(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<size_t>(left_end - left.text), right_size = static_cast<size_t>(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<size_t>(text_size) + 3u) & ~size_t{3} : text_size;
|
||||
std::vector<char> 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<const char*>(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;
|
||||
}
|
||||
+92
@@ -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 <snapshot native directory> --work <work directory> [--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
|
||||
@@ -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 <installation>\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" }
|
||||
}
|
||||
}
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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; }')
|
||||
})
|
||||
@@ -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<string> }
|
||||
invoke.mockResolvedValueOnce('platform=darwin; memory_gib=32.0')
|
||||
await expect(product.deviceInfo()).resolves.toBe('platform=darwin; memory_gib=32.0')
|
||||
|
||||
@@ -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<Record<'hop' | 'ingress', Buffer>> = {}) {
|
||||
async function fixture(name: typeof targets[number] = 'darwin-arm64', binaries: Partial<Record<'shared-texture-hop' | 'shared-texture-ingress' | 'frame-forwarding', Buffer>> = {}) {
|
||||
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<string, { platform: string; sha256: string }> = {}
|
||||
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}`)
|
||||
})
|
||||
})
|
||||
@@ -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',
|
||||
|
||||
@@ -6,5 +6,5 @@
|
||||
en: 41d772192075e133
|
||||
zh: 5ef3da69b4de1d8a
|
||||
/capability-seams-and-core-services:
|
||||
en: ae2e3f6a59a9a7ee
|
||||
zh: 9fcde04bb95424f4
|
||||
en: 20d2bcc6ee1ea353
|
||||
zh: daa830e26d32c640
|
||||
@@ -98,6 +98,7 @@ flowchart LR
|
||||
pkg_cua_mcp["cua-mcp"]
|
||||
pkg_shared_texture["shared-texture"]
|
||||
svc_sharedTexture["ctx.sharedTexture<br/>Shared-texture presentation"]
|
||||
pkg_frame_forwarding["frame-forwarding"]
|
||||
pkg_office_kit["office-kit"]
|
||||
svc_officeKit["ctx.officeKit<br/>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. |
|
||||
|
||||
@@ -100,6 +100,7 @@ flowchart LR
|
||||
pkg_cua_mcp["cua-mcp"]
|
||||
pkg_shared_texture["shared-texture"]
|
||||
svc_sharedTexture["ctx.sharedTexture<br/>Shared-texture presentation"]
|
||||
pkg_frame_forwarding["frame-forwarding"]
|
||||
pkg_office_kit["office-kit"]
|
||||
svc_officeKit["ctx.officeKit<br/>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 将回执绑定到已接受的提交。 |
|
||||
|
||||
@@ -1989,6 +1989,43 @@ export interface Config {
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-forge-gitlab -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-frame-forwarding -->
|
||||
<a id="deepseek-aidsh-frame-forwarding"></a>
|
||||
|
||||
## `@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
|
||||
}
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-frame-forwarding -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-fs-local -->
|
||||
<a id="deepseek-aidsh-fs-local"></a>
|
||||
|
||||
|
||||
@@ -1991,6 +1991,43 @@ export interface Config {
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-forge-gitlab -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-frame-forwarding -->
|
||||
<a id="deepseek-aidsh-frame-forwarding"></a>
|
||||
|
||||
## `@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
|
||||
}
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-frame-forwarding -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-fs-local -->
|
||||
<a id="deepseek-aidsh-fs-local"></a>
|
||||
|
||||
|
||||
@@ -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` | — |
|
||||
|
||||
@@ -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` | — |
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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` |
|
||||
|
||||
@@ -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` |
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
|
||||
-----
|
||||
|
||||
<a id="use-this-package"></a>
|
||||
## 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.
|
||||
|
||||
-----
|
||||
|
||||
<a id="security-semantics"></a>
|
||||
## 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.
|
||||
|
||||
-----
|
||||
|
||||
<a id="understand-the-implementation"></a>
|
||||
## 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.
|
||||
|
||||
-----
|
||||
|
||||
<a id="model-experience"></a>
|
||||
## 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
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
|
||||
- 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.
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### Dev Note
|
||||
|
||||
<details>
|
||||
<summary>Working context for maintainers</summary>
|
||||
|
||||
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.
|
||||
|
||||
</details>
|
||||
@@ -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)
|
||||
|
||||
-----
|
||||
|
||||
<a id="use-this-package"></a>
|
||||
## 使用此包
|
||||
|
||||
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 所依赖能力的接收器。
|
||||
|
||||
-----
|
||||
|
||||
<a id="security-semantics"></a>
|
||||
## 安全语义
|
||||
|
||||
帧转发是插件使用的唯一原生渲染 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 自己审计的边界,不随本包变化。
|
||||
|
||||
-----
|
||||
|
||||
<a id="understand-the-implementation"></a>
|
||||
## 实现说明
|
||||
|
||||
工作区将[原生接收器](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)持有归属的理由。
|
||||
|
||||
-----
|
||||
|
||||
<a id="model-experience"></a>
|
||||
## 模型体验
|
||||
|
||||
无:帧转发只在进程间搬运像素,不增加模型上下文或 Session 事件。
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
无。
|
||||
|
||||
## 已知限制和后续工作
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
|
||||
- 滚动或缩放时,视频播放与 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` 份额,直到连接结束。
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### 开发备注
|
||||
|
||||
<details>
|
||||
<summary>维护者工作上下文</summary>
|
||||
|
||||
[原生 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 上运行。
|
||||
|
||||
</details>
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "フレーム転送",
|
||||
"description": "Host プラグインのネイティブプロセスが描画したフレームを、ピクセルをコピーせずに Desktop ウィンドウに表示します。"
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Пересылка кадров",
|
||||
"description": "Показывает в окне Desktop кадры, которые отрисовывают нативные процессы плагинов Host, без копирования пикселей."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "帧转发",
|
||||
"description": "把 Host 插件的原生进程渲染的帧显示在 Desktop 窗口中,无需复制像素。"
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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 <clocale>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
#if defined(_WIN32)
|
||||
#include <locale.h>
|
||||
#else
|
||||
#include <xlocale.h>
|
||||
#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<char16_t>(code)); return; }
|
||||
code -= 0x10000;
|
||||
out.push_back(static_cast<char16_t>(0xD800 + (code >> 10)));
|
||||
out.push_back(static_cast<char16_t>(0xDC00 + (code & 0x3FF)));
|
||||
}
|
||||
|
||||
void append_utf8(std::string& out, uint32_t code) {
|
||||
if (code < 0x80) out.push_back(static_cast<char>(code));
|
||||
else if (code < 0x800) { out.push_back(static_cast<char>(0xC0 | (code >> 6))); out.push_back(static_cast<char>(0x80 | (code & 0x3F))); }
|
||||
else if (code < 0x10000) {
|
||||
out.push_back(static_cast<char>(0xE0 | (code >> 12))); out.push_back(static_cast<char>(0x80 | ((code >> 6) & 0x3F)));
|
||||
out.push_back(static_cast<char>(0x80 | (code & 0x3F)));
|
||||
} else {
|
||||
out.push_back(static_cast<char>(0xF0 | (code >> 18))); out.push_back(static_cast<char>(0x80 | ((code >> 12) & 0x3F)));
|
||||
out.push_back(static_cast<char>(0x80 | ((code >> 6) & 0x3F))); out.push_back(static_cast<char>(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<uint32_t>(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<const unsigned char*>(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<uint64_t>(generation_value);
|
||||
frame.revision = static_cast<uint64_t>(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<char16_t>(unit << 4);
|
||||
if (next >= '0' && next <= '9') unit = static_cast<char16_t>(unit | (next - '0'));
|
||||
else if (next >= 'a' && next <= 'f') unit = static_cast<char16_t>(unit | (next - 'a' + 10));
|
||||
else if (next >= 'A' && next <= 'F') unit = static_cast<char16_t>(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<size_t>(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<unsigned char> 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<const unsigned char*>(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<void> owner) {
|
||||
auto attached = std::make_shared<const AttachedSink>(sink, rx, timeout_ms);
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<std::mutex> lock(mutex_);
|
||||
has_deliverable_ = state != nullptr;
|
||||
deliverable_ = state ? *state : Deliverable{};
|
||||
}
|
||||
|
||||
bool Bridge::lease(Lease& lease) {
|
||||
std::lock_guard<std::mutex> 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<const AttachedSink> detached;
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<void> 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<dsh_shared_texture_sink_v2*>(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<uint32_t>(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<uint64_t>(connection_id);
|
||||
deliverable.max_generation = static_cast<uint64_t>(max_generation);
|
||||
bridge.set_deliverable(&deliverable);
|
||||
return undefined(env);
|
||||
}
|
||||
|
||||
} // namespace desktop_bridge
|
||||
} // namespace dsh_frame_forwarding
|
||||
@@ -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 <node_api.h>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
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<const AttachedSink> attached;
|
||||
std::shared_ptr<void> 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<void> 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<const AttachedSink> attached_;
|
||||
std::weak_ptr<void> 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<void> 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 <class Receiver> std::shared_ptr<Receiver>* 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<std::shared_ptr<Receiver>*>(result);
|
||||
}
|
||||
|
||||
template <class Receiver, Bridge Receiver::*member> 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<Receiver>(env, args[0]);
|
||||
if (!owner) return nullptr;
|
||||
return attach(env, args + 1, (*owner).get()->*member, std::weak_ptr<void>(*owner));
|
||||
}
|
||||
|
||||
template <class Receiver, Bridge Receiver::*member> 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<Receiver>(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 <class Receiver, class Event> struct Request {
|
||||
std::shared_ptr<Receiver> receiver;
|
||||
uint64_t delivery, connection;
|
||||
std::string request_id, adapters;
|
||||
/** The receiver connection that delivered the frame. */
|
||||
decltype(Event::source) source;
|
||||
};
|
||||
|
||||
template <class Event> 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 <class Receiver, class Event> void on_delivered(void* data, const char* error) {
|
||||
if (!error) return;
|
||||
auto request = static_cast<Request<Receiver, Event>*>(data);
|
||||
presentation_error<Event>(request->source,
|
||||
error_text("presentation", request->request_id, "Native frame transfer failed (" + request->adapters + "): " + error));
|
||||
}
|
||||
|
||||
template <class Receiver, class Event> void on_settled(void* data, int invalidated) {
|
||||
std::unique_ptr<Request<Receiver, Event>> request(static_cast<Request<Receiver, Event>*>(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 <class Receiver, class Event> 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<Event> frame(event);
|
||||
{
|
||||
std::lock_guard<std::mutex> 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<Event>(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<Event>(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<Receiver, Event>{std::static_pointer_cast<Receiver>(lease.owner), delivery, connection, producer.request_id, adapters,
|
||||
frame->source};
|
||||
const dsh_shared_texture_callbacks_v2 callbacks{request, on_delivered<Receiver, Event>, on_settled<Receiver, Event>};
|
||||
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<Event>(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
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,321 @@
|
||||
// Windows receiver-worker resources; submitted GPU copies outlive cancellation until quiescent.
|
||||
class SourceAccess {
|
||||
ComPtr<IDXGIKeyedMutex> 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<std::chrono::milliseconds>(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<DWORD>(std::min<int64_t>(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<ID3D11Device1> device;
|
||||
ComPtr<ID3D11DeviceContext> context;
|
||||
};
|
||||
struct RelaySource {
|
||||
ComPtr<ID3D11Device1> device;
|
||||
ComPtr<ID3D11Texture2D> texture;
|
||||
HANDLE handle = nullptr;
|
||||
uint32_t width = 0, height = 0;
|
||||
~RelaySource() { if (handle) CloseHandle(handle); }
|
||||
};
|
||||
struct RelayReadback {
|
||||
ComPtr<ID3D11Device1> device;
|
||||
ComPtr<ID3D11DeviceContext> context;
|
||||
ComPtr<ID3D11Texture2D> source, staging;
|
||||
std::unique_ptr<ReadbackSync> completion;
|
||||
std::shared_ptr<RelayTexture> image;
|
||||
uint32_t width = 0, height = 0;
|
||||
};
|
||||
enum class RelayStage { waiting_target, pending_target, ready };
|
||||
struct RelayTexture {
|
||||
std::shared_ptr<RelayDevice> display;
|
||||
ComPtr<ID3D11Texture2D> source, target;
|
||||
ComPtr<IDXGIKeyedMutex> target_mutex;
|
||||
bool target_locked = false;
|
||||
std::unique_ptr<ReadbackSync> 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<ReadbackSync>& completion, std::string& diagnostic) {
|
||||
if (completion) return true;
|
||||
auto sync = std::make_unique<ReadbackSync>();
|
||||
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<ID3D11Device5> 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<bool>& 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<RelayTexture>& texture) { return reinterpret_cast<uintptr_t>(texture->handle); }
|
||||
int relay_advance(const std::shared_ptr<RelayTexture>& slot, const std::atomic<bool>& 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<RelayTexture>& slot) {
|
||||
if (!slot) return 0;
|
||||
if (slot->target_completion && slot->target_completion->pending && slot->target_completion->event_armed) return reinterpret_cast<uintptr_t>(slot->target_completion->event);
|
||||
return 0;
|
||||
}
|
||||
bool relay_gpu_idle(const std::shared_ptr<RelayTexture>& 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<bool>& stopped,
|
||||
std::shared_ptr<RelayDevice>& display, std::shared_ptr<RelayTexture>& 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<RelayDevice>();
|
||||
ComPtr<IDXGIFactory1> factory; ComPtr<IDXGIAdapter1> 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<IDXGIAdapter1> 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<ID3D11Device> 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<RelayTexture>();
|
||||
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<IDXGIResource1> 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<bool>& stopped,
|
||||
std::shared_ptr<RelayDevice>& display, std::shared_ptr<RelayTexture>& slot, std::string& diagnostic) {
|
||||
if (!relay_target(width, height, adapter, deadline, stopped, display, slot, diagnostic)) return false;
|
||||
ComPtr<ID3D11Texture2D> source;
|
||||
auto result = slot->display->device->OpenSharedResource1(reinterpret_cast<HANDLE>(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<RelayReadback>& slot, std::shared_ptr<RelaySource>& imported,
|
||||
std::string& diagnostic, std::string& adapter, bool* keyed_mutex,
|
||||
std::chrono::steady_clock::time_point deadline) {
|
||||
ComPtr<ID3D11Texture2D> source;
|
||||
using CompareHandles = BOOL (WINAPI*)(HANDLE, HANDLE);
|
||||
static const auto compare_handles = reinterpret_cast<CompareHandles>(
|
||||
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<HANDLE>(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<RelayReadback>();
|
||||
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<RelaySource>();
|
||||
if (!DuplicateHandle(GetCurrentProcess(), reinterpret_cast<HANDLE>(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<RelayReadback>& 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<RelayReadback>& slot) {
|
||||
return slot && slot->completion->pending && slot->completion->event_armed ? reinterpret_cast<uintptr_t>(slot->completion->event) : 0;
|
||||
}
|
||||
int relay_upload(const std::shared_ptr<RelayReadback>& source, uint32_t width, uint32_t height,
|
||||
const std::string& adapter, std::shared_ptr<RelayDevice>& display, std::shared_ptr<RelayTexture>& target,
|
||||
std::chrono::steady_clock::time_point deadline, const std::atomic<bool>& 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<RelayTexture>& texture) { return texture->display->device.Get(); }
|
||||
void relay_forget_source(const std::shared_ptr<RelayTexture>& texture) { texture->source.Reset(); }
|
||||
bool relay_copy_output(const std::shared_ptr<RelayTexture>& 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<ID3D11Texture2D*>(destination), texture->target.Get());
|
||||
return finish_gpu_submission(texture->display->context.Get(), *texture->target_completion, diagnostic);
|
||||
}
|
||||
bool relay_readback_image(const std::shared_ptr<RelayTexture>& texture, std::shared_ptr<RelayReadback>& staging, std::string& diagnostic) {
|
||||
auto next = std::make_shared<RelayReadback>();
|
||||
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<RelayReadback>& staging,
|
||||
const std::function<bool(const uint8_t*, uint32_t)>& 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<const uint8_t*>(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);
|
||||
}
|
||||
@@ -0,0 +1,764 @@
|
||||
#include "transport.h"
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <cstdio>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
#include <chrono>
|
||||
#if defined(__APPLE__)
|
||||
#include <CoreFoundation/CoreFoundation.h>
|
||||
#include <IOSurface/IOSurface.h>
|
||||
#include <bsm/libbsm.h>
|
||||
#include <mach/mach.h>
|
||||
#include <mach/notify.h>
|
||||
#include <servers/bootstrap.h>
|
||||
#include <unistd.h>
|
||||
#else
|
||||
#define NOMINMAX
|
||||
#include <windows.h>
|
||||
#include <sddl.h>
|
||||
#include <d3d11_4.h>
|
||||
#include <dxgi1_2.h>
|
||||
#include <wrl/client.h>
|
||||
#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<uint32_t>(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<uint64_t>(*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<unsigned long long>(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<const char*>(std::memchr(packet.text, 0, sizeof(packet.text)));
|
||||
wire.text_size = nul ? static_cast<uint32_t>(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<const mach_msg_audit_trailer_t*>(
|
||||
reinterpret_cast<const char*>(&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<const char*>(&msg.wire), size - offsetof(MachMessage, wire), true, packet)) {
|
||||
mach_msg_destroy(&msg.header); return -2;
|
||||
}
|
||||
pid = static_cast<uint32_t>(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<mach_port_delta_t>(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<bool> stopped_{false};
|
||||
std::atomic<uint32_t> peer_{0};
|
||||
/** True once `local_`'s single send right reached the peer and `MACH_NOTIFY_NO_SENDERS` is armed on `local_`. */
|
||||
std::atomic<bool> 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<char*>(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<std::mutex> 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<IOSurfaceRef>(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<mach_msg_size_t>(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<uintptr_t>(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<bool> stopped_{false};
|
||||
public:
|
||||
explicit MachListener(const Endpoint& endpoint) : name_(endpoint.name) {
|
||||
port_ = allocate_listener_port();
|
||||
if (bootstrap_register(bootstrap_port, const_cast<char*>(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<char*>(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<MachChannel>(reply, pid);
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
std::unique_ptr<Listener> listen(Endpoint& endpoint, uint32_t) { return std::make_unique<MachListener>(endpoint); }
|
||||
std::unique_ptr<Channel> connect_channel(const Endpoint& endpoint, const std::function<bool()>& cancelled) {
|
||||
if (cancelled && cancelled()) throw std::runtime_error("Frame-forwarding connection cancelled or timed out");
|
||||
return std::make_unique<MachChannel>(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<IOSurfaceRef>(resource)); }
|
||||
uint64_t resource_bytes(uintptr_t resource) { return IOSurfaceGetAllocSize(reinterpret_cast<IOSurfaceRef>(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<IOSurfaceRef>(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<ID3D11Fence> fence;
|
||||
ComPtr<ID3D11DeviceContext4> signaling;
|
||||
ComPtr<ID3D11Query> 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<uint32_t>(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<uintptr_t>(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<uint32_t>(luid.HighPart) << ':' << luid.LowPart;
|
||||
return id.str();
|
||||
}
|
||||
std::string device_adapter(void* device) {
|
||||
if (!device) return {};
|
||||
ComPtr<IDXGIDevice> dxgi; ComPtr<IDXGIAdapter> adapter; DXGI_ADAPTER_DESC desc{};
|
||||
if (FAILED(static_cast<ID3D11Device*>(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<IDXGIFactory2> factory; LUID luid{};
|
||||
if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) ||
|
||||
FAILED(factory->GetSharedResourceAdapterLuid(reinterpret_cast<HANDLE>(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<LONGLONG>(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<uint32_t> 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<bool()>& 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<std::chrono::milliseconds>(deadline - Clock::now()).count();
|
||||
if (!cancelled && left <= 0) break;
|
||||
if (WaitNamedPipeA(endpoint.name.c_str(), cancelled ? 100 : static_cast<DWORD>(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<std::mutex> 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<uint64_t>(resource);
|
||||
std::memcpy(write_buffer_.text, packet.text, text_size);
|
||||
const DWORD size = static_cast<DWORD>(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<const char*>(&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<HANDLE>(static_cast<uintptr_t>(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<uintptr_t>(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<unsigned char> data(size);
|
||||
bool ok = GetTokenInformation(token, TokenUser, data.data(), size, &size) != FALSE;
|
||||
CloseHandle(token);
|
||||
LPSTR sid = nullptr;
|
||||
if (!ok || !ConvertSidToStringSidA(reinterpret_cast<TOKEN_USER*>(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<PipeChannel>(pipe, static_cast<uint32_t>(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<std::chrono::milliseconds>(handshake_end - std::chrono::steady_clock::now()).count();
|
||||
received = channel->receive(hello, static_cast<uint32_t>(std::clamp<long long>(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<Listener> listen(Endpoint& endpoint, uint32_t handshake_ms) { return std::make_unique<PipeListener>(endpoint, handshake_ms); }
|
||||
std::unique_ptr<Channel> connect_channel(const Endpoint& endpoint, const std::function<bool()>& cancelled) { return std::make_unique<PipeChannel>(endpoint, cancelled); }
|
||||
uint32_t process_id() { return GetCurrentProcessId(); }
|
||||
void release_resource(uintptr_t resource) { if (resource) CloseHandle(reinterpret_cast<HANDLE>(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<ID3D11Texture2D>& texture) {
|
||||
const auto failed = [&](const char* operation, HRESULT result) {
|
||||
std::ostringstream text; text << operation << " HRESULT=0x" << std::hex << static_cast<uint32_t>(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<IDXGIFactory1> factory; ComPtr<IDXGIAdapter1> 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<IDXGIAdapter1> 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<ID3D11Device> device; ComPtr<ID3D11Device1> 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<HANDLE>(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<ID3D11Texture2D> 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<ID3D11DeviceContext> 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; }
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
#pragma once
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <functional>
|
||||
#include <chrono>
|
||||
#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> 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<Listener> listen(Endpoint& endpoint, uint32_t handshake_ms);
|
||||
std::unique_ptr<Channel> connect_channel(const Endpoint& endpoint, const std::function<bool()>& 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<RelayTexture>& 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<bool>& stopped,
|
||||
std::shared_ptr<RelayDevice>& display, std::shared_ptr<RelayTexture>& slot, std::string& diagnostic);
|
||||
int relay_advance(const std::shared_ptr<RelayTexture>& slot, const std::atomic<bool>& stopped,
|
||||
std::chrono::steady_clock::time_point deadline, std::string& diagnostic);
|
||||
uintptr_t relay_completion_event(const std::shared_ptr<RelayTexture>& slot);
|
||||
/** True only after every submitted copy completes or its device is removed. */
|
||||
bool relay_gpu_idle(const std::shared_ptr<RelayTexture>& 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<RelayReadback>& slot, std::shared_ptr<RelaySource>& 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<RelayReadback>& slot, bool retiring, std::string& diagnostic);
|
||||
uintptr_t relay_readback_event(const std::shared_ptr<RelayReadback>& slot);
|
||||
int relay_upload(const std::shared_ptr<RelayReadback>& source, uint32_t width, uint32_t height,
|
||||
const std::string& adapter, std::shared_ptr<RelayDevice>& display, std::shared_ptr<RelayTexture>& target,
|
||||
std::chrono::steady_clock::time_point deadline, const std::atomic<bool>& 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<RelayTexture>& texture);
|
||||
void relay_forget_source(const std::shared_ptr<RelayTexture>& texture);
|
||||
/** Copy the retained image and signal its existing completion fence. */
|
||||
bool relay_copy_output(const std::shared_ptr<RelayTexture>& texture, void* destination, std::string& diagnostic);
|
||||
bool relay_readback_image(const std::shared_ptr<RelayTexture>& texture, std::shared_ptr<RelayReadback>& staging, std::string& diagnostic);
|
||||
int relay_with_pixels(const std::shared_ptr<RelayReadback>& staging,
|
||||
const std::function<bool(const uint8_t*, uint32_t)>& consume, std::string& diagnostic);
|
||||
#endif
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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<FrameViewportResult>
|
||||
/**
|
||||
* 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<void>
|
||||
/** 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<void>
|
||||
/**
|
||||
* 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<void>
|
||||
/**
|
||||
* 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
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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<FrameForwardingViewport, 'version'>, completion: Promise<FrameForwardingViewport>): Promise<FrameForwardingViewport>
|
||||
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<void>
|
||||
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<FrameForwardingViewport>
|
||||
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<typeof Promise.withResolvers<FrameForwardingViewport>> | undefined
|
||||
let requestedViewport: ReturnType<typeof Promise.withResolvers<FrameForwardingViewport>> | undefined
|
||||
let latestViewport: Parameters<MountOwner['viewport']>[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<FrameForwardingViewport>()
|
||||
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<FrameForwardingViewport> => {
|
||||
if (disposed) return Promise.reject(new FrameDiscardedError('producer-changed'))
|
||||
const completion = requestedViewport ??= Promise.withResolvers<FrameForwardingViewport>()
|
||||
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 }
|
||||
}
|
||||
@@ -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'
|
||||
}
|
||||
}
|
||||
@@ -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<void>> {
|
||||
return mountFrameForwarding(ctx, remote)
|
||||
}
|
||||
@@ -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<void>> {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<void>
|
||||
setContent(content: ContentState | undefined): void
|
||||
dispose(): void
|
||||
}
|
||||
|
||||
interface VideoTrackGenerator extends MediaStreamTrack { readonly writable: WritableStream<VideoFrame> }
|
||||
|
||||
/** 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,
|
||||
}
|
||||
}
|
||||
@@ -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<void>
|
||||
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<void>
|
||||
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<ReadyWaiter>()
|
||||
/** 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<void> | undefined
|
||||
private viewportVersion = 0
|
||||
private viewportState: FrameForwardingViewport | undefined
|
||||
private viewportReady: Promise<void> = Promise.resolve()
|
||||
private contentView: FrameContentView | undefined
|
||||
private contentWindow: FrameContentWindow | undefined
|
||||
private contentWindows: ContentState['windows'] = []
|
||||
private contentRequest: Promise<FrameForwardingViewport> | 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<void> | 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<FrameChannelCloseCause>()
|
||||
/**
|
||||
* 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<FrameChannelCloseCause> = 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<void> {
|
||||
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<FrameForwardingViewport> {
|
||||
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<FrameForwardingViewport, 'version'>, completion: Promise<FrameForwardingViewport>,
|
||||
): Promise<FrameForwardingViewport> {
|
||||
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<FrameForwardingViewport, 'version'>, beforeSend?: (viewport: FrameForwardingViewport) => void,
|
||||
): Promise<FrameForwardingViewport> {
|
||||
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<FrameForwardingViewport> {
|
||||
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<FrameConnectionId> {
|
||||
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<FrameConnectionId>((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<void>, 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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
if (this.closing === undefined) {
|
||||
const completion = Promise.withResolvers<undefined>()
|
||||
this.closing = completion.promise
|
||||
void this.closeChannel().then(() => { completion.resolve(undefined) }, completion.reject)
|
||||
}
|
||||
return this.closing
|
||||
}
|
||||
|
||||
private async closeChannel(): Promise<void> {
|
||||
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<void> {
|
||||
if (this.streamDrain !== undefined) return
|
||||
const completion = Promise.withResolvers<void>()
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<FrameForwardingEvent>({
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<RemoteResult<FrameViewportResult>>
|
||||
}
|
||||
|
||||
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<string, unknown>
|
||||
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<Element>
|
||||
/** 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<unknown>
|
||||
/** 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<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<FrameRxId, FrameChannelReceiver>()
|
||||
/** Latest state per channel, ordered by its arrival; a closed channel leaves once its consumer detaches. */
|
||||
let states = new Map<FrameRxId, FrameChannelSnapshot>()
|
||||
/** 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<FrameRxEvent, { kind: 'failure' }> | 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<void> => {
|
||||
const run = async (): Promise<void> => {
|
||||
// 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<void> => {
|
||||
const held = holder
|
||||
if (held?.rx === rx) await leave(held, () => holder === held)
|
||||
}
|
||||
const endRoutes = (event: Extract<FrameRxEvent, { kind: 'failure' }>): 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<void> | undefined
|
||||
const detach = async (): Promise<void> => {
|
||||
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<Element>(), 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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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<FrameForwardingEvent, { kind: 'snapshot' }>): 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<typeof setTimeout>
|
||||
}
|
||||
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<string, Pending>
|
||||
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<void> | undefined
|
||||
}
|
||||
|
||||
function object(value: unknown): Record<string, unknown> {
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
||||
throw new Error('Invalid frame-forwarding message')
|
||||
return value as Record<string, unknown>
|
||||
}
|
||||
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<FrameRxId, Channel>()
|
||||
/** 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<SharedTextureNativeSink> | undefined
|
||||
private generation = 0
|
||||
private sequence = 0
|
||||
private readonly operations = new Set<Promise<unknown>>()
|
||||
private resetting: Promise<void> | 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<T>(operation: Promise<T>): Promise<T> {
|
||||
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<FrameForwardingCapabilities> {
|
||||
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<FrameChannel> {
|
||||
if (this.resetting !== undefined) return Promise.reject(new Error('Native channels are closing'))
|
||||
return this.track(this.openChannel())
|
||||
}
|
||||
|
||||
private async openChannel(): Promise<FrameChannel> {
|
||||
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<FrameRxId>(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<FrameTx>(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<SharedTextureNativeSink> {
|
||||
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<FrameForwardingAdapterId | null> {
|
||||
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<FrameViewportResult> {
|
||||
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<FrameForwardingEvent, { kind: 'snapshot' }>): 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<void> {
|
||||
if (connection.pending.size >= this.limits.maxPendingRequests) return Promise.reject(new Error('Native control queue is full'))
|
||||
const requestId = randomUUID()
|
||||
return new Promise<void>((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<string, unknown>
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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 })
|
||||
}
|
||||
}
|
||||
@@ -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<void>
|
||||
}
|
||||
|
||||
/** 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<FrameForwardingReceiverEvent, { type: 'presentation-error' }>
|
||||
| { 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<void>
|
||||
}
|
||||
|
||||
/** Read `{ source, requestId?, error }` from the addon's event text; other text is a presentation failure. */
|
||||
function presentationError(
|
||||
{ connectionId, text }: Extract<AddonEvent, { type: 'presentation-error' }>,
|
||||
): Extract<FrameForwardingReceiverEvent, { type: 'presentation-error' }> {
|
||||
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<FrameForwardingBudget, object>()
|
||||
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<void> | 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) },
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -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<FrameForwardingCapabilities>
|
||||
/**
|
||||
* 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<FrameChannel>
|
||||
/**
|
||||
* 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<void>
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
Loaded 100 of 142 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user