diff --git a/docs/experiments/remote-web-public-network-confinement.md b/docs/experiments/remote-web-public-network-confinement.md new file mode 100644 index 00000000000..18c723f8415 --- /dev/null +++ b/docs/experiments/remote-web-public-network-confinement.md @@ -0,0 +1,220 @@ +# Remote web public-network confinement + +## Status + +Design proposal. Remote tenant web commands stay refused with +`remote_web_public_network_unenforced` until this contract has an implementation and end-to-end +evidence. + +## Security invariant + +A browser that belongs to a request with `internal.publicNetworkOnly` must not create a network +connection to an address that is not globally reachable. This rule applies to every browser-created +connection for the session. It is not limited to the URL supplied to `open`. + +The enforcement point must select and connect the destination IP address. A URL check, a DNS check +followed by a browser connection, or inspection after a request cannot enforce the invariant. + +## Required boundary + +Use one daemon-owned explicit forward proxy for confined web sessions. Start the proxy before the +first browser process for a confined session. Keep it alive until that browser is closed. Configure +the browser with a fixed proxy and no direct fallback. + +The proxy must apply these rules: + +1. Accept connections only on a loopback listener. Apply global and per-session connection limits, + because another local user can discover and use a TCP listener. +2. Accept only HTTP proxy requests and HTTP `CONNECT` requests. +3. Parse the authority once. Reject user information, malformed ports, IP zone identifiers, and + non-canonical or ambiguous IP address forms. +4. Permit only `http`, `https`, `ws`, and `wss` browser traffic. Treat every other external protocol + as denied unless a later design names its enforcement path. +5. Resolve a hostname for each new upstream connection. Never reuse a browser-supplied resolution. +6. Classify every resolved address. Reject the request when any answer is unspecified, loopback, + link-local, private, carrier-grade NAT, documentation, benchmarking, multicast, reserved, or + otherwise non-unicast. Also reject every address assigned to a current daemon-host network + interface, including a publicly routed address. Apply IPv4 classification and local-interface + comparison to IPv4-mapped IPv6 addresses. Reject IPv4-embedded IPv6 answers, including DNS64 + synthesis under a network-specific Pref64, unless the proxy can prove the embedded IPv4 + destination is public and the translated peer is not on a local interface. If the prefix cannot + be identified and checked, refuse the answer set. +7. Connect to one admitted numeric address from that resolution result. Do not resolve the hostname + again in the connection API. Preserve the original hostname only for the HTTP `Host` field and + TLS server name that pass through the tunnel. +8. Apply the same resolution and connection rule to an absolute-form HTTP request and to `CONNECT`. +9. Re-resolve on a new connection, including after redirects, connection failure, proxy retry, and + keep-alive expiry. A previously admitted address does not admit a different address. +10. Bound request headers, connection count, DNS time, connect time, idle time, and bytes buffered + before either side applies backpressure. +11. Require absolute-form targets for ordinary HTTP. Treat the parsed target as the only authority, + and overwrite `Host` from that authority after admission. +12. Reject conflicting or ambiguous `Content-Length`, `Transfer-Encoding`, and upgrade framing. + Remove proxy credentials and hop-by-hop headers before forwarding. Preserve only the one valid + WebSocket upgrade shape. +13. Emit typed refusal details without returning resolved private addresses to the remote caller. + +The browser launch must use the fixed proxy as its only network route. It must set +`--proxy-bypass-list="<-loopback>"`; an empty bypass list retains Chromium's implicit direct rules +for localhost, link-local, and unspecified addresses. Chromium documents `<-loopback>` as the +subtractive rule for those implicit bypasses in +[Proxy support in Chrome](https://chromium.googlesource.com/chromium/src/+/master/net/docs/proxy.md#proxy-config-url-patterns_subtract-implicit-rules). +The launch must also disable QUIC and non-proxied WebRTC UDP. The launch owner must replace +conflicting caller-supplied proxy, bypass, QUIC, and WebRTC arguments. Appending another argument +without proving Chromium's duplicate-argument precedence is not sufficient. + +If Chromium or `agent-browser` can create another external transport that does not use the fixed +proxy, remote web remains refused until that transport is disabled or confined. Examples include +WebTransport, direct sockets exposed by an extension, and a browser feature added after the pinned +backend version. + +## Backend launch and session isolation + +The implementation stack updates the managed backend from `agent-browser` 0.39.0 to 0.42.0 in +#5273. The proxy flags expose a launch seam, but they do not enforce confinement by themselves. + +- `--proxy` and `AGENT_BROWSER_PROXY` become Chromium `--proxy-server`. +- `--proxy-bypass` and `AGENT_BROWSER_PROXY_BYPASS` become Chromium `--proxy-bypass-list`. +- A changed proxy launch setting can relaunch a managed browser. The setting is ignored when the + session attaches through CDP, auto-connect, or a provider. +- Raw launch arguments can disable QUIC. The backend's domain-filter path already removes a caller + WebRTC policy argument before it appends `disable_non_proxied_udp`. + +The managed backend inherits `AGENT_BROWSER_*` connection settings from the daemon host. It also +uses the same socket directory for local and remote web sessions. This layout does not establish +that an existing browser was started under the remote confinement policy. An inherited connection +target can also select an external browser where the proxy setting has no effect. The +[0.42.0 session documentation](https://raw.githubusercontent.com/vercel-labs/agent-browser/v0.42.0/skill-data/core/references/session-management.md) +describes both the ignored proxy setting on external connections and retained settings across +commands and daemon restarts. A successful CLI command does not prove that its browser used the +proxy. + +Route remote sessions through a daemon-owned socket namespace separate from local sessions. Preserve +the ADR 0037 backend key and socket path limits. Remove inherited connection targets, profiles, +extensions, restore and state inputs, raw startup arguments, and conflicting proxy settings before +launch. Reject a remote command if the backend can still attach through CDP, auto-connect, or a +provider. Start a fresh managed Chromium browser under the confined policy, and verify that the +backend applied the proxy setting before accepting the session. Apply the same policy to every +later command that can launch or relaunch a browser. Keep the proxy alive through the browser's +life and close the browser if the matching proxy cannot be recovered. + +## Coverage table + +| Traffic source | Required enforcement | +| --- | --- | +| Initial `open` URL | Scheme admission plus the proxy's resolution and pinned numeric connection | +| HTTP redirect | The redirected request returns through the proxy and receives a fresh connection admission | +| HTML subresource, worker, service worker, `fetch`, and XHR | The browser has no direct route, so every external connection returns through the proxy | +| WebSocket | `ws` uses an absolute-form proxy request and `wss` uses `CONNECT`; both use the same admission | +| DNS rebinding | The proxy connects only to an address from its own current result and never asks the socket layer to resolve again | +| DNS64/NAT64 answer | The proxy identifies the synthesis prefix and classifies the embedded IPv4 destination before connecting, or refuses the answer set | +| HTTP keep-alive and HTTP/2 inside `CONNECT` | The admitted numeric peer stays fixed for the life of that connection | +| QUIC and WebTransport over HTTP/3 | Disabled unless the confinement owner later provides a UDP enforcement path | +| WebRTC | Non-proxied UDP disabled. A test must prove that the pinned Chromium build does not reach a private peer through another candidate type | +| `file`, `ftp`, `gopher`, custom handlers, and extension protocols | Refused before navigation or disabled at browser launch; no claim relies only on the current CLI URL parser | +| `data`, `blob`, `about`, and `view-source` | Local rendering may run, but any external connection that it initiates still uses the proxy | +| Browser proxy settings | Conflicting environment and caller arguments are replaced. The bypass list is exactly `<-loopback>`, not empty. Page content cannot change the fixed browser proxy | +| Prior local session or inherited connection target | Remote socket namespace is separate. CDP, auto-connect, and provider attachments are rejected before navigation | +| Relaunch after a later command or daemon restart | The same confinement policy and live proxy are required before any browser process starts | + +## Trust-boundary case table + +| Case | Who chooses the name | What the kernel resolves | What can change | Where bytes first leave the host | Result | +| --- | --- | --- | --- | --- | --- | +| Public hostname | Remote page or remote caller | Nothing by hostname; the proxy supplies a numeric address | DNS can change before the next connection | Proxy socket to the admitted public address | Accept | +| Public hostname resolves only to a denied address | Remote page or remote caller | No upstream socket is created | DNS can change after refusal | Nowhere | Refuse | +| Mixed public and denied answers | Authoritative DNS | No upstream socket is created | Answer order and TTL can change | Nowhere | Refuse the complete answer set | +| Hostname changes from public to denied | Authoritative DNS | Each connection receives one numeric address | DNS changes between connections | Existing connection stays on its admitted peer; the next connection is refused | Accept existing, refuse new | +| Numeric private address | Remote page or remote caller | Nothing | Text representations can be ambiguous | Nowhere | Refuse | +| Daemon host's public interface address | Remote page or remote caller | Nothing | Interface addresses can change | Nowhere | Refuse | +| Public HTTP redirect to private | Remote server | Nothing by hostname | Redirect target is attacker-controlled | Nowhere for the redirected destination | Refuse redirected connection | +| Public TLS tunnel | Remote page or remote caller | Nothing by hostname; proxy connects to an admitted numeric peer | Bytes inside TLS are opaque | Proxy socket to the admitted public address | Accept | +| Fixed proxy with an empty bypass list | Chromium's implicit rules | Chromium may connect directly to localhost, link-local, or unspecified literals | Browser defaults can change with Chromium | Browser socket bypasses the proxy | Refuse the launch configuration | +| Fixed proxy with bypass list `<-loopback>` | Remote page or remote caller | Proxy resolves and connects as above | Browser defaults can change with Chromium | Proxy socket only | Accept after the host-boundary bypass test passes | +| Proxy unavailable or loses its listener capability | Daemon lifecycle | Nothing | Browser may retry | Nowhere | Fail closed; no direct fallback | +| Existing or externally attached browser ignores proxy settings | Backend session state or inherited host environment | No confined destination is proven | A later command can reuse or relaunch the browser | The external browser can connect directly | Refuse; do not adopt that browser | + +## Lifecycle and ownership + +The confinement proxy belongs beside the managed browser lifecycle in `@agent-device/platform-web`. +The request router supplies the trusted `publicNetworkOnly` fact through request-bound runtime +composition. Page input and command flags must not be able to enable confinement for one call and +then reuse the browser without it, or disable confinement on a browser that was created with it. + +Confinement does not add a suffix or another axis to the device ID or backend key. ADR 0037 derives +`p_`, `w_`, and `t_` keys from session and tenant isolation, independently of `publicNetworkOnly`. +A remote request can therefore use a `p_` or `w_` key, and a local tenant-isolated request can use +a `t_` key. Record the confinement fact on the web session lease and durable process record. Before +an existing session is adopted, compare that fact with the request and refuse a mismatch, regardless +of key prefix. Keep confined browser sockets in a separate namespace from local browser sockets. +The process record also identifies the confined browser's proxy listener. +Startup recovery must close a browser when it cannot prove that the matching proxy listener is live +and owned by this daemon process. The remote socket namespace must remain separate after a daemon +restart. A local session must not be able to reuse its backend key to enter that namespace. + +`close` remains available when proxy startup, proxy recovery, or confinement admission fails. + +## Proof required before enabling remote web + +Focused unit tests must cover the complete IPv4 and IPv6 classification table, authority parsing, +pinned-address connection, limits, and typed refusals. Integration tests with the real pinned +Chromium and managed `agent-browser` must demonstrate denial for initial URLs, redirects, +subresources, workers, service workers, WebSockets, DNS rebinding, loopback bypass, QUIC, WebRTC, +and conflicting browser arguments. + +The browser evidence must observe attempted connections at a host network boundary. A proxy log +alone cannot prove that Chromium had no bypass. Run the same public destinations as positive +controls and prove that normal remote web commands still work. + +Repeat this evidence when the pinned `agent-browser` or Chromium version changes. Keep remote web +fail-closed when the evidence lane is absent or fails. + +## Phased implementation + +Each phase can merge while `assertRemoteWebDeviceAdmitted` still refuses remote web. Remove that +refusal only in the final phase. + +1. Add `publicNetworkOnly?: true` to `PlatformProviderRequestContext`. Populate it only from + `DaemonRequest.internal.publicNetworkOnly`. Forward it to default web provider construction. + Add routing tests that prove nested batch and replay requests cannot clear the fact. +2. Add a private `@agent-device/platform-web` public-destination classifier. Cover every IPv4 and + IPv6 range, IPv4-mapped IPv6, DNS64/NAT64 synthesis, mixed DNS answers, and current host-interface + addresses. Do not export it as a general URL validator. +3. Add the bounded loopback forward proxy. Use Node's HTTP parser for absolute-form HTTP and + `CONNECT`. Resolve all answers, reject the complete set when one answer is denied, and connect + with the admitted numeric address. Add framing, header, timeout, backpressure, cancellation, and + capacity tests at this module boundary. +4. Give the default web provider a confinement-proxy lease keyed by the existing backend key and + recorded confinement fact. Refuse adoption when a request's fact differs from that of the + existing session. Isolate its backend socket namespace from local sessions. Start the proxy + before `open`. + Pass the fixed proxy, the exact `<-loopback>` subtractive bypass rule, `--disable-quic`, and the + enforced WebRTC policy on every backend call. Remove inherited connection targets and reject + external attachments and conflicting host settings. Verify a fresh managed browser received the + proxy policy before navigation. Record proxy ownership beside the managed browser process record. + Close both resources together. +5. Add real Chromium integration evidence for every row in the coverage table. Observe attempted + egress outside the proxy process. Include public positive controls and proxy-death fail-closed + behavior on macOS, Linux, and Windows. +6. Replace `remote_web_public_network_unenforced` admission with a check for a live, matching + confinement lease. Keep `close` independent of that check. Update help and security docs in the + same change. + +The dependency change is optional. The current backend flags can launch a confined browser. A +smaller and safer integration would add an upstream `--public-network-proxy ` mode that rejects +profiles, providers, restore/state, extensions, startup URLs in raw arguments, proxy bypasses, QUIC, +and unsafe WebRTC settings as one atomic launch policy. Without that API, agent-device must pin and +re-audit those launch-option conflicts at each backend upgrade. + +## Rejected partial fixes + +- Checking only the `open` URL misses redirects, subresources, script-created requests, and sockets. +- Resolving before navigation and then passing the hostname to Chromium permits a second DNS lookup + and DNS rebinding. +- Request interception through an `agent-browser` command is unavailable in the managed backend and + would still need proof for workers, WebSockets, service workers, and browser-owned traffic. +- Observing `network requests` after execution detects traffic after the protected service may have + received it. +- An HTTP proxy without browser launch hardening leaves implicit bypasses and UDP transports. +- A DNS server that filters private answers does not pin the address used by the connection and does + not cover numeric destinations. diff --git a/packages/command-surface/src/recording/index.ts b/packages/command-surface/src/recording/index.ts index 12659a90e1f..bba91367c2b 100644 --- a/packages/command-surface/src/recording/index.ts +++ b/packages/command-surface/src/recording/index.ts @@ -129,7 +129,7 @@ export const recordCommandFacet = defineCommandFacet({ summary: 'Start or stop screen recording', searchHint: 'mp4', cliDetail: - 'MP4 verification setup starts in the background before recording output preparation, without delaying capture. If setup exceeds the stop budget, details.reason is video_validator_compile_timeout (retriable); run record stop again while setup continues. Hosts without xcrun keep container-only MP4 completion. Other compilation failures, or an unavailable validator executable or AVFoundation during verification, return video_validator_unavailable. A Swift helper cache that is not private to this user returns swift_cache_untrusted. When details.ancestor is the configured cache root or a directory above it that the group or other users can write, remove that write access (chmod g-w,o-w) from that directory. When it is v3 or a directory inside it (bin, home or module-cache), do not chmod it: that clears the refusal but keeps whatever was written while it was open. Set AGENT_DEVICE_SWIFT_CACHE_DIR to a new directory only you can write, or remove that directory yourself; agent-device never deletes it. When details.exposure is untrusted_developer_dir, the DEVELOPER_DIR selection is refused; it is checked only when a Swift helper compiles, and a cached helper is reused without checking it: restart the daemon with DEVELOPER_DIR unset, or set DEVELOPER_DIR to an empty value for one local command to select the system default, or point it at an Xcode Contents/Developer directory, given as an absolute path, that root or you own along with every directory above it. Repair the reported failure and retry record stop; a failed compile is retried on the next start or stop. The default --scope app requires an active app session from open ; use --scope device/system to explicitly request whole-screen recording where the selected backend supports it. Android record start publishes a durable device manifest, recordings longer than the 180s adb screenrecord limit are returned as multiple MP4 chunks while the daemon stays alive, and daemon-restart recovery uses only manifest-owned chunks. An Android recorder the device refuses at startup returns COMMAND_FAILED with reason android_screenrecord_startup_failed, and details.stderr carries the message the native recorder printed. That message is the verdict of the device policy, so report it to the device manufacturer; agent-device has no alternative Android recording backend. Android screenrecord encodes a frame only when the screen changes, so a clip can end at the last frame the recorder encoded instead of at record stop; durationMs is host wall clock from record start until the export finished, and capturedDurationMs reports the video timeline when it can be measured, with a warning naming how much of the window that video covers. An Android manifest left by an unreachable recording is retired on the next start once its recorders are proven gone; one still owned refuses with non-retriable DEVICE_IN_USE and reason native_recovery_evidence_open naming the session to run record stop for, and a recorder that is still writing an artifact refuses with DEVICE_IN_USE and reason native_recording_artifact_claimed, which clears itself once that recorder ends at the 180s limit. HarmonyOS supports whole-screen recording on physical devices only: use --scope device/system; --fps, --quality, and --hide-touches are unsupported. Use --quality to choose medium or high export quality on supported backends. The touch overlay renders at most 30 frames a second, or at --fps when lower; a lower --fps makes record stop faster on a long recording, and an overlay export that runs past its budget returns the raw video with an overlayWarning. A watchOS simulator records the same way an iOS simulator does: the host runs simctl recordVideo, so the watch needs no runner recorder and the export keeps the resolution of the watch. An iOS simulator host recording lock returns non-retriable DEVICE_IN_USE with reason apple_simulator_recording_busy. Stop the recording in its owning session; if a dead recorder left the host locked, ask the host operator to restart the CoreSimulator stream service. A physical iPhone or iPad on a USB cable of this Mac records the USB screen-capture source of the device near 60 fps when both recording transports belong to this host; otherwise it records runner screenshots (help physical-device). When USB capture cannot record, before its first frame, the runner records instead and recorderFallbackReason names why: ios_usb_capture_camera_access_not_authorized (agent-device never asks for camera access), ios_usb_capture_device_name_shared (another Apple device in the inventory of the daemon, cabled or wireless, or another USB capture source on this Mac has the name), ios_usb_capture_device_not_found (no capture source with the device name appeared), ios_usb_capture_no_frames (screen asleep or locked), or ios_usb_capture_start_busy (another USB capture recording on this Mac, of any user, held the host-wide start lock). USB capture fails the start with ios_usb_capture_start_lock_unusable (another account owns the start lock file and does not let this user read it). On any backend, record start first settles the open recording records on its device that it would refuse on and whose session this daemon no longer holds: it finishes each one as its own record stop would, so the export lands at the output path of that recording and a later record stop in that session returns it, and runs the exact-owner recovery a daemon restart runs, which discards what that recording left, only for a record that cannot finish. A record it cannot confirm cleaned, or one whose session is still held, refuses the start with reason cleanup-unconfirmed and names that session: stop or close it, then retry. A record that another device left under the same session name is never settled from this device: the start refuses and names that device, so stop it in that session or record under another session name. A record stop that cannot produce its export keeps what a retry reads back — on Android the device-side artifact and the native manifest — leaves the recording manifest of that session open, and returns its own error, so retry record stop in that session; while this daemon holds that session, only closing it disposes them, and once it does not, the next record start on that device settles them as described above. Every stopped recording also reports what became of its recorder and of the file that recorder writes to: recorder is confirmed, or lost when the session holding it died, and nativePathDisposition is retirable while that file still owes a removal or retired once its removal was verified. Both are optional disclosures, not failures; ADR 0024 declares further states (unconfirmed, pending) for the steps that gain those probes, and no stop reports them yet. record contact-sheet [--out ] is a local report over a file you already exported: it decodes frames out of that MP4 and writes one PNG holding the cells where the screen visibly changed, each labeled with its elapsed time on the clip timeline. It needs no session and no device, rebuilds any past recording, and works for every backend that exports MP4; a WebM recording is refused with reason contact_sheet_container_unsupported. The sample grid is bounded and spread across the whole clip, so it reports coverage rather than a review: a flash that opens and closes entirely between two sample times is not in the sheet, which is why the result also reports how many times it sampled and how many frames came back. Frame decoding is Apple AVFoundation tooling, so the command runs only on macOS hosts and refuses elsewhere with reason contact_sheet_unsupported_host.', + 'MP4 verification setup starts in the background before recording output preparation, without delaying capture. If setup exceeds the stop budget, details.reason is video_validator_compile_timeout (retriable); run record stop again while setup continues. Hosts without xcrun keep container-only MP4 completion. Other compilation failures, or an unavailable validator executable or AVFoundation during verification, return video_validator_unavailable. A Swift helper cache that is not private to this user returns swift_cache_untrusted. When details.ancestor is the configured cache root or a directory above it that the group or other users can write, remove that write access (chmod g-w,o-w) from that directory. When it is v3 or a directory inside it (bin, home or module-cache), do not chmod it: that clears the refusal but keeps whatever was written while it was open. Set AGENT_DEVICE_SWIFT_CACHE_DIR to a new directory only you can write, or remove that directory yourself; agent-device never deletes it. When details.exposure is untrusted_developer_dir, the DEVELOPER_DIR selection is refused; it is checked only when a Swift helper compiles, and a cached helper is reused without checking it: restart the daemon with DEVELOPER_DIR unset, or set DEVELOPER_DIR to an empty value for one local command to select the system default, or point it at an Xcode Contents/Developer directory, given as an absolute path, that root or you own along with every directory above it. Repair the reported failure and retry record stop; a failed compile is retried on the next start or stop. The default --scope app requires an active app session from open ; use --scope device/system to explicitly request whole-screen recording where the selected backend supports it. Android record start publishes a durable device manifest, recordings longer than the 180s adb screenrecord limit are returned as multiple MP4 chunks while the daemon stays alive, and daemon-restart recovery uses only manifest-owned chunks. An Android recorder the device refuses at startup returns COMMAND_FAILED with reason android_screenrecord_startup_failed, and details.stderr carries the message the native recorder printed. That message is the verdict of the device policy, so report it to the device manufacturer; agent-device has no alternative Android recording backend. Android screenrecord encodes a frame only when the screen changes, so a clip can end at the last frame the recorder encoded instead of at record stop; durationMs is host wall clock from record start until the export finished, and capturedDurationMs reports the video timeline when it can be measured, with a warning naming how much of the window that video covers. An Android manifest left by an unreachable recording is retired on the next start once its recorders are proven gone; one still owned refuses with non-retriable DEVICE_IN_USE and reason native_recovery_evidence_open naming the session to run record stop for, and a recorder that is still writing an artifact refuses with DEVICE_IN_USE and reason native_recording_artifact_claimed, which clears itself once that recorder ends at the 180s limit. HarmonyOS supports whole-screen recording on physical devices only: use --scope device/system; --fps, --quality, and --hide-touches are unsupported. Use --quality to choose medium or high export quality on supported backends. The touch overlay renders at most 30 frames a second, or at --fps when lower; a lower --fps makes record stop faster on a long recording, and an overlay export that runs past its budget returns the raw video with an overlayWarning. A watchOS simulator records the same way an iOS simulator does: the host runs simctl recordVideo, so the watch needs no runner recorder and the export keeps the resolution of the watch. An iOS simulator host recording lock returns non-retriable DEVICE_IN_USE with reason apple_simulator_recording_busy. Stop the recording in its owning session; if a dead recorder left the host locked, ask the host operator to restart the CoreSimulator stream service. A physical iPhone or iPad on a USB cable of this Mac records the USB screen-capture source of the device near 60 fps when both recording transports belong to this host; otherwise it records runner screenshots (help physical-device). A USB capture recording learns the capture source of a device when every other device with its name has a learned source and the store in ~/.agent-device can be written, and later recordings of that device open that source while it has the device name, and otherwise match by name; only a newer exact match replaces what was learned. When USB capture cannot record, before its first frame, the runner records instead and recorderFallbackReason names why: ios_usb_capture_camera_access_not_authorized (agent-device never asks for camera access), ios_usb_capture_device_name_shared (no capture source is learned for the device, and another Apple device in the inventory of the daemon, cabled or wireless, that has no learned source, or another USB capture source on this Mac that is not learned for another device, has the name, or the inventory could not be read), ios_usb_capture_source_of_another_device (no capture source is learned for the device, and another device learned the capture source that matched its name while it started), ios_usb_capture_device_not_found (neither the source learned for the device nor a source with the device name appeared; the learned source is kept), ios_usb_capture_no_frames (screen asleep or locked), or ios_usb_capture_start_busy (another USB capture recording on this Mac, of any user, held the host-wide start lock). USB capture fails the start with ios_usb_capture_start_lock_unusable (another account owns the start lock file and does not let this user read it). On any backend, record start first settles the open recording records on its device that it would refuse on and whose session this daemon no longer holds: it finishes each one as its own record stop would, so the export lands at the output path of that recording and a later record stop in that session returns it, and runs the exact-owner recovery a daemon restart runs, which discards what that recording left, only for a record that cannot finish. A record it cannot confirm cleaned, or one whose session is still held, refuses the start with reason cleanup-unconfirmed and names that session: stop or close it, then retry. A record that another device left under the same session name is never settled from this device: the start refuses and names that device, so stop it in that session or record under another session name. A record stop that cannot produce its export keeps what a retry reads back — on Android the device-side artifact and the native manifest — leaves the recording manifest of that session open, and returns its own error, so retry record stop in that session; while this daemon holds that session, only closing it disposes them, and once it does not, the next record start on that device settles them as described above. Every stopped recording also reports what became of its recorder and of the file that recorder writes to: recorder is confirmed, or lost when the session holding it died, and nativePathDisposition is retirable while that file still owes a removal or retired once its removal was verified. Both are optional disclosures, not failures; ADR 0024 declares further states (unconfirmed, pending) for the steps that gain those probes, and no stop reports them yet. record contact-sheet [--out ] is a local report over a file you already exported: it decodes frames out of that MP4 and writes one PNG holding the cells where the screen visibly changed, each labeled with its elapsed time on the clip timeline. It needs no session and no device, rebuilds any past recording, and works for every backend that exports MP4; a WebM recording is refused with reason contact_sheet_container_unsupported. The sample grid is bounded and spread across the whole clip, so it reports coverage rather than a review: a flash that opens and closes entirely between two sample times is not in the sheet, which is why the result also reports how many times it sampled and how many frames came back. Frame decoding is Apple AVFoundation tooling, so the command runs only on macOS hosts and refuses elsewhere with reason contact_sheet_unsupported_host.', }, metadata: recordCommandMetadata, run: (client, input) => client.recording.record(input as RecordOptions), diff --git a/packages/contracts/src/screen-recording-runtime-host.ts b/packages/contracts/src/screen-recording-runtime-host.ts index 78b003b6ed9..baf4766e1ee 100644 --- a/packages/contracts/src/screen-recording-runtime-host.ts +++ b/packages/contracts/src/screen-recording-runtime-host.ts @@ -53,7 +53,7 @@ export type ApplePhysicalDeviceRecorder = 'runner' | 'usb-capture'; * records instead, and the recording result names the reason. */ export const IOS_USB_CAPTURE_FALLBACK_REASONS = { - // No USB screen-capture source with the device name appeared on the host. + // Neither the USB screen-capture source learned for the device nor another source with the device name appeared on the host. deviceNotFound: { reason: 'ios_usb_capture_device_not_found' }, // The capture source opened but sent no frame before the first-frame timeout. noFrames: { reason: 'ios_usb_capture_no_frames' }, @@ -61,8 +61,10 @@ export const IOS_USB_CAPTURE_FALLBACK_REASONS = { cameraAccessNotAuthorized: { reason: 'ios_usb_capture_camera_access_not_authorized' }, // Another USB capture recording on this Mac, of any user, held the start lock for the whole lock timeout. startBusy: { reason: 'ios_usb_capture_start_busy' }, - // Another Apple device in the daemon's inventory, cabled or wireless, has the device name. + // No capture source is learned for the device, and the device name is not unique among the unlearned: another Apple device in the daemon's inventory, cabled or wireless, with no learned source, or another USB capture source on this Mac not learned for another device, has it, or the inventory could not be read. deviceNameShared: { reason: 'ios_usb_capture_device_name_shared' }, + // Another Apple device learned the capture source that matched the device name while this start ran. + sourceOfAnotherDevice: { reason: 'ios_usb_capture_source_of_another_device' }, } as const satisfies ReasonTable<'record'>; export type IosUsbCaptureFallbackReason = diff --git a/packages/host-swift/src/recording-swift-sources.ts b/packages/host-swift/src/recording-swift-sources.ts index 452d1239f05..ea3b9997ca3 100644 --- a/packages/host-swift/src/recording-swift-sources.ts +++ b/packages/host-swift/src/recording-swift-sources.ts @@ -29,6 +29,6 @@ export const RECORDING_FRAMES_SOURCES: readonly EmbeddedSwiftSource[] = [ export const IOS_USB_CAPTURE_SOURCES: readonly EmbeddedSwiftSource[] = [ { fileName: 'ios-usb-capture.swift', - text: 'import AVFoundation\nimport CoreMediaIO\nimport Foundation\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nenum CaptureExit: Int32 {\n case invalidArguments = 2\n case deviceNotFound = 3\n case deviceAmbiguous = 4\n case noFrames = 5\n case permissionDenied = 6\n case interrupted = 7\n case startFailed = 8\n case startBusy = 9\n case writeFailed = 10\n case startLockUnusable = 11\n}\n\nenum FinishOutcome {\n case finished\n case noFrames\n case writerFailed\n}\n\nstruct CaptureOptions {\n let deviceName: String\n let outputURL: URL\n let startLockPath: String\n let deviceTimeout: TimeInterval\n let firstFrameTimeout: TimeInterval\n let startLockTimeout: TimeInterval\n}\n\n\n\nfunc report(_ message: String) {\n fputs(message + "\\n", stderr)\n}\n\nfunc fail(_ code: CaptureExit, _ message: String) -> Never {\n report(message)\n exit(code.rawValue)\n}\n\nfunc parseOptions(_ arguments: [String]) -> CaptureOptions {\n var values: [String: String] = [:]\n var index = 1\n while index < arguments.count {\n let key = arguments[index]\n guard key.hasPrefix("--"), index + 1 < arguments.count else {\n fail(.invalidArguments, "invalid argument: \\(key)")\n }\n values[key] = arguments[index + 1]\n index += 2\n }\n guard let name = values["--device-name"], !name.isEmpty,\n let output = values["--output"], !output.isEmpty,\n let lockPath = values["--start-lock-path"], lockPath.hasPrefix("/")\n else {\n fail(.invalidArguments, "--device-name, --output and an absolute --start-lock-path are required")\n }\n func milliseconds(_ key: String, _ fallback: Double) -> TimeInterval {\n guard let text = values[key] else { return fallback / 1000 }\n guard let value = Double(text), value > 0 else { fail(.invalidArguments, "invalid \\(key)") }\n return value / 1000\n }\n return CaptureOptions(\n deviceName: name,\n outputURL: URL(fileURLWithPath: output),\n startLockPath: lockPath,\n deviceTimeout: milliseconds("--device-timeout-ms", 10_000),\n firstFrameTimeout: milliseconds("--first-frame-timeout-ms", 10_000),\n startLockTimeout: milliseconds("--start-lock-timeout-ms", 25_000)\n )\n}\n\n\n\n\n\nfinal class StartLock {\n private var descriptor: Int32 = -1\n\n func acquire(at path: String, within timeout: TimeInterval) {\n let directory = (path as NSString).deletingLastPathComponent\n var directoryStatus = stat()\n guard lstat(directory, &directoryStatus) == 0,\n directoryStatus.st_mode & S_IFMT == S_IFDIR,\n directoryStatus.st_uid == 0,\n directoryStatus.st_mode & S_ISVTX != 0\n else {\n fail(.startFailed, "the start lock directory \\(directory) is not a root-owned sticky directory")\n }\n let opened = openLockFile(path)\n var fileStatus = stat()\n\n guard fstat(opened, &fileStatus) == 0, fileStatus.st_mode & S_IFMT == S_IFREG,\n fileStatus.st_nlink == 1\n else {\n fail(.startLockUnusable, "the start lock \\(path) is not a regular file with one link")\n }\n let deadline = Date().addingTimeInterval(timeout)\n while flock(opened, LOCK_EX | LOCK_NB) != 0 {\n if Date() >= deadline {\n fail(.startBusy, "another USB capture held the start lock for \\(Int(timeout * 1000))ms")\n }\n usleep(50_000)\n }\n descriptor = opened\n }\n\n\n\n private func openLockFile(_ path: String) -> Int32 {\n let flags = O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK\n while true {\n let created = open(path, flags | O_CREAT | O_EXCL, 0o644)\n if created >= 0 {\n\n guard fchmod(created, 0o644) == 0 else { failToOpen(path, errno) }\n return created\n }\n guard errno == EEXIST else { failToOpen(path, errno) }\n let existing = open(path, flags)\n if existing >= 0 { return existing }\n guard errno == ENOENT else { failToOpen(path, errno) }\n }\n }\n\n private func failToOpen(_ path: String, _ code: Int32) -> Never {\n let message = "could not open the start lock \\(path): \\(String(cString: strerror(code)))"\n switch code {\n case EACCES, EPERM, ELOOP: fail(.startLockUnusable, message)\n default: fail(.startFailed, message)\n }\n }\n\n func release() {\n guard descriptor >= 0 else { return }\n flock(descriptor, LOCK_UN)\n close(descriptor)\n descriptor = -1\n }\n}\n\n\nfunc allowScreenCaptureDevices() {\n var address = CMIOObjectPropertyAddress(\n mSelector: CMIOObjectPropertySelector(kCMIOHardwarePropertyAllowScreenCaptureDevices),\n mScope: CMIOObjectPropertyScope(kCMIOObjectPropertyScopeGlobal),\n mElement: CMIOObjectPropertyElement(kCMIOObjectPropertyElementMain)\n )\n var allow: UInt32 = 1\n let status = CMIOObjectSetPropertyData(\n CMIOObjectID(kCMIOObjectSystemObject), &address, 0, nil,\n UInt32(MemoryLayout.size), &allow)\n guard status == noErr else {\n fail(.startFailed, "macOS refused to expose USB screen-capture devices (OSStatus \\(status))")\n }\n}\n\n\nfunc ensureCameraAccess() {\n guard AVCaptureDevice.authorizationStatus(for: .video) == .authorized else {\n fail(.permissionDenied, "macOS camera access is not authorized")\n }\n}\n\nfunc findCaptureDevice(named name: String, within timeout: TimeInterval) -> AVCaptureDevice {\n let deadline = Date().addingTimeInterval(timeout)\n while true {\n let matches = AVCaptureDevice.DiscoverySession(\n deviceTypes: [.external], mediaType: .muxed, position: .unspecified\n ).devices.filter { $0.localizedName == name }\n if matches.count > 1 {\n fail(.deviceAmbiguous, "\\(matches.count) USB capture devices are named \\(name)")\n }\n if let device = matches.first { return device }\n if Date() >= deadline {\n fail(.deviceNotFound, "no USB capture device named \\(name) appeared")\n }\n RunLoop.current.run(until: Date().addingTimeInterval(0.25))\n }\n}\n\n\nfinal class CaptureWriter: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {\n let queue = DispatchQueue(label: "agent-device.ios-usb-capture")\n private let outputURL: URL\n private let startLock: StartLock\n private var writer: AVAssetWriter?\n private var input: AVAssetWriterInput?\n private var dimensions = CMVideoDimensions(width: 0, height: 0)\n private var framesWritten = 0\n private var framesResized = 0\n private var framesLate = 0\n private var finished = false\n\n init(outputURL: URL, startLock: StartLock) {\n self.outputURL = outputURL\n self.startLock = startLock\n }\n\n var hasRecorded: Bool { framesWritten > 0 }\n\n func captureOutput(\n _ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer,\n from connection: AVCaptureConnection\n ) {\n if finished { return }\n guard let format = CMSampleBufferGetFormatDescription(sampleBuffer) else { return }\n let frameDimensions = CMVideoFormatDescriptionGetDimensions(format)\n if writer == nil {\n startWriting(dimensions: frameDimensions, at: sampleBuffer)\n startLock.release()\n }\n guard let input else { return }\n\n guard frameDimensions.width == dimensions.width, frameDimensions.height == dimensions.height\n else {\n framesResized += 1\n return\n }\n guard input.isReadyForMoreMediaData else {\n framesLate += 1\n return\n }\n guard input.append(sampleBuffer) else {\n let cause = writer?.error?.localizedDescription ?? "unknown"\n if framesWritten == 0 { fail(.startFailed, "the MP4 writer refused the first frame: \\(cause)") }\n fail(.writeFailed, "the MP4 writer failed after \\(framesWritten) frames: \\(cause)")\n }\n framesWritten += 1\n }\n\n private func startWriting(dimensions frameDimensions: CMVideoDimensions, at sampleBuffer: CMSampleBuffer) {\n let created: AVAssetWriter\n do {\n created = try AVAssetWriter(outputURL: outputURL, fileType: .mp4)\n } catch {\n fail(.startFailed, "could not create the MP4 writer: \\(error.localizedDescription)")\n }\n let settings: [String: Any] = [\n AVVideoCodecKey: AVVideoCodecType.h264,\n AVVideoWidthKey: Int(frameDimensions.width),\n AVVideoHeightKey: Int(frameDimensions.height),\n ]\n let videoInput = AVAssetWriterInput(mediaType: .video, outputSettings: settings)\n videoInput.expectsMediaDataInRealTime = true\n guard created.canAdd(videoInput) else { fail(.startFailed, "the MP4 writer refused H.264 video") }\n created.add(videoInput)\n guard created.startWriting() else {\n fail(.startFailed, "the MP4 writer did not start: \\(created.error?.localizedDescription ?? "unknown")")\n }\n created.startSession(atSourceTime: CMSampleBufferGetPresentationTimeStamp(sampleBuffer))\n writer = created\n input = videoInput\n dimensions = frameDimensions\n }\n\n\n func finish() -> FinishOutcome {\n finished = true\n guard let writer, let input, framesWritten > 0 else {\n writer?.cancelWriting()\n return .noFrames\n }\n input.markAsFinished()\n let done = DispatchSemaphore(value: 0)\n writer.finishWriting { done.signal() }\n done.wait()\n guard writer.status == .completed else {\n report("the MP4 writer failed: \\(writer.error?.localizedDescription ?? "unknown")")\n return .writerFailed\n }\n report(\n "recorded \\(framesWritten) frames at \\(dimensions.width)x\\(dimensions.height); "\n + "dropped \\(framesLate) the encoder was not ready for and \\(framesResized) of another size")\n return .finished\n }\n}\n\nsignal(SIGPIPE, SIG_IGN)\nlet options = parseOptions(CommandLine.arguments)\nsetvbuf(stdout, nil, _IOLBF, 0)\nensureCameraAccess()\nlet startLock = StartLock()\nstartLock.acquire(at: options.startLockPath, within: options.startLockTimeout)\nallowScreenCaptureDevices()\nlet device = findCaptureDevice(named: options.deviceName, within: options.deviceTimeout)\n\nlet session = AVCaptureSession()\nlet deviceInput: AVCaptureDeviceInput\ndo {\n deviceInput = try AVCaptureDeviceInput(device: device)\n} catch {\n fail(.startFailed, "could not open the USB capture device: \\(error.localizedDescription)")\n}\nguard session.canAddInput(deviceInput) else { fail(.startFailed, "the capture session refused the device") }\nsession.addInput(deviceInput)\n\nlet captureWriter = CaptureWriter(outputURL: options.outputURL, startLock: startLock)\nlet videoOutput = AVCaptureVideoDataOutput()\nvideoOutput.alwaysDiscardsLateVideoFrames = false\nvideoOutput.videoSettings = [\n kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange\n]\nvideoOutput.setSampleBufferDelegate(captureWriter, queue: captureWriter.queue)\nguard session.canAddOutput(videoOutput) else { fail(.startFailed, "the capture session refused video output") }\nsession.addOutput(videoOutput)\n\n\nfunc stopAndExit(_ finishedCode: Int32) -> Never {\n session.stopRunning()\n switch captureWriter.queue.sync(execute: { captureWriter.finish() }) {\n case .finished: exit(finishedCode)\n case .noFrames: fail(.noFrames, "the recording stopped before a frame was written")\n case .writerFailed: exit(CaptureExit.writeFailed.rawValue)\n }\n}\n\nsignal(SIGINT, SIG_IGN)\nsignal(SIGTERM, SIG_IGN)\nlet stopSources = [SIGINT, SIGTERM].map { number -> DispatchSourceSignal in\n let source = DispatchSource.makeSignalSource(signal: number, queue: .main)\n source.setEventHandler { stopAndExit(0) }\n source.resume()\n return source\n}\n\nlet interruptions = [\n AVCaptureSession.runtimeErrorNotification, AVCaptureDevice.wasDisconnectedNotification,\n].map { name in\n NotificationCenter.default.addObserver(forName: name, object: nil, queue: .main) { notification in\n if name == AVCaptureDevice.wasDisconnectedNotification, notification.object as? AVCaptureDevice != device { return }\n report("USB capture ended: \\(name.rawValue)")\n stopAndExit(CaptureExit.interrupted.rawValue)\n }\n}\n\nsession.startRunning()\nDispatchQueue.main.asyncAfter(deadline: .now() + options.firstFrameTimeout) {\n if !captureWriter.queue.sync(execute: { captureWriter.hasRecorded }) {\n session.stopRunning()\n fail(.noFrames, "no frame from the USB capture device was written; wake and unlock the device")\n }\n}\nprint("capturing \\(options.deviceName)")\nwithExtendedLifetime((stopSources, interruptions)) { dispatchMain() }\n', + text: 'import AVFoundation\nimport CoreMediaIO\nimport Foundation\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nenum CaptureExit: Int32 {\n case invalidArguments = 2\n case deviceNotFound = 3\n case deviceAmbiguous = 4\n case noFrames = 5\n case permissionDenied = 6\n case interrupted = 7\n case startFailed = 8\n case startBusy = 9\n case writeFailed = 10\n case startLockUnusable = 11\n}\n\nenum FinishOutcome {\n case finished\n case noFrames\n case writerFailed\n}\n\nstruct CaptureOptions {\n let deviceName: String\n let deviceUid: String?\n let excludedUids: Set\n let outputURL: URL\n let startLockPath: String\n let deviceTimeout: TimeInterval\n let firstFrameTimeout: TimeInterval\n let startLockTimeout: TimeInterval\n}\n\n\n\nfunc report(_ message: String) {\n fputs(message + "\\n", stderr)\n}\n\nfunc fail(_ code: CaptureExit, _ message: String) -> Never {\n report(message)\n exit(code.rawValue)\n}\n\nfunc parseOptions(_ arguments: [String]) -> CaptureOptions {\n var values: [String: String] = [:]\n var excludedUids: Set = []\n var index = 1\n while index < arguments.count {\n let key = arguments[index]\n guard key.hasPrefix("--"), index + 1 < arguments.count else {\n fail(.invalidArguments, "invalid argument: \\(key)")\n }\n if key == "--exclude-device-uid" {\n excludedUids.insert(arguments[index + 1])\n } else {\n values[key] = arguments[index + 1]\n }\n index += 2\n }\n guard let name = values["--device-name"], !name.isEmpty,\n let output = values["--output"], !output.isEmpty,\n let lockPath = values["--start-lock-path"], lockPath.hasPrefix("/")\n else {\n fail(.invalidArguments, "--device-name, --output and an absolute --start-lock-path are required")\n }\n let uid = values["--device-uid"]\n if let uid, uid.isEmpty { fail(.invalidArguments, "invalid --device-uid") }\n func milliseconds(_ key: String, _ fallback: Double) -> TimeInterval {\n guard let text = values[key] else { return fallback / 1000 }\n guard let value = Double(text), value > 0 else { fail(.invalidArguments, "invalid \\(key)") }\n return value / 1000\n }\n return CaptureOptions(\n deviceName: name,\n deviceUid: uid,\n excludedUids: excludedUids,\n outputURL: URL(fileURLWithPath: output),\n startLockPath: lockPath,\n deviceTimeout: milliseconds("--device-timeout-ms", 10_000),\n firstFrameTimeout: milliseconds("--first-frame-timeout-ms", 10_000),\n startLockTimeout: milliseconds("--start-lock-timeout-ms", 25_000)\n )\n}\n\n\n\n\n\nfinal class StartLock {\n private var descriptor: Int32 = -1\n\n func acquire(at path: String, within timeout: TimeInterval) {\n let directory = (path as NSString).deletingLastPathComponent\n var directoryStatus = stat()\n guard lstat(directory, &directoryStatus) == 0,\n directoryStatus.st_mode & S_IFMT == S_IFDIR,\n directoryStatus.st_uid == 0,\n directoryStatus.st_mode & S_ISVTX != 0\n else {\n fail(.startFailed, "the start lock directory \\(directory) is not a root-owned sticky directory")\n }\n let opened = openLockFile(path)\n var fileStatus = stat()\n\n guard fstat(opened, &fileStatus) == 0, fileStatus.st_mode & S_IFMT == S_IFREG,\n fileStatus.st_nlink == 1\n else {\n fail(.startLockUnusable, "the start lock \\(path) is not a regular file with one link")\n }\n let deadline = Date().addingTimeInterval(timeout)\n while flock(opened, LOCK_EX | LOCK_NB) != 0 {\n if Date() >= deadline {\n fail(.startBusy, "another USB capture held the start lock for \\(Int(timeout * 1000))ms")\n }\n usleep(50_000)\n }\n descriptor = opened\n }\n\n\n\n private func openLockFile(_ path: String) -> Int32 {\n let flags = O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK\n while true {\n let created = open(path, flags | O_CREAT | O_EXCL, 0o644)\n if created >= 0 {\n\n guard fchmod(created, 0o644) == 0 else { failToOpen(path, errno) }\n return created\n }\n guard errno == EEXIST else { failToOpen(path, errno) }\n let existing = open(path, flags)\n if existing >= 0 { return existing }\n guard errno == ENOENT else { failToOpen(path, errno) }\n }\n }\n\n private func failToOpen(_ path: String, _ code: Int32) -> Never {\n let message = "could not open the start lock \\(path): \\(String(cString: strerror(code)))"\n switch code {\n case EACCES, EPERM, ELOOP: fail(.startLockUnusable, message)\n default: fail(.startFailed, message)\n }\n }\n\n func release() {\n guard descriptor >= 0 else { return }\n flock(descriptor, LOCK_UN)\n close(descriptor)\n descriptor = -1\n }\n}\n\n\nfunc allowScreenCaptureDevices() {\n var address = CMIOObjectPropertyAddress(\n mSelector: CMIOObjectPropertySelector(kCMIOHardwarePropertyAllowScreenCaptureDevices),\n mScope: CMIOObjectPropertyScope(kCMIOObjectPropertyScopeGlobal),\n mElement: CMIOObjectPropertyElement(kCMIOObjectPropertyElementMain)\n )\n var allow: UInt32 = 1\n let status = CMIOObjectSetPropertyData(\n CMIOObjectID(kCMIOObjectSystemObject), &address, 0, nil,\n UInt32(MemoryLayout.size), &allow)\n guard status == noErr else {\n fail(.startFailed, "macOS refused to expose USB screen-capture devices (OSStatus \\(status))")\n }\n}\n\n\nfunc ensureCameraAccess() {\n guard AVCaptureDevice.authorizationStatus(for: .video) == .authorized else {\n fail(.permissionDenied, "macOS camera access is not authorized")\n }\n}\n\nfunc findCaptureDevice(_ options: CaptureOptions) -> AVCaptureDevice {\n let deadline = Date().addingTimeInterval(options.deviceTimeout)\n var learnedUid = options.deviceUid\n while true {\n let devices = AVCaptureDevice.DiscoverySession(\n deviceTypes: [.external], mediaType: .muxed, position: .unspecified\n ).devices\n if let uid = learnedUid, let learned = devices.first(where: { $0.uniqueID == uid }) {\n if learned.localizedName == options.deviceName { return learned }\n report("the USB capture device \\(uid) is named \\(learned.localizedName); matching by name")\n learnedUid = nil\n }\n let timedOut = Date() >= deadline\n if learnedUid == nil || timedOut {\n let matches = devices.filter {\n $0.localizedName == options.deviceName && !options.excludedUids.contains($0.uniqueID)\n }\n if matches.count > 1 {\n fail(.deviceAmbiguous, "\\(matches.count) USB capture devices are named \\(options.deviceName)")\n }\n if let device = matches.first { return device }\n }\n if timedOut {\n fail(.deviceNotFound, "no USB capture device for \\(options.deviceName) appeared")\n }\n RunLoop.current.run(until: Date().addingTimeInterval(0.25))\n }\n}\n\n\nfinal class CaptureWriter: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {\n let queue = DispatchQueue(label: "agent-device.ios-usb-capture")\n private let outputURL: URL\n private let startLock: StartLock\n private var writer: AVAssetWriter?\n private var input: AVAssetWriterInput?\n private var dimensions = CMVideoDimensions(width: 0, height: 0)\n private var framesWritten = 0\n private var framesResized = 0\n private var framesLate = 0\n private var finished = false\n\n init(outputURL: URL, startLock: StartLock) {\n self.outputURL = outputURL\n self.startLock = startLock\n }\n\n var hasRecorded: Bool { framesWritten > 0 }\n\n func captureOutput(\n _ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer,\n from connection: AVCaptureConnection\n ) {\n if finished { return }\n guard let format = CMSampleBufferGetFormatDescription(sampleBuffer) else { return }\n let frameDimensions = CMVideoFormatDescriptionGetDimensions(format)\n if writer == nil {\n startWriting(dimensions: frameDimensions, at: sampleBuffer)\n startLock.release()\n }\n guard let input else { return }\n\n guard frameDimensions.width == dimensions.width, frameDimensions.height == dimensions.height\n else {\n framesResized += 1\n return\n }\n guard input.isReadyForMoreMediaData else {\n framesLate += 1\n return\n }\n guard input.append(sampleBuffer) else {\n let cause = writer?.error?.localizedDescription ?? "unknown"\n if framesWritten == 0 { fail(.startFailed, "the MP4 writer refused the first frame: \\(cause)") }\n fail(.writeFailed, "the MP4 writer failed after \\(framesWritten) frames: \\(cause)")\n }\n framesWritten += 1\n }\n\n private func startWriting(dimensions frameDimensions: CMVideoDimensions, at sampleBuffer: CMSampleBuffer) {\n let created: AVAssetWriter\n do {\n created = try AVAssetWriter(outputURL: outputURL, fileType: .mp4)\n } catch {\n fail(.startFailed, "could not create the MP4 writer: \\(error.localizedDescription)")\n }\n let settings: [String: Any] = [\n AVVideoCodecKey: AVVideoCodecType.h264,\n AVVideoWidthKey: Int(frameDimensions.width),\n AVVideoHeightKey: Int(frameDimensions.height),\n ]\n let videoInput = AVAssetWriterInput(mediaType: .video, outputSettings: settings)\n videoInput.expectsMediaDataInRealTime = true\n guard created.canAdd(videoInput) else { fail(.startFailed, "the MP4 writer refused H.264 video") }\n created.add(videoInput)\n guard created.startWriting() else {\n fail(.startFailed, "the MP4 writer did not start: \\(created.error?.localizedDescription ?? "unknown")")\n }\n created.startSession(atSourceTime: CMSampleBufferGetPresentationTimeStamp(sampleBuffer))\n writer = created\n input = videoInput\n dimensions = frameDimensions\n }\n\n\n func finish() -> FinishOutcome {\n finished = true\n guard let writer, let input, framesWritten > 0 else {\n writer?.cancelWriting()\n return .noFrames\n }\n input.markAsFinished()\n let done = DispatchSemaphore(value: 0)\n writer.finishWriting { done.signal() }\n done.wait()\n guard writer.status == .completed else {\n report("the MP4 writer failed: \\(writer.error?.localizedDescription ?? "unknown")")\n return .writerFailed\n }\n report(\n "recorded \\(framesWritten) frames at \\(dimensions.width)x\\(dimensions.height); "\n + "dropped \\(framesLate) the encoder was not ready for and \\(framesResized) of another size")\n return .finished\n }\n}\n\nsignal(SIGPIPE, SIG_IGN)\nlet options = parseOptions(CommandLine.arguments)\nsetvbuf(stdout, nil, _IOLBF, 0)\nensureCameraAccess()\nlet startLock = StartLock()\nstartLock.acquire(at: options.startLockPath, within: options.startLockTimeout)\nallowScreenCaptureDevices()\nlet device = findCaptureDevice(options)\n\nlet session = AVCaptureSession()\nlet deviceInput: AVCaptureDeviceInput\ndo {\n deviceInput = try AVCaptureDeviceInput(device: device)\n} catch {\n fail(.startFailed, "could not open the USB capture device: \\(error.localizedDescription)")\n}\nguard session.canAddInput(deviceInput) else { fail(.startFailed, "the capture session refused the device") }\nsession.addInput(deviceInput)\n\nlet captureWriter = CaptureWriter(outputURL: options.outputURL, startLock: startLock)\nlet videoOutput = AVCaptureVideoDataOutput()\nvideoOutput.alwaysDiscardsLateVideoFrames = false\nvideoOutput.videoSettings = [\n kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange\n]\nvideoOutput.setSampleBufferDelegate(captureWriter, queue: captureWriter.queue)\nguard session.canAddOutput(videoOutput) else { fail(.startFailed, "the capture session refused video output") }\nsession.addOutput(videoOutput)\n\n\nfunc stopAndExit(_ finishedCode: Int32) -> Never {\n session.stopRunning()\n switch captureWriter.queue.sync(execute: { captureWriter.finish() }) {\n case .finished: exit(finishedCode)\n case .noFrames: fail(.noFrames, "the recording stopped before a frame was written")\n case .writerFailed: exit(CaptureExit.writeFailed.rawValue)\n }\n}\n\nsignal(SIGINT, SIG_IGN)\nsignal(SIGTERM, SIG_IGN)\nlet stopSources = [SIGINT, SIGTERM].map { number -> DispatchSourceSignal in\n let source = DispatchSource.makeSignalSource(signal: number, queue: .main)\n source.setEventHandler { stopAndExit(0) }\n source.resume()\n return source\n}\n\nlet interruptions = [\n AVCaptureSession.runtimeErrorNotification, AVCaptureDevice.wasDisconnectedNotification,\n].map { name in\n NotificationCenter.default.addObserver(forName: name, object: nil, queue: .main) { notification in\n if name == AVCaptureDevice.wasDisconnectedNotification, notification.object as? AVCaptureDevice != device { return }\n report("USB capture ended: \\(name.rawValue)")\n stopAndExit(CaptureExit.interrupted.rawValue)\n }\n}\n\nprint("capture-source-uid \\(device.uniqueID)")\nsession.startRunning()\nDispatchQueue.main.asyncAfter(deadline: .now() + options.firstFrameTimeout) {\n if !captureWriter.queue.sync(execute: { captureWriter.hasRecorded }) {\n session.stopRunning()\n fail(.noFrames, "no frame from the USB capture device was written; wake and unlock the device")\n }\n}\nwithExtendedLifetime((stopSources, interruptions)) { dispatchMain() }\n', }, ]; diff --git a/packages/host-swift/swift/ios-usb-capture.swift b/packages/host-swift/swift/ios-usb-capture.swift index 938fcdc1c4e..c8da9e5d5aa 100644 --- a/packages/host-swift/swift/ios-usb-capture.swift +++ b/packages/host-swift/swift/ios-usb-capture.swift @@ -5,13 +5,20 @@ import Foundation /// Records the screen of an iPhone or iPad connected by USB cable to an H.264 MP4, through the /// CoreMediaIO screen-capture device macOS exposes for it (the source QuickTime Player records). /// -/// Usage: `ios-usb-capture --device-name --output --start-lock-path +/// Usage: `ios-usb-capture --device-name [--device-uid ] +/// [--exclude-device-uid ]... --output --start-lock-path /// [--device-timeout-ms ] [--first-frame-timeout-ms ] [--start-lock-timeout-ms ]`. /// /// The writer creates the output file when the first frame arrives and appends that frame at once. A /// writer that refuses the first frame exits 8, so a file and a live helper are the readiness signal. -/// A capture device names only the device name, never its UDID, so the caller passes the name it -/// resolved and a name two connected devices share is refused rather than guessed. +/// A capture device names only the device name, never its UDID. A name match opens the one capture +/// device with the device name that no `--exclude-device-uid` names, and refuses a name that two such +/// devices share rather than guess. The caller excludes the sources it knows belong to other devices. +/// With `--device-uid`, the helper waits for the capture device with that `uniqueID` and opens it +/// only while it has the device name. When that device has another name, or does not appear within +/// the device timeout, the helper tries a name match instead. Before the capture session starts, so +/// before the first frame, the helper prints `capture-source-uid ` on stdout for the +/// capture device that it opened. /// /// Two helpers that discover and open capture devices at the same time can each receive the other /// device's frames. With two iPhones connected, 4 of 6 simultaneous starts recorded the wrong phone @@ -23,8 +30,9 @@ import Foundation /// SIGINT or SIGTERM ends the helper by that signal. Exit codes: /// - 0: SIGINT or SIGTERM arrived after recording began; the file is finished. /// - 2: invalid arguments. -/// - 3: no capture device with that name appeared within the device timeout. -/// - 4: more than one capture device has that name. +/// - 3: no capture device with that `uniqueID` and name, and none that a name match finds, appeared +/// within the device timeout. +/// - 4: a name match found more than one capture device that is not excluded with that name. /// - 5: no frame was written within the first-frame timeout or before SIGINT or SIGTERM; no file is usable. /// - 6: macOS camera access is not authorized for the process that launched the recorder. The helper /// checks before anything else and never asks for access. @@ -57,6 +65,8 @@ enum FinishOutcome { struct CaptureOptions { let deviceName: String + let deviceUid: String? + let excludedUids: Set let outputURL: URL let startLockPath: String let deviceTimeout: TimeInterval @@ -77,13 +87,18 @@ func fail(_ code: CaptureExit, _ message: String) -> Never { func parseOptions(_ arguments: [String]) -> CaptureOptions { var values: [String: String] = [:] + var excludedUids: Set = [] var index = 1 while index < arguments.count { let key = arguments[index] guard key.hasPrefix("--"), index + 1 < arguments.count else { fail(.invalidArguments, "invalid argument: \(key)") } - values[key] = arguments[index + 1] + if key == "--exclude-device-uid" { + excludedUids.insert(arguments[index + 1]) + } else { + values[key] = arguments[index + 1] + } index += 2 } guard let name = values["--device-name"], !name.isEmpty, @@ -92,6 +107,8 @@ func parseOptions(_ arguments: [String]) -> CaptureOptions { else { fail(.invalidArguments, "--device-name, --output and an absolute --start-lock-path are required") } + let uid = values["--device-uid"] + if let uid, uid.isEmpty { fail(.invalidArguments, "invalid --device-uid") } func milliseconds(_ key: String, _ fallback: Double) -> TimeInterval { guard let text = values[key] else { return fallback / 1000 } guard let value = Double(text), value > 0 else { fail(.invalidArguments, "invalid \(key)") } @@ -99,6 +116,8 @@ func parseOptions(_ arguments: [String]) -> CaptureOptions { } return CaptureOptions( deviceName: name, + deviceUid: uid, + excludedUids: excludedUids, outputURL: URL(fileURLWithPath: output), startLockPath: lockPath, deviceTimeout: milliseconds("--device-timeout-ms", 10_000), @@ -199,18 +218,30 @@ func ensureCameraAccess() { } } -func findCaptureDevice(named name: String, within timeout: TimeInterval) -> AVCaptureDevice { - let deadline = Date().addingTimeInterval(timeout) +func findCaptureDevice(_ options: CaptureOptions) -> AVCaptureDevice { + let deadline = Date().addingTimeInterval(options.deviceTimeout) + var learnedUid = options.deviceUid while true { - let matches = AVCaptureDevice.DiscoverySession( + let devices = AVCaptureDevice.DiscoverySession( deviceTypes: [.external], mediaType: .muxed, position: .unspecified - ).devices.filter { $0.localizedName == name } - if matches.count > 1 { - fail(.deviceAmbiguous, "\(matches.count) USB capture devices are named \(name)") + ).devices + if let uid = learnedUid, let learned = devices.first(where: { $0.uniqueID == uid }) { + if learned.localizedName == options.deviceName { return learned } + report("the USB capture device \(uid) is named \(learned.localizedName); matching by name") + learnedUid = nil + } + let timedOut = Date() >= deadline + if learnedUid == nil || timedOut { + let matches = devices.filter { + $0.localizedName == options.deviceName && !options.excludedUids.contains($0.uniqueID) + } + if matches.count > 1 { + fail(.deviceAmbiguous, "\(matches.count) USB capture devices are named \(options.deviceName)") + } + if let device = matches.first { return device } } - if let device = matches.first { return device } - if Date() >= deadline { - fail(.deviceNotFound, "no USB capture device named \(name) appeared") + if timedOut { + fail(.deviceNotFound, "no USB capture device for \(options.deviceName) appeared") } RunLoop.current.run(until: Date().addingTimeInterval(0.25)) } @@ -320,7 +351,7 @@ ensureCameraAccess() let startLock = StartLock() startLock.acquire(at: options.startLockPath, within: options.startLockTimeout) allowScreenCaptureDevices() -let device = findCaptureDevice(named: options.deviceName, within: options.deviceTimeout) +let device = findCaptureDevice(options) let session = AVCaptureSession() let deviceInput: AVCaptureDeviceInput @@ -371,6 +402,7 @@ let interruptions = [ } } +print("capture-source-uid \(device.uniqueID)") session.startRunning() DispatchQueue.main.asyncAfter(deadline: .now() + options.firstFrameTimeout) { if !captureWriter.queue.sync(execute: { captureWriter.hasRecorded }) { @@ -378,5 +410,4 @@ DispatchQueue.main.asyncAfter(deadline: .now() + options.firstFrameTimeout) { fail(.noFrames, "no frame from the USB capture device was written; wake and unlock the device") } } -print("capturing \(options.deviceName)") withExtendedLifetime((stopSources, interruptions)) { dispatchMain() } diff --git a/scripts/capability-matrix/annotations.ts b/scripts/capability-matrix/annotations.ts index b94e448a758..3f8aa7c81f6 100644 --- a/scripts/capability-matrix/annotations.ts +++ b/scripts/capability-matrix/annotations.ts @@ -313,7 +313,7 @@ export const MATRIX_SECTIONS: readonly MatrixSection[] = [ label: 'Screen recording', commands: ['record'], link: docs('commands', 'media-and-logs'), - note: 'A cabled iPhone or iPad records its USB screen-capture source near 60 fps when the app that runs the daemon has macOS camera access and no other Apple device has its name, and falls back to runner screenshots before its first frame otherwise: no audio, the screen must be awake and unlocked, and frames are dropped while the screen is turned away from the orientation it started in. Otherwise an iOS physical device records runner screenshots, not a native video stream: no audio, and dropped frames are expected. An Android clip covers 180 seconds, and a longer recording arrives as chunks.', + note: 'A cabled iPhone or iPad records its USB screen-capture source near 60 fps when the app that runs the daemon has macOS camera access and its capture source appears. agent-device learns the source of a device on a recording when every other Apple device and capture source with the device name is learned for another device; later recordings of that device open the learned source while it has the device name, and otherwise match by name; only a newer exact match replaces what was learned. It falls back to runner screenshots before its first frame otherwise: no audio, the screen must be awake and unlocked, and frames are dropped while the screen is turned away from the orientation it started in. Otherwise an iOS physical device records runner screenshots, not a native video stream: no audio, and dropped frames are expected. An Android clip covers 180 seconds, and a longer recording arrives as chunks.', }, { id: 'logs', diff --git a/scripts/layering/root-module-zones.ts b/scripts/layering/root-module-zones.ts index 0f330ab350a..f18aad01f2f 100644 --- a/scripts/layering/root-module-zones.ts +++ b/scripts/layering/root-module-zones.ts @@ -92,6 +92,7 @@ export const ROOT_MODULE_ZONES: Readonly> = { 'src/platform-runtime-screen-recording-apple-simulator-host.ts', 'src/platform-runtime-screen-recording-apple-transport.ts', 'src/platform-runtime-screen-recording-apple-usb-capture-host.ts', + 'src/platform-runtime-screen-recording-apple-usb-capture-sources.ts', 'src/platform-runtime-screen-recording-finalizer-host.ts', 'src/platform-runtime-screen-recording-harmony-host.ts', 'src/platform-runtime-screen-recording-host.ts', diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 98add812905..c43458fadbb 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -412,7 +412,8 @@ iOS runner transport: iOS physical-device recording: A CoreDevice iPhone or iPad on a USB cable of this Mac records its USB screen-capture source (the source QuickTime Player records) at native resolution near 60 fps, video only, when the recording transports are this host's own. Otherwise it records runner screenshots at a low frame rate. record start and record stop --json name the recorder in recordingBackend. - When USB capture cannot record, the runner records instead, and recorderFallbackReason names why: ios_usb_capture_camera_access_not_authorized, ios_usb_capture_device_name_shared (another Apple device in the daemon's inventory, cabled or wireless, or another USB capture source on this Mac has the name; give each device a unique name in Settings > General > About > Name), ios_usb_capture_device_not_found, ios_usb_capture_no_frames (screen asleep or locked), or ios_usb_capture_start_busy. This happens only before the first frame. After it the recorder never changes. + A capture source carries the device name, not its UDID. A device that has no learned source matches its source by name, among the capture sources not learned for another device. When every other Apple device in the daemon's inventory with that name has a learned source, the match is exact: the recording learns the uniqueID of the source and records it in ~/.agent-device/ios-usb-capture-sources. The record is a hint: when that directory cannot be written, nothing is learned and later recordings match by name again. Later recordings of a learned device open its source by uniqueID while that source has the device name, whatever other devices are named, and do not read the device inventory. When the learned source does not appear or has another name, the recording matches by name instead, and only a newer exact match replaces the record. So devices that share a name all keep USB capture when you connect and record them one at a time. Two devices that share a name and have no learned source cannot be told apart: give one of them a unique name for one recording. + When USB capture cannot record, the runner records instead, and recorderFallbackReason names why: ios_usb_capture_camera_access_not_authorized, ios_usb_capture_device_name_shared (no capture source is learned for the device, and another Apple device in the daemon's inventory, cabled or wireless, that has no learned source, or another USB capture source on this Mac that is not learned for another device, has the name, so give the device a unique name in Settings > General > About > Name for one recording; or the daemon could not read its device inventory, so check agent-device devices and retry), ios_usb_capture_source_of_another_device (no capture source is learned for the device, and another device learned the capture source that matched its name while it started; retry record start), ios_usb_capture_device_not_found (when a source is learned for the device, neither it nor another source with the device name appeared, and the record is kept for the next start), ios_usb_capture_no_frames (screen asleep or locked), or ios_usb_capture_start_busy. This happens only before the first frame. After it the recorder never changes. agent-device never asks for camera access. Allow it for the app that runs agent-device in System Settings > Privacy & Security > Camera, then restart the daemon. The first frame can take several seconds, and up to about 10 s after the previous USB capture recording of the device stopped. USB capture recordings start one at a time on this Mac, for every daemon and every user, through the start lock /private/tmp/agent-device-ios-usb-capture-start.lock. Another user's recording holds it until its first frame. A lock file that another account owns and does not let this user read fails with ios_usb_capture_start_lock_unusable; ask that account or an administrator to remove the file. diff --git a/src/platform-runtime-screen-recording-apple-usb-capture-host.test.ts b/src/platform-runtime-screen-recording-apple-usb-capture-host.test.ts index 11ca2f0ab81..1e3ef21854c 100644 --- a/src/platform-runtime-screen-recording-apple-usb-capture-host.test.ts +++ b/src/platform-runtime-screen-recording-apple-usb-capture-host.test.ts @@ -1,29 +1,41 @@ import fs from 'node:fs'; import path from 'node:path'; +import { PassThrough } from 'node:stream'; import { fileURLToPath } from 'node:url'; import { withTestDeviceInventory } from '@agent-device/device-selection/inventory-gateways-fixtures'; import { withCommandExecutorOverride } from '@agent-device/host-kit/command'; import type { DeviceInfo } from '@agent-device/kernel/device'; -import { beforeEach, expect, test, vi } from 'vitest'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { afterEach, beforeEach, expect, test, vi } from 'vitest'; import { - deviceNameIsUnique, + inventoryNamesakes, selectApplePhysicalDeviceRecorder, startAppleUsbCaptureRecording, UsbCaptureUnavailable, usbCaptureStartError, } from './platform-runtime-screen-recording-apple-usb-capture-host.ts'; +import { rememberCaptureSourceUid } from './platform-runtime-screen-recording-apple-usb-capture-sources.ts'; const hostRecorder = vi.hoisted(() => ({ startAppleHostRecorder: vi.fn() })); +const swiftHelper = vi.hoisted(() => ({ startSwiftHelper: vi.fn() })); vi.mock('./platform-runtime-screen-recording-apple-host-recorder.ts', () => hostRecorder); vi.mock('@agent-device/host-swift/swift-cache', () => ({ compileSwiftSources: async () => '/cache/ios-usb-capture', - startSwiftHelper: async () => { - throw new Error('the host recorder is faked'); - }, + startSwiftHelper: swiftHelper.startSwiftHelper, })); +let home: string; + beforeEach(() => { hostRecorder.startAppleHostRecorder.mockReset(); + swiftHelper.startSwiftHelper.mockReset(); + // The capture source store lives under the home directory. + home = mkdtempForTestSync('usb-capture-sources-'); + vi.stubEnv('HOME', home); +}); + +afterEach(() => { + vi.unstubAllEnvs(); }); const HELPER_SOURCE = path.resolve( @@ -127,19 +139,19 @@ test('an iPhone on no USB cable of this host selects the runner', async () => { ).resolves.toBe('runner'); }); -async function uniqueIn(target: DeviceInfo, inventory: readonly DeviceInfo[]) { +async function namesakesIn(target: DeviceInfo, inventory: readonly DeviceInfo[]) { return await withTestDeviceInventory( { local: async () => inventory }, - async () => await deviceNameIsUnique(target), + async () => await inventoryNamesakes(target), ); } -test('a name that a cabled and a wireless device share is not unique', async () => { +test('a cabled and a wireless device with one name are namesakes, and the host Mac is not', async () => { const cabled = iphone('00008130-001824261190001C'); const wireless = iphone('00008110-000A796C1104801E'); - await expect(uniqueIn(cabled, [cabled, wireless, HOST_MAC])).resolves.toBe(false); - await expect(uniqueIn(cabled, [cabled, HOST_MAC])).resolves.toBe(true); - await expect(uniqueIn(cabled, [wireless])).resolves.toBe(false); + await expect(namesakesIn(cabled, [cabled, wireless, HOST_MAC])).resolves.toEqual([wireless]); + await expect(namesakesIn(cabled, [cabled, HOST_MAC])).resolves.toEqual([]); + await expect(namesakesIn(cabled, [wireless])).resolves.toBeUndefined(); }); test('a capture whose name the inventory shows twice is discarded so the runner records', async () => { @@ -232,3 +244,318 @@ test('two capture sources with the device name fall back to the runner without t reason: 'ios_usb_capture_device_name_shared', }); }); + +const SOURCE_A = '5F5AED56-0000-4000-8000-00000000000A'; + +/** A helper whose stdout carries `stdout`, as the Swift helper prints it before its first frame. */ +function helperPrinting(stdout: string) { + const stream = new PassThrough(); + stream.end(stdout); + return { child: { pid: 4242, kill: vi.fn(), stdout: stream }, wait: new Promise(() => {}) }; +} + +/** A recording process whose helper exits only when it is terminated. */ +function liveRecording() { + let exit = () => {}; + const wait = new Promise((resolve) => { + exit = () => resolve({ stdout: '', stderr: '', exitCode: 0 }); + }); + return { markers: [], wait, terminate: vi.fn(async () => exit()) }; +} + +/** The next host recorder start launches the helper, which prints `stdout`, then records. */ +function recordsPrinting(stdout: string) { + const process = liveRecording(); + swiftHelper.startSwiftHelper.mockResolvedValueOnce(helperPrinting(stdout)); + hostRecorder.startAppleHostRecorder.mockImplementationOnce( + async ({ start }: { start: () => Promise }) => { + await start(); + return process; + }, + ); + return process; +} + +/** The next host recorder start launches the helper, which exits 3 before its first frame. */ +function findsNoSource() { + swiftHelper.startSwiftHelper.mockResolvedValueOnce(helperPrinting('')); + hostRecorder.startAppleHostRecorder.mockImplementationOnce( + async ({ + start, + startError, + }: { + start: () => Promise; + startError: typeof usbCaptureStartError; + }) => { + await start(); + throw startError({ + kind: 'exited', + result: { stdout: '', stderr: 'no USB capture device appeared', exitCode: 3 }, + }); + }, + ); +} + +function helperArgs(call: number): readonly string[] { + return swiftHelper.startSwiftHelper.mock.calls[call]![2] as readonly string[]; +} + +async function startIn(target: DeviceInfo, inventory: () => Promise) { + return await withTestDeviceInventory( + { local: inventory }, + async () => + await startAppleUsbCaptureRecording({ env: {}, cwd: '/' }, target, '/tmp/usb-capture.mp4'), + ); +} + +test('an exact name match learns its source, and the next start opens that source without the inventory', async () => { + const cabled = iphone('00008130-000000000000A01E'); + const inventory = vi.fn(async () => [cabled]); + + const learning = recordsPrinting(`capture-source-uid ${SOURCE_A}\n`); + await expect(startIn(cabled, inventory)).resolves.toEqual({ + status: 'recording', + process: learning, + }); + expect(helperArgs(0)).not.toContain('--device-uid'); + expect(inventory).toHaveBeenCalledOnce(); + const store = path.join(home, '.agent-device', 'ios-usb-capture-sources'); + const [record] = fs.readdirSync(store); + expect(fs.statSync(store).mode & 0o777).toBe(0o700); + expect(fs.statSync(path.join(store, record!)).mode & 0o777).toBe(0o600); + + const known = recordsPrinting(`capture-source-uid ${SOURCE_A}\n`); + await expect(startIn(cabled, inventory)).resolves.toEqual({ + status: 'recording', + process: known, + }); + expect(helperArgs(1)).toEqual(expect.arrayContaining(['--device-uid', SOURCE_A])); + expect(inventory).toHaveBeenCalledOnce(); +}); + +test('a name match whose helper reports no source keeps the recording and learns nothing', async () => { + const cabled = iphone('00008130-000000000000A02E'); + const inventory = async () => [cabled]; + const kept = recordsPrinting(''); + await expect(startIn(cabled, inventory)).resolves.toEqual({ status: 'recording', process: kept }); + + recordsPrinting(''); + await startIn(cabled, inventory); + expect(helperArgs(1)).not.toContain('--device-uid'); +}); + +test('a learned source that does not appear keeps its record for the next start', async () => { + const cabled = iphone('00008130-000000000000A03E'); + const inventory = vi.fn(async () => [cabled]); + recordsPrinting(`capture-source-uid ${SOURCE_A}\n`); + await startIn(cabled, inventory); + + findsNoSource(); + await expect(startIn(cabled, inventory)).resolves.toMatchObject({ + status: 'unavailable', + reason: 'ios_usb_capture_device_not_found', + message: expect.stringContaining('the learned source is kept'), + }); + expect(helperArgs(1)).toEqual(expect.arrayContaining(['--device-uid', SOURCE_A])); + + recordsPrinting(`capture-source-uid ${SOURCE_A}\n`); + await startIn(cabled, inventory); + expect(helperArgs(2)).toEqual(expect.arrayContaining(['--device-uid', SOURCE_A])); + expect(inventory).toHaveBeenCalledOnce(); +}); + +test('a known device whose helper matched another source by name keeps its record when the match is not exact', async () => { + const cabled = iphone('00008130-000000000000A12E'); + const unlearned = iphone('00008110-000000000000A12E'); + recordsPrinting(`capture-source-uid ${SOURCE_A}\n`); + await startIn(cabled, async () => [cabled]); + + const discarded = recordsPrinting(`capture-source-uid ${SOURCE_B}\n`); + await expect(startIn(cabled, async () => [cabled, unlearned])).resolves.toMatchObject({ + status: 'unavailable', + reason: 'ios_usb_capture_device_name_shared', + }); + expect(discarded.terminate).toHaveBeenCalledOnce(); + expect(storedUids()).toEqual([SOURCE_A]); +}); + +test('a known device whose helper matched another source by name replaces its record when the match is exact', async () => { + const cabled = iphone('00008130-000000000000A13E'); + recordsPrinting(`capture-source-uid ${SOURCE_A}\n`); + await startIn(cabled, async () => [cabled]); + + const replaced = recordsPrinting(`capture-source-uid ${SOURCE_B}\n`); + await expect(startIn(cabled, async () => [cabled])).resolves.toEqual({ + status: 'recording', + process: replaced, + }); + expect(helperArgs(1)).toEqual(expect.arrayContaining(['--device-uid', SOURCE_A])); + + recordsPrinting(''); + await startIn(cabled, async () => [cabled]); + expect(helperArgs(2)).toEqual(expect.arrayContaining(['--device-uid', SOURCE_B])); +}); + +/** The capture source `uniqueID` of every record in the store. */ +function storedUids(): string[] { + const store = path.join(home, '.agent-device', 'ios-usb-capture-sources'); + return fs + .readdirSync(store) + .map( + (name) => + (JSON.parse(fs.readFileSync(path.join(store, name), 'utf8')) as { captureUid: string }) + .captureUid, + ); +} + +test('a name match onto a source another device learned during the start is discarded so the runner records', async () => { + const learned = iphone('00008130-000000000000A04E'); + const other = iphone('00008110-000000000000A04E'); + recordsPrinting(`capture-source-uid ${SOURCE_A}\n`); + await startIn(learned, async () => [learned]); + fs.rmSync(path.join(home, '.agent-device'), { recursive: true }); + + // The other phone starts before the learned phone's record exists, so the helper excludes nothing. + const wrong = liveRecording(); + swiftHelper.startSwiftHelper.mockResolvedValueOnce( + helperPrinting(`capture-source-uid ${SOURCE_A}\n`), + ); + hostRecorder.startAppleHostRecorder.mockImplementationOnce( + async ({ start }: { start: () => Promise }) => { + await start(); + await rememberCaptureSourceUid(learned, SOURCE_A); + return wrong; + }, + ); + await expect(startIn(other, async () => [other])).resolves.toMatchObject({ + status: 'unavailable', + reason: 'ios_usb_capture_source_of_another_device', + }); + expect(wrong.terminate).toHaveBeenCalledOnce(); + expect(fs.readdirSync(path.join(home, '.agent-device', 'ios-usb-capture-sources'))).toHaveLength( + 1, + ); + + recordsPrinting(''); + await startIn(learned, async () => [learned]); + expect(helperArgs(2)).toEqual(expect.arrayContaining(['--device-uid', SOURCE_A])); +}); + +test('a capture source store that cannot be written keeps the recording', async () => { + const cabled = iphone('00008130-000000000000A05E'); + // A file where the store directory's parent belongs refuses every write. + fs.writeFileSync(path.join(home, '.agent-device'), ''); + const kept = recordsPrinting(`capture-source-uid ${SOURCE_A}\n`); + await expect(startIn(cabled, async () => [cabled])).resolves.toEqual({ + status: 'recording', + process: kept, + }); + + recordsPrinting(`capture-source-uid ${SOURCE_A}\n`); + await startIn(cabled, async () => [cabled]); + expect(helperArgs(1)).not.toContain('--device-uid'); +}); + +test('a helper that never reports its source keeps the recording and loses the stdout reader', async () => { + const cabled = iphone('00008130-000000000000A07E'); + const stdout = new PassThrough(); + const process = liveRecording(); + swiftHelper.startSwiftHelper.mockResolvedValueOnce({ + child: { pid: 4242, kill: vi.fn(), stdout }, + wait: new Promise(() => {}), + }); + hostRecorder.startAppleHostRecorder.mockImplementationOnce( + async ({ start }: { start: () => Promise }) => { + await start(); + return process; + }, + ); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + try { + const started = startIn(cabled, async () => [cabled]); + await vi.advanceTimersByTimeAsync(1_000); + await expect(started).resolves.toEqual({ status: 'recording', process }); + } finally { + vi.useRealTimers(); + } + expect(stdout.listenerCount('data')).toBe(0); + expect(fs.existsSync(path.join(home, '.agent-device', 'ios-usb-capture-sources'))).toBe(false); +}); + +const SOURCE_B = '8A8B74D1-0000-4000-8000-00000000000B'; + +test('a device whose namesakes all learned their sources excludes those sources and learns its own', async () => { + const learned = iphone('00008130-000000000000A08E'); + const added = iphone('00008130-000000000000B08E'); + recordsPrinting(`capture-source-uid ${SOURCE_A}\n`); + await startIn(learned, async () => [learned]); + + const kept = recordsPrinting(`capture-source-uid ${SOURCE_B}\n`); + await expect(startIn(added, async () => [learned, added])).resolves.toEqual({ + status: 'recording', + process: kept, + }); + expect(helperArgs(1)).toEqual(expect.arrayContaining(['--exclude-device-uid', SOURCE_A])); + + recordsPrinting(''); + await startIn(added, async () => [learned, added]); + expect(helperArgs(2)).toEqual(expect.arrayContaining(['--device-uid', SOURCE_B])); +}); + +test('a device with a namesake that learned no source still falls back to the runner', async () => { + const learned = iphone('00008130-000000000000A09E'); + const added = iphone('00008130-000000000000B09E'); + const unlearned = iphone('00008130-000000000000C09E'); + recordsPrinting(`capture-source-uid ${SOURCE_A}\n`); + await startIn(learned, async () => [learned]); + + const discarded = recordsPrinting(`capture-source-uid ${SOURCE_B}\n`); + await expect(startIn(added, async () => [learned, added, unlearned])).resolves.toMatchObject({ + status: 'unavailable', + reason: 'ios_usb_capture_device_name_shared', + }); + expect(discarded.terminate).toHaveBeenCalledOnce(); + expect(fs.readdirSync(path.join(home, '.agent-device', 'ios-usb-capture-sources'))).toHaveLength( + 1, + ); +}); + +test.each([ + ['another user owns', 'owner'], + ['another user can write', 'mode'], +] as const)( + 'a record that %s is ignored, and the next start learns over it', + async (_case, exposure) => { + const cabled = iphone( + exposure === 'owner' ? '00008130-000000000000A10E' : '00008130-000000000000A11E', + ); + const inventory = async () => [cabled]; + recordsPrinting(`capture-source-uid ${SOURCE_A}\n`); + await startIn(cabled, inventory); + const store = path.join(home, '.agent-device', 'ios-usb-capture-sources'); + const [name] = fs.readdirSync(store); + const record = path.join(store, name!); + fs.writeFileSync(record, fs.readFileSync(record, 'utf8').replace(SOURCE_A, SOURCE_B)); + + const realFstat = fs.fstatSync; + if (exposure === 'owner') { + vi.spyOn(fs, 'fstatSync').mockImplementation(((descriptor: number) => { + const stats = realFstat(descriptor); + return Object.assign(Object.create(Object.getPrototypeOf(stats) as object), stats, { + uid: stats.uid + 1, + }); + }) as typeof fs.fstatSync); + } else { + fs.chmodSync(record, 0o620); + } + try { + recordsPrinting(`capture-source-uid ${SOURCE_A}\n`); + await startIn(cabled, inventory); + } finally { + vi.restoreAllMocks(); + } + expect(helperArgs(1)).not.toContain('--device-uid'); + expect(fs.readFileSync(record, 'utf8')).toContain(SOURCE_A); + expect(fs.statSync(record).mode & 0o777).toBe(0o600); + }, +); diff --git a/src/platform-runtime-screen-recording-apple-usb-capture-host.ts b/src/platform-runtime-screen-recording-apple-usb-capture-host.ts index e81d8078839..e87c2178330 100644 --- a/src/platform-runtime-screen-recording-apple-usb-capture-host.ts +++ b/src/platform-runtime-screen-recording-apple-usb-capture-host.ts @@ -1,5 +1,7 @@ import fs from 'node:fs'; -import { execFailureDetails } from '@agent-device/host-kit/command'; +import type { Readable } from 'node:stream'; +import { execFailureDetails, type ExecBackgroundResult } from '@agent-device/host-kit/command'; +import { settleWithin } from '@agent-device/host-kit/settle-within'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import type { DeviceInfo } from '@agent-device/kernel/device'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; @@ -13,6 +15,13 @@ import { startAppleHostRecorder, type AppleHostRecorderExit, } from './platform-runtime-screen-recording-apple-host-recorder.ts'; +import { + captureSourceDeviceKey, + isCaptureSourceUid, + recallCaptureSourceUid, + recallOtherDeviceSources, + rememberCaptureSourceUid, +} from './platform-runtime-screen-recording-apple-usb-capture-sources.ts'; const LABEL = 'iOS USB screen capture'; const DEVICE_TIMEOUT_MS = 10_000; @@ -27,6 +36,11 @@ const START_LOCK_TIMEOUT_MS = DEVICE_TIMEOUT_MS + FIRST_FRAME_TIMEOUT_MS + 5_000 const READY_TIMEOUT_MS = START_LOCK_TIMEOUT_MS + DEVICE_TIMEOUT_MS + FIRST_FRAME_TIMEOUT_MS + 5_000; const COMPILE_TIMEOUT_MS = 180_000; const IOREG_TIMEOUT_MS = 5_000; +// The helper prints the source it opened before its capture session starts, so the line is on stdout +// long before the first frame makes the recording ready. This only bounds a line that never comes. +const SOURCE_UID_REPORT_TIMEOUT_MS = 1_000; +const SOURCE_UID_LINE = /^capture-source-uid (.+)$/; +const MAX_STDOUT_SCAN_CHARS = 4_096; // After a capture session closes, the device leaves screen-capture mode. A helper that starts within // about 4 s of the close never sees the capture source come back in its own process, and exits 3 // after its device timeout. One that starts 5 s or more after the close finds it. In either case the @@ -81,10 +95,17 @@ const EXIT_MEANINGS: Readonly> = { * Starts the helper and answers once it wrote its first frame. A helper that ends before its first frame * for a reason the runner recorder does not share answers `unavailable`, so the runner can record instead. * - * A capture source carries only the device name, so the recording is kept only when no other Apple - * device in the daemon's inventory, cabled or wireless, has that name. The inventory read takes about - * 2 s, so it runs while the helper starts, and only a helper that recorded waits for it. A capture of - * a shared name is discarded before it is returned, and the runner records instead. + * A capture source carries only the device name and a `uniqueID` that macOS assigns once per device + * per Mac. A device whose source was learned before opens that source while it has the device name, + * and the inventory is not read. When the learned source does not appear, or has another name, the + * helper matches by name instead, and the record stays until a newer exact match replaces it. + * + * A name match looks only at the sources not learned for another device. It is exact when every other + * Apple device in the daemon's inventory, cabled or wireless, with that name has a learned source: + * the one unlearned source with the name is then this device's. Only an exact match keeps the + * recording and learns its `uniqueID`, unless another device learned that source meanwhile. Otherwise + * the capture is discarded, and the runner records instead. The inventory read takes about 2 s, so a + * device with no learned source runs it while the helper starts. */ export async function startAppleUsbCaptureRecording( host: HostEnvironment, @@ -92,36 +113,165 @@ export async function startAppleUsbCaptureRecording( outputPath: string, signal?: AbortSignal, ): Promise { - // An inventory that cannot be read proves no name unique. - const nameIsUnique = deviceNameIsUnique(device).catch(() => false); + const [learnedUid, otherSources] = await Promise.all([ + recallCaptureSourceUid(device), + recallOtherDeviceSources(device), + ]); + let exactness: Promise | undefined; + const nameMatchIsExact = () => (exactness ??= namesakesAllLearned(device, otherSources)); + if (learnedUid === undefined) void nameMatchIsExact(); + const helperReport: { reader?: SourceUidReport } = {}; // A helper that failed or could not record answers at once: only a recording needs the name check. - const started = await startUsbCaptureHelper(host, device, outputPath, signal); - if (started.status === 'unavailable' || (await nameIsUnique)) return started; + const started = await startUsbCaptureHelper( + host, + device, + outputPath, + { learnedUid, excludedUids: [...new Set(otherSources.values())] }, + signal, + (helper) => { + helperReport.reader = readReportedSourceUid(helper.child.stdout); + }, + ); + // The reader holds listeners on the helper's stdout until it is stopped. + const reader = helperReport.reader; + if (started.status === 'unavailable') { + reader?.stop(); + if ( + learnedUid === undefined || + started.reason !== IOS_USB_CAPTURE_FALLBACK_REASONS.deviceNotFound.reason + ) { + return started; + } + return { + ...started, + message: + 'Neither the USB screen-capture source learned for this device nor another source with the device name appeared; the learned source is kept for the next start', + }; + } + const report = await settleWithin( + () => reader?.uid ?? Promise.resolve(undefined), + SOURCE_UID_REPORT_TIMEOUT_MS, + ); + reader?.stop(); + const uid = report.kind === 'settled' ? report.value : undefined; + // The helper opened the learned source only while it had the device name. + if (learnedUid !== undefined && uid === learnedUid) return started; + if (!(await nameMatchIsExact())) { + return await discardCapture(started, outputPath, { + reason: IOS_USB_CAPTURE_FALLBACK_REASONS.deviceNameShared.reason, + message: `Another Apple device of this daemon with no learned USB screen-capture source is also named ${device.name}, or the device inventory could not be read`, + }); + } + // A helper that reported no source keeps its exact match and teaches nothing. + if (uid === undefined) return started; + const learnedElsewhere = await recallOtherDeviceSources(device); + if ([...learnedElsewhere.values()].includes(uid)) { + return await discardCapture(started, outputPath, { + reason: IOS_USB_CAPTURE_FALLBACK_REASONS.sourceOfAnotherDevice.reason, + message: `The USB screen-capture source named ${device.name} is learned for another Apple device`, + }); + } + await rememberCaptureSourceUid(device, uid); + return started; +} + +/** Whether every other Apple device in the inventory with the name of `device` has a learned source. */ +async function namesakesAllLearned( + device: DeviceInfo, + otherSources: ReadonlyMap, +): Promise { + try { + const namesakes = await inventoryNamesakes(device); + if (namesakes === undefined) return false; + const keys = await Promise.all(namesakes.map(captureSourceDeviceKey)); + return keys.every((key) => otherSources.has(key)); + } catch { + // An inventory that cannot be read proves no match exact. + return false; + } +} + +async function discardCapture( + started: Extract, + outputPath: string, + fallback: Readonly<{ reason: IosUsbCaptureFallbackReason; message: string }>, +): Promise { await started.process.terminate(); await started.process.wait.catch(() => undefined); fs.rmSync(outputPath, { force: true }); - return { - status: 'unavailable', - reason: IOS_USB_CAPTURE_FALLBACK_REASONS.deviceNameShared.reason, - message: `Another Apple device of this daemon is also named ${device.name}`, - }; + return { status: 'unavailable', ...fallback }; +} + +/** A reader of the helper's `capture-source-uid` line. `stop` removes its stdout listeners. */ +type SourceUidReport = Readonly<{ uid: Promise; stop(): void }>; + +/** + * The `uniqueID` in the helper's `capture-source-uid` line, or `undefined` when its stdout ends first, + * names no valid ID, or the reader is stopped. Only the start of stdout is scanned. + */ +function readReportedSourceUid(stdout: Readable | null): SourceUidReport { + if (!stdout) return { uid: Promise.resolve(undefined), stop: () => {} }; + let stop = () => {}; + const uid = new Promise((resolve) => { + let pending = ''; + let scanned = 0; + const finish = (found: string | undefined) => { + stdout.off('data', onData); + stdout.off('end', onEnd); + stdout.off('close', onEnd); + resolve(found); + }; + stop = () => finish(undefined); + const onEnd = () => finish(undefined); + const onData = (chunk: string | Buffer) => { + const text = String(chunk); + scanned += text.length; + const lines = (pending + text).split('\n'); + pending = lines.pop() ?? ''; + for (const line of lines) { + const reported = SOURCE_UID_LINE.exec(line)?.[1]; + if (reported !== undefined) { + return finish(isCaptureSourceUid(reported) ? reported : undefined); + } + } + if (scanned > MAX_STDOUT_SCAN_CHARS) finish(undefined); + }; + stdout.on('data', onData); + stdout.once('end', onEnd); + stdout.once('close', onEnd); + }); + return { uid, stop }; } -/** Whether `device` is the only Apple device in the daemon's inventory, cabled or wireless, with its name. */ -export async function deviceNameIsUnique(device: DeviceInfo): Promise { +/** + * The other Apple devices in the daemon's inventory, cabled or wireless, with the name of `device`, or + * `undefined` when the inventory does not hold `device` under that name. + */ +export async function inventoryNamesakes( + device: DeviceInfo, +): Promise { const { listLocalDeviceInventory } = await import('@agent-device/device-selection/device-inventory-context'); const named = (await listLocalDeviceInventory({ platform: 'apple', kind: 'device' })).filter( (candidate) => candidate.appleOs !== 'macos' && candidate.name === device.name, ); - return named.length === 1 && named[0]?.id === device.id; + if (!named.some((candidate) => candidate.id === device.id)) return undefined; + return named.filter((candidate) => candidate.id !== device.id); } +/** + * How the helper picks the capture source: the learned `uniqueID` while it has the device name, and + * otherwise the device name among the sources not excluded. + */ +type SourceMatch = Readonly<{ learnedUid: string | undefined; excludedUids: readonly string[] }>; + async function startUsbCaptureHelper( host: HostEnvironment, device: DeviceInfo, outputPath: string, + match: SourceMatch, signal?: AbortSignal, + onHelperStarted?: (helper: ExecBackgroundResult) => void, ): Promise { const [{ compileSwiftSources, startSwiftHelper }, { IOS_USB_CAPTURE_SOURCES }] = await Promise.all([ @@ -141,13 +291,15 @@ async function startUsbCaptureHelper( { label: LABEL, readyTimeoutMs: READY_TIMEOUT_MS, - start: () => - startSwiftHelper( + start: async () => { + const helper = await startSwiftHelper( host, executablePath, [ '--device-name', device.name, + ...(match.learnedUid === undefined ? [] : ['--device-uid', match.learnedUid]), + ...match.excludedUids.flatMap((uid) => ['--exclude-device-uid', uid]), '--output', outputPath, '--start-lock-path', @@ -160,7 +312,10 @@ async function startUsbCaptureHelper( String(START_LOCK_TIMEOUT_MS), ], { allowFailure: true }, - ), + ); + onHelperStarted?.(helper); + return helper; + }, startError: usbCaptureStartError, }, outputPath, diff --git a/src/platform-runtime-screen-recording-apple-usb-capture-sources.ts b/src/platform-runtime-screen-recording-apple-usb-capture-sources.ts new file mode 100644 index 00000000000..a7972b7773f --- /dev/null +++ b/src/platform-runtime-screen-recording-apple-usb-capture-sources.ts @@ -0,0 +1,201 @@ +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +import { + admitPrivateRoot, + openVerifiedFileForRead, + publishDurableFileSync, +} from '@agent-device/host-kit/file'; +import type { DeviceInfo } from '@agent-device/kernel/device'; + +/** + * The USB screen-capture source each physical iOS device opened on this Mac, learned from exact name + * matches. macOS assigns a capture source its `uniqueID` once per device per Mac and keeps the UDID + * mapping in a root-only file, so agent-device keeps its own copy here. + * + * A record is a hint: every function answers as if no record exists when the store cannot be read or + * written, and never fails the recording that asked. + */ +const SCHEMA_VERSION = 1; +const MAX_UID_LENGTH = 128; +const MAX_RECORD_BYTES = 4_096; +const RECORD_FILE_NAME = /^[0-9a-f]{64}\.json$/; + +type CaptureSourceRecord = Readonly<{ + schemaVersion: typeof SCHEMA_VERSION; + deviceKey: string; + captureUid: string; + learnedAtMs: number; +}>; + +/** Whether `value` can be a capture source `uniqueID` that the helper accepts as one argument. */ +export function isCaptureSourceUid(value: unknown): value is string { + return ( + typeof value === 'string' && + value.length > 0 && + value.length <= MAX_UID_LENGTH && + value.trim() === value && + !/\p{Cc}/u.test(value) + ); +} + +/** The capture source `uniqueID` recorded for `device`, or `undefined`. */ +export async function recallCaptureSourceUid(device: DeviceInfo): Promise { + return await hint('recall', undefined, async () => { + const deviceKey = await deviceKeyOf(device); + if (!admitStore('repair')) return undefined; + return readRecord(recordPath(deviceKey), deviceKey)?.captureUid; + }); +} + +/** Records `captureUid` for `device`, replacing an earlier record. */ +export async function rememberCaptureSourceUid( + device: DeviceInfo, + captureUid: string, +): Promise { + await hint('remember', undefined, async () => { + if (!isCaptureSourceUid(captureUid)) return; + const deviceKey = await deviceKeyOf(device); + if (!admitStore('establish')) return; + const record: CaptureSourceRecord = { + schemaVersion: SCHEMA_VERSION, + deviceKey, + captureUid, + learnedAtMs: Date.now(), + }; + publishDurableFileSync({ + destination: recordPath(deviceKey), + contents: `${JSON.stringify(record)}\n`, + mode: 0o600, + }); + }); +} + +/** + * The capture source `uniqueID` recorded for each Apple device other than `device`, by the device + * key of that device. A store that cannot be read holds none. + */ +export async function recallOtherDeviceSources( + device: DeviceInfo, +): Promise> { + return await hint('list', new Map(), async () => { + const deviceKey = await deviceKeyOf(device); + const sources = new Map(); + if (!admitStore('repair')) return sources; + let names: string[]; + try { + names = fs.readdirSync(storeRoot()); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return sources; + throw error; + } + for (const name of names) { + if (!RECORD_FILE_NAME.test(name)) continue; + const record = readRecordOrNone(path.join(storeRoot(), name)); + if (!record || record.deviceKey === deviceKey) continue; + if (name !== recordFileName(record.deviceKey)) continue; + sources.set(record.deviceKey, record.captureUid); + } + return sources; + }); +} + +/** The key the store files the record of `device` under. */ +export async function captureSourceDeviceKey(device: DeviceInfo): Promise { + return await deviceKeyOf(device); +} + +async function hint(operation: string, fallback: T, work: () => Promise): Promise { + try { + return await work(); + } catch (error) { + emitDiagnostic({ + level: 'warn', + phase: 'ios_usb_capture_source_store_failed', + data: { operation, error: error instanceof Error ? error.message : String(error) }, + }); + return fallback; + } +} + +async function deviceKeyOf(device: DeviceInfo): Promise { + const { canonicalLocalDeviceKey } = await import('@agent-device/daemon-contracts/device-claims'); + return canonicalLocalDeviceKey(device); +} + +function storeRoot(): string { + return path.join(os.homedir(), '.agent-device', 'ios-usb-capture-sources'); +} + +/** Admits the store directory as this user's own, at 0700. A refused directory holds no record. */ +function admitStore(mode: 'repair' | 'establish'): boolean { + const admission = admitPrivateRoot({ rootPath: storeRoot(), mode }); + if (admission.status === 'admitted') return true; + emitDiagnostic({ + level: 'warn', + phase: 'ios_usb_capture_source_store_refused', + data: { component: admission.component, exposure: admission.exposure }, + }); + return false; +} + +function recordFileName(deviceKey: string): string { + return `${crypto.createHash('sha256').update(deviceKey).digest('hex')}.json`; +} + +function recordPath(deviceKey: string): string { + return path.join(storeRoot(), recordFileName(deviceKey)); +} + +/** One unreadable record does not hide the others. */ +function readRecordOrNone(file: string): CaptureSourceRecord | undefined { + try { + return readRecord(file); + } catch { + return undefined; + } +} + +/** + * Reads one record without following a link. A missing, oversized or malformed file holds none, and + * so does a file that another user owns or can write: a store directory that was once open to others + * can still hold files they planted, and admitting the directory does not remove them. + */ +function readRecord(file: string, deviceKey?: string): CaptureSourceRecord | undefined { + const descriptor = openVerifiedFileForRead(file); + if (descriptor === undefined) return undefined; + let text: string; + try { + const stats = fs.fstatSync(descriptor); + if (!isOwnPrivateFile(stats) || stats.size > MAX_RECORD_BYTES) return undefined; + text = fs.readFileSync(descriptor, 'utf8'); + } finally { + fs.closeSync(descriptor); + } + let value: unknown; + try { + value = JSON.parse(text); + } catch { + return undefined; + } + const record = asRecord(value); + if (!record || (deviceKey !== undefined && record.deviceKey !== deviceKey)) return undefined; + return record; +} + +function isOwnPrivateFile(stats: fs.Stats): boolean { + const uid = process.getuid?.(); + return (uid === undefined || stats.uid === uid) && (stats.mode & 0o022) === 0; +} + +function asRecord(value: unknown): CaptureSourceRecord | undefined { + if (typeof value !== 'object' || value === null) return undefined; + const { schemaVersion, deviceKey, captureUid, learnedAtMs } = value as Record; + if (schemaVersion !== SCHEMA_VERSION) return undefined; + if (typeof deviceKey !== 'string' || deviceKey.length === 0) return undefined; + if (!isCaptureSourceUid(captureUid)) return undefined; + if (typeof learnedAtMs !== 'number' || !Number.isFinite(learnedAtMs)) return undefined; + return { schemaVersion, deviceKey, captureUid, learnedAtMs }; +} diff --git a/website/docs/docs/capabilities.md b/website/docs/docs/capabilities.md index 0e215e53e56..fef21148f19 100644 --- a/website/docs/docs/capabilities.md +++ b/website/docs/docs/capabilities.md @@ -239,7 +239,7 @@ What a **Yes** does not claim: What a **Yes** does not claim: -- **Screen recording**: A cabled iPhone or iPad records its USB screen-capture source near 60 fps when the app that runs the daemon has macOS camera access and no other Apple device has its name, and falls back to runner screenshots before its first frame otherwise: no audio, the screen must be awake and unlocked, and frames are dropped while the screen is turned away from the orientation it started in. Otherwise an iOS physical device records runner screenshots, not a native video stream: no audio, and dropped frames are expected. An Android clip covers 180 seconds, and a longer recording arrives as chunks. +- **Screen recording**: A cabled iPhone or iPad records its USB screen-capture source near 60 fps when the app that runs the daemon has macOS camera access and its capture source appears. agent-device learns the source of a device on a recording when every other Apple device and capture source with the device name is learned for another device; later recordings of that device open the learned source while it has the device name, and otherwise match by name; only a newer exact match replaces what was learned. It falls back to runner screenshots before its first frame otherwise: no audio, the screen must be awake and unlocked, and frames are dropped while the screen is turned away from the orientation it started in. Otherwise an iOS physical device records runner screenshots, not a native video stream: no audio, and dropped frames are expected. An Android clip covers 180 seconds, and a longer recording arrives as chunks. - **HTTP(S) request inspection**: Local native app sessions inspect the HTTP(S) entries present in the session app log; traffic absent from those logs is not captured. The three WebDriver provider clouds refuse a live dump: their traffic is on the provider side, and TestMu AI can return provider network-log artifacts after the session ends. Managed web sessions inspect the browser request history. - **Audio probe**: A simulator, emulator, or macOS desktop session samples host system audio, which works on a macOS agent host and needs Screen Recording permission there. diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 2a670b003f7..ef92976f599 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -291,11 +291,12 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `contact_sheet_threshold_invalid` | The change threshold is not a finite share between 0 and 1. | | `video_validator_compile_timeout` | The Swift compile is still running past the caller's wait; try the stop again. | | `video_validator_unavailable` | The validator could not be built or run at all, so playability stays unverified. | -| `ios_usb_capture_device_not_found` | No USB screen-capture source with the device name appeared on the host. | +| `ios_usb_capture_device_not_found` | Neither the USB screen-capture source learned for the device nor another source with the device name appeared on the host. | | `ios_usb_capture_no_frames` | The capture source opened but sent no frame before the first-frame timeout. | | `ios_usb_capture_camera_access_not_authorized` | macOS camera access is not authorized for the app that launched the daemon. Nothing prompts for it. | | `ios_usb_capture_start_busy` | Another USB capture recording on this Mac, of any user, held the start lock for the whole lock timeout. | -| `ios_usb_capture_device_name_shared` | Another Apple device in the daemon's inventory, cabled or wireless, has the device name. | +| `ios_usb_capture_device_name_shared` | No capture source is learned for the device, and the device name is not unique among the unlearned: another Apple device in the daemon's inventory, cabled or wireless, with no learned source, or another USB capture source on this Mac not learned for another device, has it, or the inventory could not be read. | +| `ios_usb_capture_source_of_another_device` | Another Apple device learned the capture source that matched the device name while this start ran. | | `android_screenrecord_startup_failed` | Android `screenrecord` exited before it began writing; its startup output says why. | | `recording-output-unplayable` | The recording's file is not a playable video, which only a recorder still finalizing it can undo. | | `native_recovery_evidence_unavailable` | The marker exists but the device could not be read, so it cannot be classified. |