Skip to content

Latest commit

 

History

History
545 lines (443 loc) · 127 KB

architecture.md

File metadata and controls

545 lines (443 loc) · 127 KB

CodeNomad Architecture

Overview

CodeNomad is a SolidJS UI and Fastify server hosted by Electron or Tauri. The official @opencode/client dependency pins live in the server and UI manifests; the runtime CLI is independently managed.

Desktop host -> CodeNomad server -> one shared OpenCode service
                    ^    |
                    |    +-> CodeNomad /api/* and /api/events
                    +------ UI clients through /workspaces/:id/instance/api/*

CodeNomad's bundled native plugins (automation, see BROWSER_AUTOMATION.md; session pruning; Missions) load through native V2 discovery.

Shared Service And Locations

packages/server/src/workspaces/opencode-service.ts runs the selected host or WSL CLI's official service status, service start, and service get password lifecycle, validates the authenticated loopback endpoint, and pins that identity while active. It connects to one externally owned global daemon and never stops it on backend shutdown. An acquisition more than 30 seconds after the last check repeats discovery: a different discovered daemon (URL, PID, version or credentials) replaces the connection, while a discovery that fails or finds no service keeps it until the next interval. Failed location validation, proxy transport or authentication failures and upstream event-stream EOF/errors retire the connection.

OpenCode owns the daemon's standard state and database. Configured allowed environment variables and NODE_EXTRA_CA_CERTS apply only if CodeNomad starts a missing daemon; a running daemon keeps its environment. OPENCODE_DB and XDG_STATE_HOME never reach the daemon or session environments (workspaces/host-opencode-service.ts, workspaces/session-environment.ts). WSL support requires Windows localhost forwarding and executes the Linux CLI lifecycle inside the selected distribution without cross-namespace PID operations.

packages/server/src/workspaces/manager.ts treats selected folders as native OpenCode locations:

  1. Validate the directory with client.location.get.
  2. Store the returned LocationRef and publish the logical workspace.
  3. Reuse the shared service for every additional directory.
  4. Closing a project tab deletes that occurrence's logical workspace record (DELETE /api/workspaces/:id; see PROJECTS.md).

Native Profiles, Windows, And Client State

Electron POSIX startup discovers the shell environment in an isolated process group, bounded to three seconds and 1 MiB. The framed emitter keeps a referenced three-second exit timer so its leader stays signalable until group cleanup and expires if the discovery parent disappears. Cleanup rejects signal errors other than ESRCH.

Electron and Tauri run one native singleton process and one CodeNomad backend per data profile/config pair (DESKTOP_DATA_PROFILES.md), isolating singleton identity, backend/browser storage and client state. A second launch opens another UUID-backed window by default; Advanced settings can restore most-recent-window focus, while --new-window always creates another window.

--connect-server <value> (or --connect-server=<value>) asks for a remote window; both hosts parse it beside --folder/positional folders (Electron startup.ts parseLaunchIntent, Tauri launch.rs, Windows second-instance forwarding included) and keep the raw value (empty when missing). The host never resolves or connects: it queues the value to a local window (window:connections-pending / desktop:connections-pending, pulled and acknowledged in order like launch folders), and the renderer resolves it against the saved remote servers (lib/launch-connect-target.ts: id, then name, then an http(s) URL without user info or fragment) and runs the same saveServer flow as Connect (probe, TLS/certificate prompts, proxy session, openRemoteServerWindow). A connect-only launch (no folders, no --new-window) skips the startup window restore and, without an open local window, runs in a hidden, unpersisted launch window (connectOnly/connect_only) that the host closes once the remote window is open (connect-launch.ts, Tauri local_windows.rs). That window holds no slot of the 16-window limit (registration and new-window admission share one user-window count) and is never an MRU, focus or launch target, so folder launches arriving meanwhile open an ordinary window. Launch-owned hidden windows (the launch window and, on Electron, a remote window still loading for a launch) never count for the last-application-window decision (isLaunchWindow, Tauri is_final_application_window's launch labels): closing the last visible window quits normally and keeps its saved state. The saved Preferences window is restored only by a normal start: a connect-only launch holds it (DeferredRestore, Tauri startup_restore_deferred) until its fallback. It never prompts or shows errors: a failure, a connection that needs a prompt (the Tauri local-certificate install, InteractionRequiredError), a backend error or a 60-second timeout makes the host perform the normal restore and queue the connection (with its failure, if any) and every one still pending to the restored window, which reports or runs them visibly; if that restore fails, the launch window itself is promoted and shown. Launch connections open the remote window with requireLoad: on Electron a failed first page load destroys the hidden new remote window and rejects instead of showing the loading screen (Tauri cannot observe the remote page's load result and shows the webview's own error page). A forwarded connect-only second launch runs in the most recent window instead of opening a new one. Electron forwards the second launch's own parsed intent through requestSingleInstanceLock(additionalData) (forwardedLaunchData/readForwardedLaunchIntent), because Chromium reorders the forwarded argv; the Windows Tauri single-instance plugin forwards arguments joined and split on |, so every Windows Tauri launch refuses an argument containing | with a startup error before the plugin runs (launch::pipe_argument_error), which keeps forwarded argument boundaries exact.

Remote windows are never restored, and the user can always reach a working local window. Rules (both hosts):

  • Every new local window signs itself in to the local server: Tauri gives each one the session cookie before its first backend navigation (LocalCliAccess::session_cookie_for, read through ready_local_access without the lifecycle lock), because WebView2 drops a session cookie once every window of its store has closed (the last local window closed beside a remote window, or a launch connection). Electron keeps the cookie in the application-lifetime default session.
  • Closing the last local window keeps its saved state even while remote windows stay open, as quitting would (Electron MultiwindowLifecycle.hasOtherLocalWindow, Tauri LocalWindows::has_other_user_window); the next local window (File → New Window, a later launch or the next start) reopens it. Only a local window closing beside another local window forgets its state.
  • A local window showing a page that does not run the application (loading, sign-in, pairing, /auth/*) closes and lets CodeNomad quit without waiting for a client-state flush it could never answer (Electron isListenerlessDocument in renderer-client-state-flush.ts, Tauri awaits_renderer_flush over is_listenerless_document).
  • A remote window whose server cannot be loaded keeps a way back. Electron loads its own loading page with #remote-unavailable=<token> (lib/native/remote-unavailable.ts): Try again, Open a local window and Close window (remote:retry, remote:openLocalWindow). RemoteRecoveryPages and showRemoteUnavailable (electron/main/remote-recovery.ts) load a new document for every token (a recovery load counter in the query, so a Try again whose load commits nothing, such as HTTP 204, still replaces the page) and authorise a request only from the registered remote window's main frame with that token and the origin bound once by that load's own commit. Any later main-frame commit or a renderer crash revokes the token for good. The window remembers its revoked recovery documents (up to 16), so when the user brings one back (native Reload, also after a crash, or history) its commit shows a fresh document with a fresh token; a crash itself never reloads. A URL the page can rewrite (History API) is never the authority; remote-recovery.test.ts checks this through real Electron IPC. Tauri remote windows show WebView2's error page with its reload button, their native title bar and File menu.

A plain browser tab, including an installed PWA, keeps its V1 client snapshot in sessionStorage (lib/web-session-client-state.ts, selected by lib/native/client-state.ts). A reload or page discard restores projects, sessions, drafts and scroll positions. Layout values stay in shared localStorage, and Clear leaves them. The tab remembers its Restore previous state switch; a refused save leaves later saves and Clear available. A non-cached departure marks the snapshot released before deleting its workspace records. Only an unmarked snapshot resumed with document.wasDiscarded === true can reclaim surviving exact records. A fresh restoration marks the inherited snapshot ineligible for reuse until it saves its own records. Desktop remote windows keep no persistent client state.

OpenCode sessions and messages are shared through the global daemon. Window membership, tabs, drafts, view state, and native bounds are local to each UUID window. Client-state V3 is a per-window envelope over the V2 SHA-256 content-addressed partition graph: immutable partitions are prepared before atomic root publication, writes and migrations are fenced by current ownership and renderer authority, and garbage collection runs after publication while retaining every partition referenced by any window.

Empty tab descriptors occupy ordered slots in the session manifest, using spare capacity within the saved tab limit. Each restores a fresh Browse and Recent view.

Each workspace descriptor has its own optional viewState payload, normalized by stores/tab-view-state-codec.ts and stored inline in that descriptor's workspace partition (client-state-partitions.ts). Duplicate folders keep distinct descriptors through their occurrence and runtime tab bindings; restore seeds the envelope onto each recreated instance UUID before session hydration. The payload is:

Field Saved presentation
version: 1 Envelope schema version.
previews[sessionId] Foreground mode (chat/preview).
missions Selected Mission/native schedule, task, reader target, expanded rows and target-specific disclosures.
rightPanelTab Selected built-in or extension tab ID.
filesMode workspace, changes or history.

Session-owned preview URLs, history cursors and viewport presets use the opencode-session-browser-state-v1 layout entry and share a 4,000-character serialized budget across the window, with at most 32 sessions and 32 URLs per history. History trims before preview eviction. Imported occurrence resources merge by session with active-descriptor priority, then their envelopes retain only foreground modes. Each Mission envelope is bounded to 4,096 serialized characters, 30 expanded rows and 160 disclosure choices; the newest disclosure choices survive trimming. Invalid optional fields are normalized away; an unsupported envelope version yields an empty presentation seed while the descriptor's other recoverable state remains available. Transcript scroll snapshots retain their separate occurrence/session storage. Live file targets, editor models/drafts and native browser documents use their in-memory lifetimes; saved browser pages load only on explicit opening. PROJECTS.md defines hydration, closure, partial restore and preview migration.

Electron and Tauri use the native preview contract for guest lifecycle, storage, automation and permissions.

Projects on saved profiles follow the remote preview transport contract.

Plain-browser and remote-view previews use unguessable capabilities for HTTP and WebSocket proxy traffic. Preview proxies never forward request cookies and strip the target's Set-Cookie. Path-proxied preview responses (/previews/<token>/… and the Referer asset fallback, every content type) carry Content-Security-Policy: sandbox with the iframe's flags (previews/sandbox.ts, shared with the UI) and Referrer-Policy: same-origin, so a preview document stays opaque even when opened outside its iframe and its capability path stays out of Referer headers to other sites. The per-token preview.localhost host has its own origin and receives neither override. The proxy rewrites root-relative URLs in HTML attributes, CSS url() and JavaScript imports, and the runtime bridge rewrites fetch, XHR, WebSocket, EventSource, history, untargeted link-click and form-submission URLs, and gives opaque documents whose storage access throws one stable in-memory localStorage/sessionStorage/document.cookie object each for the current page load, detected by reading alone so working storage (the per-token host opened on its own) stays native. Other root-relative requests (a CSS @import string, for example) reach the static UI or dev-proxy handlers, which proxy them to the preview named by their Referer when the request has a CodeNomad session, as every direct-listener request has with authentication disabled; stylesheet subresources send the stylesheet's URL as Referer even from an opaque document. Remote Control refuses this fallback while previews are off. Browser preview iframes are opaque-origin sandboxes without allow-same-origin; preview element comments use a source-checked message bridge instead of parent DOM access. SideCar iframes add allow-same-origin by design: a SideCar is a trusted extension of CodeNomad, and its scripts run with the application's origin and access. /sidecars/* authenticates with the SameSite=Lax session cookie and rejects Origin: null, which an opaque frame cannot satisfy.

API Boundaries

CodeNomad control routes under /api/* include:

  • /api/workspaces and /api/workspaces/:id/worktrees/*
  • /api/workspaces/:id/worktrees/:slug/git-status|git-diff|git-stage|git-unstage|git-commit
  • /api/events and /api/client-connections/pong
  • /api/storage, /api/settings, /api/filesystem, /api/speech
  • /api/opencode-plugin/automation, authenticated by a per-process loopback token and restricted to CodeNomad-owned locations
  • /api/remote-control/*, managed from the host only; POST /api/remote-control/pair and /remote-pair answer only through Remote Control and verified direct HTTPS origins (REMOTE_CONTROL.md)

Authentication and Remote Control admission judge routedPath() (server/routed-path.ts), the path Fastify's router matches (/%61pi/x routes as /api/x), and refuse targets it would reinterpret. Never base an access decision on the raw request target.

Native OpenCode requests use /workspaces/:id/instance/api/*. The Fastify proxy exposes an explicit method/path allowlist, adds shared-service authorization, validates prompt files, defaults safe requests to the workspace location, and rejects locations/directories outside the selected workspace or its worktrees. Session routes also verify session.location.directory. Never trust a browser-supplied worktree path: resolve ownership server-side. Upstream additions are exposed only after an explicit proxy review.

The conversation permission mode route (/api/workspaces/:id/sessions/:sessionId/permission-mode) owns the Supervised block of native session rules. OpenCode evaluates the same session rules for CodeNomad and its terminal UI; configuration is read-only to this route. Native session.permissions triggers a fresh mode read. See Native interruption UX.

Published UI compatibility

packages/cloudflare/release-config.json sets the remote UI's minimum CodeNomad server to 1.2.0. The Status panel reads and writes conversation permissions through /api/workspaces/:id/sessions/:sessionId/permission-mode. ui/remote-ui.ts checks the manifest's minimum before downloading: older servers keep their cached or bundled interface and expose the server-upgrade status. ui/__tests__/remote-ui.test.ts covers both sides of this boundary.

Client And Events

packages/ui/src/lib/sdk-manager.ts uses OpenCode.make() and caches generated Promise clients by instance proxy path. packages/ui/src/stores/opencode-client.ts is the root-client authority; native directory/location fields select the worktree.

The server holds one client.event.subscribe() stream. InstanceEventBridge maps native location events to CodeNomad instance.event records, and /api/events multiplexes them with workspace events for the browser; heartbeats use POST /api/client-connections/pong. The stream is volatile and has no replay guarantee: reconnect must reconcile sessions and pending requests and reread authoritative file/config state. Pending recovery uses the loaded-only broker, never worktree-wide ordinary lists; see compatibility, whose Agent conventions also specify relay ordering and ownership fences.

Per-backend transport

Remote clients resolve CodeNomad HTTP routes, panel-extension routes, deferred tool images, the default events URL and workspace SDK proxies from the backend origin through BackendTransport.url() / resolveBackendUrl(). A trailing slash on the base URL is optional; a path prefix on that base is discarded for these root-relative routes. An explicit absolute events URL is preserved. The SDK manager and panel-extension factory take the backend's url and fetch; mounted transcript consumers resolve media through createMediaSource.

Injected local bases preserve their resource-specific joining contracts through the shared resolver: HTTP/auth use URL resolution, panel extensions and SSE append their paths verbatim, and deferred images and SDK proxies trim trailing base slashes before appending. buildInstanceBaseUrl() exposes the injected-local SDK joining contract. The append and append-trimmed resolver modes serve these local adapters; remote factories use the backend's URL resolver. Storage, metadata and Mission requests delegate URL construction to the same backend API; event transport delegates to its API's already resolved events URL, adding connection identity query parameters there.

packages/ui/src/lib/backend-client.ts describes one CodeNomad backend as a BackendClient: base URL, events URL, authenticated fetch, login recovery (auth), api (createServerApi), events (ServerEvents), storage, meta and the OpenCode sdk manager, each built by its module's factory. createBackendClient() builds another backend's client from an absolute http(s) base URL (anything else throws a TypeError); its events stream connects only on events.start(), its api, storage, meta and sdk requests all go through its own fetch, its 401s probe only its own login, and a restored login restarts only its own stream. localBackend is assembled from the module singletons (serverApi, serverEvents, authRecovery, authenticatedFetch, storage, sdkManager, getServerMeta), which remain the same mutable objects their importers and tests use; the serverEvents singleton connects at import. backends starts with local; the saved-profile registry owns remote publication through registerBackendClient(). backendOf(instanceId) returns the registered owner of the instance key's backend and throws for an unregistered one. lib/backend-transport.ts is the only reader of the injected API base and events URL (through lib/api-base.ts); EventSource and fetch are resolved per call. Network code takes a backend's transport (BackendHttp) with the local one as default, never the injected globals.

Saved-profile backend relay

The common server onRequest hook captures session/device principals for every reviewed remote UI operation before body parsing. codenomad-servers/relay-principal.ts supplies that original signal to relay, browse, connect, probe, memory and profile-administration adapters; the common publication hook and per-operation checks fence dispatch and results. Queue waits retain their signal and shared authentication uses independent borrowers. Memory repository waits and decisions retain each principal through the durable journal checkpoint. Session observers retain idle/absolute deadlines; device socket lifetime and read-only validity checks retain channel ownership. Releasing one principal leaves other principals and the host-owned saved connection live. The complete operation contract defines each surface, including closed WebSocket control routes and metadata-only request logging.

Saved profiles may include ssh: { host }. Their baseUrl is resolved from that OpenSSH host, while codenomad-servers/ssh.ts owns one on-demand local forward per profile authority. The explicit transport dials its private loopback port and retains the saved origin for HTTP and TLS identity. Credentials and revocation bind the SSH destination, origin and TLS policy together. All backend listeners share the forward lifetime; a child exit drops the dial endpoint while retaining credentials for the next explicit request. Removal, retargeting, Forget and final backend shutdown close the owned child. OpenSSH supplies host-key verification, configuration, keys and agent authentication with prompting disabled.

createRemoteBackendClient(profileId) constructs an unregistered client whose resolver prefixes HTTP, auth, SSE, SDK and media routes with /api/backends/<profileId> on the UI's CodeNomad origin. Electron, Tauri and admitted remote browsers use the same host-owned transport. The host-owned config.ui.settings.multiBackend flag defaults to true when omitted and requires boolean true when set. Its configuration has no visible control. Remote browser admission reads this flag authoritatively from YAML through SettingsService.multiBackendEnabled() and refuses unreadable or invalid documents. The renderer uses AbortSignal.any() directly; the WebKit requirement is 17.4 or later. While off, the local registry and existing tabs retain their behavior; registry demand performs zero remote IO.

stores/remote-backends.ts owns the renderer's backendRegistry, implemented by stores/backend-registry.ts. ensure(profileId) rereads host policy and saved profiles, coalesces a candidate per profile and reads authenticated metadata afresh through the relay with no-store and an eight-second deadline, independently of display caches. Compatible metadata precedes client registration, event fan-in attachment, SSE start and the backend-owned workspace list. Profile ids remain backend ids. Reactive states are idle, admitting, compatible, refused, unauthorized and unreachable. Merely observing profiles starts no network work.

retryWorkspaces(profileId) explicitly recovers inventory on an existing admission after its initial read settles. Fresh metadata confirms the contract, server identity and immutable relay proof before the injected workspace loader receives that exact client and captured attachment signal. Concurrent calls share the flight; { invalidate: true } coalesces demand into at most one follow-up. Failures reject while retaining the last display snapshot; success repairs availability only for the current entry, target, flag, metadata-failure epoch and attachment. Continued invalidation parks for the next explicit demand. ensure retains its admitted promise across inventory failures.

Metadata reads share a monotonic validation generation. A superseded live SSE gate follows the newest metadata verdict while its own response stays fenced; an obsolete inventory metadata read rejects for a fresh explicit demand. Healthy metadata revalidation preserves inventory publication authority. Metadata failures advance a separate health epoch that fences pending inventory success. Inventory failures retain their unavailable state through metadata-only success; a current successful inventory clears that failure.

Renaming a saved profile retains its client. Address/TLS change, removal, explicit detach, disposal or flag off revoke fan-in authority first, abort candidate IO, dispose stream/retry/watchdog resources and remove the client. Late candidate replies check both their exact entry and current saved policy. A fresh attachment has a new signal. Temporary stream failure preserves the attachment and existing tabs, using ordinary retries. Each remote connection attempt rereads metadata before acquiring EventSource or delivering open/domain resyncs; contract or server identity changes refuse and revoke the backend. Superseded connection attempts abort their validation reads. Workspace-list failures retain the admitted client and expose unreachable until recovery.

The saved-profile relay contract owns forwarding, authentication, TLS and connection lifetime.

Remote previews use the preview transport contract.

index.ts owns one RemoteServerBrowseManager, its settings-change subscription and shutdown across HTTP, HTTPS and the private bridge listener. Standalone listener managers sharing the backend's SettingsService retain the same connection state: credentials, clients, pending connections, queues and profile authorities. Closing one owner releases its lease; the last owner closes the shared connections. Forget revokes the shared authority immediately, across every listener.

Registry candidates opt into bindRelayAuthority. Reconnect must observe the same proof and installation identity; a replacement at the same origin can be detected only once its identity is observed. SDK proxy bases stay plain, and their fetch carries the proof header.

Project opening and cleanup retain their original backend and exact receipt; see remote opening ownership.

Boundary Admission and revocable authority
UI relay and browse/connect/forget createBackendUiAccess: local callers retain guardLocalBackendCaller provenance; the strict host flag admits paired ingress, verified direct HTTPS and declared LAN HTTP UI sessions on reviewed methods/paths. Sensitive LAN reads require Origin/Referer; new passwords/pairing links require local, Remote Control or verified HTTPS. Meta announces use/manage/secret-entry capabilities. Explicit server-device traffic keeps its closed catalog. See admission.
Saved remote client Backend-shared authority captured at admission; exact saved origin and confirmed TLS policy; credentials in remote-server-credentials.json beside the config with mode 0600. Each client owns an AbortController; request cancellation composes with it through uploads and streamed response bodies.
Profile changes and removal Synchronous storage.stateChanged reconciliation revokes the generation, closes changed/removed clients and pending connections, deletes credentials, and fences queued dispatch and pending authentication before persistence. Forget revokes every listener; backend shutdown closes their shared owner.
Remote device The remote gate authenticates the private device credential on each request, admits the reviewed method/path catalog, marks device scope on both listeners, and retains sockets on both for revocation, eviction and shutdown. Stop and tunnel failure close only ingress sockets. Browser pairing judges ingress-socket membership or a verified direct HTTPS origin; browser Origin admission retains its own policy.
Response publication Selected safe response headers, private-cookie removal, no-store, sandbox CSP and nosniff; decoded transfer lengths follow decoded bytes. Local caller disconnect closes the upstream transfer.

The UI boundary registry below classifies relay construction and URL resolution as retained-client operations; existing A/P callers supply the same cancellation signals through this transport. A sent mutation can settle remotely while its revoked caller loses publication authority.

Server metadata contract

GET /api/meta adds the public serverId UUID, apiContract integer and capabilities: string[] to the shared ServerMeta response. SettingsService.getServerId() reads server.serverId authoritatively from the selected config YAML. When absent, it creates <config-target>.server-id exclusively with openSync(..., "wx", 0o600), writes a UUID, then rereads the config and persists the winning UUID. Concurrent initializers read the same immutable claim; config symlink aliases share the final target's claim. Readers retry an incomplete UUID for at most one second while its creator finishes writing. Each distinct fresh config receives its own UUID; copying a config preserves its identity.

A complete claim survives a crash or failed YAML write and supplies the same UUID on retry. An incomplete or invalid claim remains untouched and requires explicit operator repair: stop all servers using this config and restore the known UUID, or explicitly remove an incomplete claim only after confirming that no stable identity was advertised. Identity initialization preserves other owners and server settings. Unreadable, read-only or malformed config, invalid stored UUIDs/claims, conflicts and persistence errors log a warning; startup continues with serverId omitted from metadata and remote registry admission refused. An existing valid YAML identity is authoritative and supports read-only startup without a write.

packages/server/src/meta-contract.ts defines the CodeNomad contract, initially 1. Increment it whenever an existing UI-consumed CodeNomad wire contract breaks; additive optional fields and capabilities preserve the integer. Review the server and UI consumers together. OpenCode compatibility follows the consumed native API/capability contracts described in OPENCODE_COMPATIBILITY.md.

Initial capabilities identify implemented CodeNomad route families: workspaces (/api/workspaces inventory and lifecycle), workspace-files (workspace filesystem routes), workspace-git (workspace Git reads and mutations), and events (/api/events). Each route retains its own authorization, ownership and runtime availability checks. Optional features may add distinct capability names; unknown names can be ignored.

BackendClient.meta.getServerMeta() retains these fields in its existing per-client snapshot and signal-owned project cache. The wire fields are optional for older servers and an unavailable stable identity. The pure backendCompatibility() policy returns compatible for exact equality with the local CodeNomad contract and a nonblank serverId, and refused otherwise. Registry admission reads fresh metadata directly. Refused profiles remain saved for an explicit retry after updating the server. Never open a webview or separate window for a refused backend.

Per-backend event fan-in

Revoke the attachment before publishing removal. Isolate publication and individual cleanup failures so all unsubscribers and removal callbacks still run. Preference ownership and write ordering follow Settings and the cache conventions.

ServerEvents owns one backend's EventSource, auth probe, pong, staleness watchdog, retry timer and connection generation. The synchronous backendEvents singleton lives in lib/backend-events.ts; importing this module or captureBackendOperation constructs only the fan-in. lib/server-events.ts re-exports the same singleton, connects the local source and attaches it. The fan-in scopes CodeNomad envelope instance/workspace ids (including descriptors and log entries), adds backendId for another backend and preserves native event/location data, generations and physical paths. Local events retain their object and ids, and serverEvents === localBackend.events stays the local source. Lifecycle callbacks carry the source backend (onOpen(backendId), onTransportStatus(status, backendId)); forInstance() filters against a view's current instance. Each backend has its own SSE manager and transport display state, with the existing session hooks receiving globally scoped instance keys. Reconnect refreshes, display invalidations and foreground recovery target only that backend.

backendEvents.signal(backendId) and reactive signalForInstance(instanceId) expose the attachment's AbortSignal; an absent instance attachment yields an aborted signal. captureBackendOperation(instanceId, parent?, owns?) captures that authority, combines the optional parent signal and exposes signal and current(). Attachment-owned work retains this token across awaits, callbacks, queues and timers, combining it with client, view and request-generation predicates before publication or follow-up work. Reattachment creates a distinct authority even when the backend id and source object are reused. Notification recipients are captured before delivery, and each delivery checks the same authority again. The inventory below distinguishes attachment-owned work, durable client operations and caller/view-only guards.

Detaching a source unsubscribes its fan-in and aborts its attachment authority. A final disconnected status is delivered while the id remains absent; onDetach(backendId, revokedSignal) always identifies the removed owner, and cleanup checks that token before releasing keyed state. Removal disposes and deletes the backend's SSE manager, reactive connection records and foreground recovery controller, clears its integration connection epoch and binding authority, and permits a fresh owner on reattachment, including from inside a callback. Status reads observe existing managers without creating owners. Disposing ServerEvents also detaches every attached fan-in, fences pending connection acquisition and callbacks, closes its captured transport, clears reconnect/watchdog timers and browser/auth subscriptions, aborts event-owned auth probes and pong IO/backoff, and releases source subscriber sets. Connection acquisition, reconnect scheduling and notifications recheck disposal and connection generation at callback boundaries.

Foreground recovery passes its signal through session/message reads, pending-request invalidation, worktree reads and inbox follow-ups; its continuations check revocation before further reads, invalidations or message reloads. Workspace-list reconciliation captures its attachment and list-request authority. Worktree reads coalesce by signal/client owner, with request-identity cleanup. Authentication probes coalesce within their request owner's signal, inherit the originating request's cancellation even on a pong 401, and publish while both their login generation and accepted-observation order remain current. Each backend client owns its storage, metadata and SDK caches; workspace snapshots and view demands follow their instance/view lifetime and workspace-stop cleanup. Other event consumers and their concrete request/coalescence boundaries are inventoried below. The local source remains attached for the page lifetime.

Backend instance identity

Composer history keys preserve the exact physical directory for the local backend and prefix it with the backend id for another backend; PromptInput passes that persistence identity separately to its state hook. Mission completion seeding uses the project scope; pending-recovery notice deduplication uses the backend plus normalized folder. Instance/session-keyed drafts, attachments and caches retain their opaque instance keys.

Qualified instance IDs own Mission and preview presentation. MissionControl and MissionReader acquire request directories from the owning instance's physical folder. File and Location operations use physical directories.

lib/backend-identity.ts names instances and projects per backend. An instance key is the workspace id for the local backend and ${backendId}~${workspaceId} for another one (backend ids match [A-Za-z0-9_-]{1,64}; never :, which instance-keyed maps split on); Instance.backendId is absent for the local backend. A project is one folder of one backend: workspaceIdentity(folder, backendId) matches saved tabs to live workspaces, occurrences, lifecycle events, project renames and temporary marks. projectScope() keys completion acknowledgements and legacy layout adoption (the folder itself for the local backend). refreshWorkspaceList(backendId) reconciles only that backend's instances under its own BackendWorkspaceListReconciliationFence entry, so one backend's list never closes another backend's tabs. Remote workspace snapshots carry the profile backendId and the verified /api/meta serverId. Inventory matching and draft recovery stay within that installation.

Native events include session lifecycle/output events (session.created, session.renamed, session.moved, session.execution.*, session.retry.scheduled, session.step.*, session.compaction.*, session.text.*, session.reasoning.*, session.tool.*), background Shell refresh via shell.created, shell.exited, shell.deleted, file invalidation via filesystem.changed, and configuration invalidation via config.updated. Each busy period settles with exactly one session.execution.succeeded/failed/interrupted; derive session activity from these events, never from the declared but unpublished session.status/session.idle.

UI asynchronous backend inventory

Paths below are relative to packages/ui/src and cover files with detected backend accesses or backend-reaching continuations. Families include the initiating handler, delegated store/adapter, queued work and pagination. HTTP ownership follows the backend transport even when the feature also invokes native desktop methods.

  • A — attachment operation: captureBackendOperation or a captured signalForInstance plus the row's local predicates. Follow delegated calls to their owner; admission and publication guards may live in different modules. The transport-method table identifies which HTTP methods accept cancellation: an A publication guard can coexist with a client-lived outbound request.
  • C — durable client: intentionally retained backend client/transport for persistence, sent mutations, authentication/probing, resource cleanup or local-server bootstrap/administration. A dispatched mutation can finish server-side; any view continuation has its own predicate. Client caches and persistence queues survive SSE reconnection.
  • P — propagated: callback, queue or transport receives its owner's signal/current predicate. Its caller supplies attachment authority; optional signals also admit client-lived requests.
  • V — view/request scope: browser resources, dialog outcomes and retained presentation demand use their view controller/generation/identity. Backend runtime work delegated from these views uses its A or P owner; durable local services retain C.
  • DOM / IPC / EXTERNAL / COMPUTE: rendering/device/browser work, native desktop-only operations, declared third-party HTTP and local calculation/storage encoding follow their component, resource, native request or external-site lifetime. Their helpers, timers and local names remain outside the table; mixed backend files name these local families alongside their backend work.

Generic P helpers inherit their injected read/action callback's authority, including helpers with no statically resolved IO. Queues, retries, debounce, trailing refresh, pagination, body/stream transfer and projection retain the caller's signal/current predicate, logical deadline and request identity across every dispatch, await and publication. Cancellation releases queued work and owned timers; coalescence joins compatible signal/client/request owners, and cleanup releases only its recorded lane. Retained view demand and stale snapshots can acquire a fresh operation after revocation. Dialog and menu dispatch retain the selected request/action and view lifetime; the supplied backend action owns admission and any sent mutation.

Generic C helpers retain the admitted client and creation/mutation request or receipt through persisted writes, serialized native startup-state transactions, abandoned-resource cleanup and retries. A dispatched mutation settles once under that owner; further reads, navigation and UI publication use the original operation's current predicate. Pure encoding, loaders and cache helpers inherit their caller's storage/native owner. Browser media and preview resources retain their element/source or capability identity and view cleanup.

Demand V and operation A are distinct. A displayed view, subscription count, cached snapshot, selected session or persisted preference may survive an attachment. Revocation ends its current A, while a subsequent attachment admits a new A for the still-retained V. The coalescence owner is the captured signal/client/request tuple; backend families identify their concrete lanes and cleanup.

Transient read, search and mutation indicators belong to the exact admitted operation and settle independently of its right to publish a response. Cleanup checks the recorded request, controller or exclusive local owner before releasing a flag; a replacement operation keeps its own busy state. Rebinding releases an abandoned cache flight without starting IO, and applies its new ownership before invoking abort callbacks. Exact schedule receipts similarly settle their dispatched intent while further reads, navigation and view callbacks require a current attachment/view.

A logical read budget retains one deadline and signal across slices, continuation, invalidation and shared demand; composing attachment cancellation preserves that logical identity. A replacement attachment acquires an independent budget. Restoration passes the caller's logical signal through SDK reads and keeps composed attachment cancellation private to queueing and settlement. Extension-host deadlines cancel their IO while the still-live attachment retains authority to answer its own deadline error; attachment/session revocation suppresses the reply.

lib/backend-async-inventory.test.ts scans every UI TypeScript source (excluding tests and declarations) with TypeScript's compiler API. tests/contracts/backend-async-inventory.ts resolves call signatures to their declarations: HTTP transport calls, network constructors, generated OpenCode Promise methods, HTTP adapter methods and backend event subscriptions are boundaries. Local aliases retain the declaration's identity. Callback registrations count only when their callback reaches a boundary through resolved calls or delegated callbacks; recursive call graphs are resolved to a fixed point. Pure DOM, IPC, calculation and authority-capture helpers are free to change their awaits, timers and local names. The same whole-source scan detects a new backend call in any such module, including a new file. Fetch targets whose literal types resolve to the two declared GitHub origins are EXTERNAL; dynamic targets and additional origins require review.

scripts/backend-async-operations.json records only backend-bearing files: counted boundary declaration identities, aggregate IO-reaching delegated calls and backend-reaching callback registrations. Local helper and setter names are excluded from these identities; standard scheduler/Promise registrations retain their API names. The table below supplies exactly these files' families and authority. Discovery scans all UI sources independently of the table, so a first backend access in any other module requires classification. Formatting, LF/CRLF and unrelated local work preserve these identities; added or removed backend accesses and backend-reaching timers require review. File discovery, stale documented paths, HTTP method names and signal/scope IO classifications have separate checks. Semantic source review assigns each access its actual family, captured authority, admission, publication and cleanup predicates; behavioral owner/revocation tests qualify those invariants. Review also covers dynamic dispatch, equal-count substitutions and callback parameter injection beyond statically resolved declarations.

Run node --import tsx packages/ui/tests/contracts/backend-async-inventory.ts > candidate.json from the repository root. Compare the candidate with the checked-in registry, review changed accesses and their delegated continuations, update the ownership table where needed, then transfer the reviewed entries. Tests read the registry. Run node --conditions=browser --import tsx --test packages/ui/src/lib/backend-async-inventory.test.ts to verify it; its in-memory counterexamples include new HTTP and HTTP-timer operations in an existing backend module and ordinary DOM-only transformations.

File Lifetime Operation families Current authority / retained ownership
components/server-add-field.tsx C inline profile save/pair; focus and completion Strict host flag, mounted generation and captured profile policy; host secret-entry capability gates pairing input and submission; transient pairing cleared before IO; exact flight owns busy and focus publication.
components/settings/servers-settings-section.tsx C profile edit/remove confirmation; selection intent Strict host flag, host server capabilities and mounted hook; edit predicates retain management availability; immutable target policy and management rechecked after confirmation; host Forget precedes awaitable persisted removal; selection callback receives captured profile.
lib/remote-server-request.ts C browse/connect/forget host requests and stable errors Host transport id required before dispatch; current host secret-entry policy gates connect passwords/pairing links before fetch; secret-free connect/browse/forget retain access. Caller signal across dispatch and body; bounded browsing response supplied by the host manager; allowlisted error codes, private credential response bodies discarded.
lib/native/server-selection.ts C+IPC Preferences saved-server selection forwarded to the main renderer Native host validates the Preferences sender/section and exact opener; main renderer revalidates immutable saved policy and the strict host flag before showing the browser. Embedded settings delegate to that same consumer.
stores/remote-project-open.ts A+C select saved server; admit/recover inventory; create ordinary project and select tab; select an open folder tab and record a live one in Recents Captured immutable profile policy, selection identity and caller cancellation checked across admission/recovery/create/publication. Registry owns shared admission. The onCreation lease captures the request/API/attachment before POST; caller-finally discards every untransferred outcome, including rejection and resolved-but-stale creation. Synchronous guarded tab selection transfers the exact occurrence and releases its captured request key. Explicit opening permits one recovery of an unavailable initial inventory. Selecting an already-open folder tab is synchronous; only a non-error project tab writes its Recents access through the host preferences.
components/browse-menu.tsx V+C host capabilities, SideCar list, browse the selected server Mounted selector owns focus and selected policy; shared host metadata and SideCar caches own their reads.
stores/app-tab-close.ts P+C close an instance, temporary project, waiting tab, or SideCar Dispatch by the captured tab occurrence; temporary choices retain the caller's current predicate.
stores/remote-server-removal.ts P+C confirm removal and close matching tabs Recheck the captured profile policy after confirmation and each temporary-project choice; only then detach remaining occurrences.
components/recent-tabs-menu.tsx, components/remote-recent-session.tsx, lib/recent-open-target.ts V+C display recents and select existing tabs; open SideCars or start a remote row's inline flow Launcher and recent row own their visible intent and focus; the SideCar cache, server browser and tab-selection actions own reads and mutations.
stores/recent-projects.ts A+C read and update the host's recent-project metadata on explicit open, rename or remove Read and write through the existing host UI state owner. Queue edits, match the saved policy before persistence, and leave credentials with the backend. Display merges cached metadata without admitting or reading any destination.
components/remote-server-browser.tsx V+C browse folders and publish server-scoped recents; authenticate/pair; Retry; open selected physical path Host API owns browsing/authentication; mounted profile and request generation/controller fence reads and focus. Disposal aborts its reads/opening; saved-policy revocation unmounts the browser. The opening captures the foreground tab selection. Host secret-entry capability gates the credential form and connect dispatch; credentials remain in the form/submitted request. Registry owns explicit inventory recovery and workspace receipt owns admitted creation.
stores/backend-registry.ts A+C candidate metadata, admission, explicit inventory recovery, profile/policy reconciliation, reconnect validation and disposal Exact candidate controller/profile URL/TLS/entry identity; fresh no-store metadata with deadline; current host flag before publication. Registered fan-in signal owns domain reads; validation generation fences metadata replies, superseded live SSE gates follow the latest verdict, and the metadata-failure epoch fences inventory success. Inventory failure stays unavailable until current inventory success. Explicit recovery shares one flight and at most one invalidation follow-up, retains snapshots on failure, and rejects absent/revoked admission. Revocation precedes resource disposal and client removal.
stores/remote-backends.ts A renderer registry composition; backend workspace list after SSE start Host preference/profile getters; Preferences skips instance reconciliation; other renderers retain the admitted client and captured attachment signal through refreshWorkspaceList.
App.tsx A+C foreground timeout/retries; pending liveness → session refresh → messages; folder/temp/SideCar/tab/session handlers; agent/model changes; preview claiming; fullscreen Foreground controller/attachment signal and instance/client checks; delegated action guards; native preview claim and fullscreen are IPC; local launch/admin uses retained client.
main.tsx C+IPC bootstrap; preferences startup-state command installation Page/client bootstrap; native startup-state command ownership.
lib/backend-client.ts C create direct backend client or unregistered createRemoteBackendClient(profileId); authenticated fetch, auth-restored stream restart; backend registry Factory-owned transport/auth/storage/meta/SDK; remote factory uses the local origin's /api/backends/:profileId relay for HTTP, SSE, SDK, media and auth status/login. Saved-profile auth sign-in checks current host secret-entry policy at dispatch; relay credentials remain backend-owned; retained client identity.
lib/backend-relay-authority.ts C+P opted-in relay fetch dispatch, resource/EventSource URLs and metadata proof admission One immutable locally minted proof per candidate, admitted after registry metadata validation. Fetch and URL resources retain that generation across retries; missing proof refuses ordinary dispatch. Bootstrap is limited to metadata and authentication. Caller signals propagate unchanged; server authority revocation fences even cleanup requests without a signal. SDK bases use the plain resolver with this bound fetch.
lib/backend-transport.ts C resolve backend URLs and HTTP transport Per-client URL/fetch ownership; callers supply cancellation.
lib/backend-events.ts A BackendEvents attach/detach; source onDispose subscription; scopeBackendEvent/notify; forInstance subscriptions; reactive signal/signalForInstance Pure synchronous bus; per-attachment controller/source identity fences each delivery and revoked-owner cleanup; absent attachment yields an aborted signal; subscribers retain their captured admission token.
lib/api-client.ts P+C sendRequest/sendRawRequest/error bodies; workspace create/list/delete/cancel/release/clone/temp; worktrees/Git/filesystem/files/config; storage/config/state owners; metadata/auth/remote proxies/control; binary/setup; conversation permission mode/pending/receipts; speech/images/usage/accounts; plugins/integrations; SideCars/previews; all Mission maps/tasks/content/programmed Missions/admission/control/recovery/deletion BackendHttp fetch; caller signal; secondaryRead background queue; mutation request IDs/status receipts; current host secret-entry policy before connectRemoteServer credential dispatch; durable local administration and persisted writes use client lifetime.
lib/auth-recovery.ts C+P auth check/signIn; authenticated fetch/401 probe; body parsing; onRestored subscriptions/notifications Login generation and observation order; signal-owned probe coalescence; Request/RequestInit signal; retained auth client for sign-in/probes and backend-scoped restored subscriptions. Saved-profile clients supply a pre-dispatch credential admission check; host password login retains its own transport policy.
lib/event-transport.ts C+P connectWorkspaceEvents; EventSource creation and dispatch Source/backend transport plus caller callbacks; ServerEvents owns connection generation.
lib/event-source-handlers.ts P attachEventSourceHandlers; message/error/close/ping callbacks Supplied transport callbacks retain ServerEvents source/connection generation; parser callback ownership follows that source.
lib/server-events.ts C+A connect/start/restart/dispose; event batch dispatch; auth acquisition; ping/pong/backoff; reconnect/watchdog; local source startup/attachment; backend fan-in re-export Source lifetime AbortController, connection generation/disposed checks; captured per-attachment fan-in signals; client-owned source connection.
lib/sse-manager.ts A instance event handlers; transport/open/detach callbacks; worktree/session refresh delegation Backend attachment signal and manager disposal; backend-scoped manager ownership.
lib/sdk-manager.ts C+A createClient/createInstanceFetch; generated SDK HTTP; location priority; catalog background queue; 426 setup reporting; 502 error bodies Cached clients retain backend HTTP transport. Each request composes Request/init cancellation with the currently attached backend signal, passes it through priority/background queues and fetch, and checks it across response/body/import awaits before setup reporting. Standalone/pre-attachment clients use caller/client lifetime; request creation reads the pure bus.
lib/server-meta.ts C+A getServerMeta; shared promise/cache; initial host recovery API/client-owned host cache and signal-keyed project snapshots/flights; host transport replies publish the shared host-server-meta secret-entry signal for input and low-level dispatch checks. Each attachment rechecks revocation before publication and releases only its pending request. Recovery joins the pending host read and requests a new one only while the snapshot is missing and its caller still needs it.
lib/project-server-meta.ts A+C attachment metadata; host preview availability and stream-open recovery Captured backend client and reactive attachment signal fence project presentation. Remote projects also read the host snapshot; the local event stream's open can retry a missing host snapshot while the view and attachment still need it. Effect disposal removes the listener and abort revokes presentation.
lib/media-source.ts A+V tool, Markdown and attachment media transfer; passive image validation; attachment download transfer; blob publication/disposal Mounted instance/source identity, attachment and controller span fetch, body transfer and signature validation; each await rechecks attachment authority before canonical passive-image blob publication. Session-media paths use the owning transport, same-origin absolute sources stay inside its namespace, and data/public HTTP sources resolve independently. Explicit downloads share those owner checks and transfer unverified bytes as an attachment only. Source replacement, cleanup and revocation release only the owned object URL. Backend authentication stays in the owning transport.
lib/storage.ts C+A config-owner load/revalidate/read/reconcile/patch; stable-owner retries; state-owner load/patch; Mission preference CAS; per-document settlement barriers and bounded waits; instance data load/write/delete; pending write flush Client/document barriers retain sent mutations across attachments; replacement loads read afresh after settlement. Captured attachment guards owner admission/publication; timeout refuses dependent work while retaining the barrier. Instance persistence and flush retain client ownership.
stores/preferences.tsx A+C ensureLoaded/ensureEditDocument; independent document reads and edit queues; config/state/Mission preference reads/patches; model-library writes; visibility; speech/listening/update feed; recent/project/remote-server/model/thinking/favorite preferences; palette and parent-folder write queues Host presentation uses local storage and its existing per-setting write paths. Server preferences capture their registered backend and attachment; remote edits derive from their own loaded document at their document queue turn. Full initialization joins independently published owner reads. Revocation fences queued dispatch, owner publication and subscriptions while mounted reads expose empty server buckets and host presentation/model inheritance. Mission edits retain storage CAS checks.
stores/model-picker.ts A+C model list preference selection Instance-owned preference accessor; host fallback for absent server model fields; captured preference attachment fences reads.
lib/agent-memory-api.ts C+A memory settings and revision-checked entry operations Local authenticated transport retains its request shape; qualified remote calls capture the backend client and attachment signal through timeout, fetch and body publication; raw workspace IDs at HTTP boundary.
stores/agent-memory.ts C+A+V review, scoped reads, edits, Forget and reconnect demand Injected owner memory API; backend/scope/context generation, pending-read identity, disposed checks and revocable confirmation; per-owner event subscriptions; sent edits retain their revision.
stores/agent-memory-cleanup.ts A+V fresh settings/list preflight, create and send cleanup Native request ID retained across uncertain outcomes; attachment, workspace client/folder and authorized cleanup directory rechecked between stages; owner memory API and session API/actions own creation and send.
lib/native-browser-hold.ts C native browser hold renewal and release while a local desktop view shows a session The view's hold ID and captured workspace/session own each renewal; cleanup stops the timer and releases the hold.
lib/native/memory-cleanup.ts IPC+P native cleanup intent handoff and main-renderer handler Exact local opener/window claim and normalized request; delegated cleanup owns backend work.
components/settings/agent-memory-editor.tsx P+V revision-checked Save and confirmed Forget Review store and selected-entry confirmation signal; the review owns HTTP and publication.
components/settings/agent-memory-settings-card.tsx C+A+V enablement reads/writes, review and cleanup confirmation Qualified project memory API; captured edit owner, request sequence/disposal, scope/context consent and native cleanup request; backend event subscriptions are released on owner change and disposal.
components/settings-screen.tsx C+P+IPC cached host metadata bootstrap; render Preferences memory context; select a saved server Host metadata cache owns the mount read; strict host flag and host server-use capability gate Servers. Resolved Preferences project context; memory card/review and native opener own IO. Saved-server selection delegates an immutable intent to the exact main window; failures stay in Servers.
stores/instance-config.tsx C ensureInstanceConfig/updateInstanceConfig; persisted instance-data hydration Storage client and instance data snapshot; view memo/cleanup; persistence survives attachment replacement.
stores/message-history.ts C addToHistory/getHistory/clearHistory Storage-backed composer history identity, retained client persistence.
lib/hooks/use-app-session-capture.ts C+P capture debounce/flush; shutdown/navigation acknowledgments and record release; late workspace binding hydration Client-state persistence owns saves. Release tracks results by attached record ID and cancels pending creations by exact receipt. Hydration has a captured binding, current predicate and AbortController; IPC listeners follow renderer disposal and generation.
lib/hooks/use-app-session-restore.ts C+P restoreTabs/restoreWorkspace/restoreSidecar; ordered commits; abort timeout; setup recovery and resumeRestoration; remote Retry, unavailable lifecycle and placeholder replacement; release created workspace Restore controller/current occurrence binding/request ID, captured clients; explicit remote recovery owns still-open placeholders independently of the startup preference. After cancelled shutdown, each backend recovers independently. A failed release permits exact reuse only after a fresh owning-backend inventory; a failed or timed-out read falls back to fresh records. Inventory admission reserves workspaces bound to sibling tabs. Uncertain creates retain their request owner; definitive refusals permit another attempt. Cleanup mutations retain their creation request owner.
components/remote-restore-view.tsx V+P Retry, credentials/pairing Connect, and registry recovery Mounted placeholder and AbortController own login IO. Host secret-entry capability gates credential controls and login dispatch. Disposal cancels login and fences detach/recovery after its reply. Retry delegates exact-ID reuse or creation to the guarded restore controller and its shared backend flight; secrets clear on settlement.
stores/app-session-workspace-hydration.ts A+P seed occurrence view; hydrate restored session chains Captured attachment and caller AbortSignal fence every SDK stage; seeding preserves current gestures and explicit occurrence state.
stores/instances.ts A+C workspace create/ready/attach/hydrate; project/worktree/session/catalog/config hydration; refreshWorkspaceList/initializeWorkspaces; remote onOpen inventory reconciliation; volatile native resync; pending snapshots/forms/permissions/inboxes/liveness; recovery-notice coverage probe; timeout/retry/queue continuations; close/delete/release/cancel/restore cleanup Local inventory and SSE drive local readiness. Remote onOpen (A) waits on backendRegistry.initialInventory for the exact captured client, leaving the initial read to registry admission. After the wait, reconciliation requires the same live attachment signal and uses the captured client API; the captured SSE generation fences dispatch and publication, the list request fence guards workspace reconciliation, and the registry's entry and health epoch guard inventory success. Hydration captures signal/client before enqueue and propagates signal through worktree/session/project/supplemental metadata/pending reads, checking before config/pending follow-ups. Descriptor mapping resolves environment preferences on the explicit backend; preference initialization retains that store's attachment authority. Runtime operations combine captureBackendOperation, client/native generation, pending token/controller/request identity. The queued notice probe starts after the successful full recovery releases its slot; it uses that attachment/client, sync generation, directory scope and notice claim to prove exclusions and release only the notice claim. It waits for overlapping recovery and clears only its own check. Sent creation/close/form/permission mutations retain their client/request owner while runtime projection/readback uses A. Direct and observation-triggered creation cancellation share one bounded flight on the captured request/API/attachment through AbortCreatedWorkspaceCleanup; confirmed settlement fences subsequent dispatch, and exhausted flights permit a later explicit demand.
stores/app-tabs.ts C select created tab → captured claim release; close tab → closeWorkspace Tab occurrence identity; an explicit creation lease is checked before attachment and selection, then releases its exact request/API/attachment. Dispatched release/deletion retains its captured client ownership.
stores/closed-workspace-drafts.ts C+V closed-project draft handoff; wait for session hydration; restore saved session chains Backend/folder identity isolates the bounded vault. A consumed claim and current-instance predicate fence asynchronous hydration; existing occurrence state and touched sessions win. Delegated session reads retain their backend authority; placeholder Close requires the exact saved occurrence.
stores/temporary-instances.ts C open/keep/discard/close temporary instance; cleanup on failed or interrupted open; recent-folder persistence Temporary creation uses the local API. Departure cancels the exact creation with keepalive; only a server advertising combined cancellation and abandonment also removes the unused empty folder. Keep and Discard use the workspace owner and decode its raw ID at the HTTP boundary.
stores/worktrees.ts A+C queueWorktreeRequest/load/ensure/reload; ready handler → sessions; create/delete/moveSessionFamily; parent-session slug changes; uncertain family-move reconciliation captureBackendOperation/signal, client/native generation/folder and request lane; compatible coalescence and owned finally. Sent create/delete/move retains client/request ownership; invalidation, session/worktree readback and move-result projection check the captured A and owned move record.
lib/hooks/use-instance-metadata.ts A loadInstanceMetadata/loadInstanceProjectMetadata; project/location/MCP parallel reads Entry composes signalForInstance with caller signal and refuses aborted admission; SDK reads receive the signal. Client/location/metadata generation/pending identity govern coalescence and publication; finally releases only the matching request.
lib/contexts/instance-metadata-context.tsx A ensureMetadata; view/provider metadata demands captureBackendOperation with view disposal/current checks; retained demand reacquires operation.
lib/hooks/use-foreground-refresh.ts A backend controller allocation/open/status/detach; foreground trigger Captured backend signal, per-backend controller map and cleanup.
stores/session-api.ts A+C refreshSessionCatalog; fetchV2Sessions/complete inventory/runtime status; restored parent-chain hydration and placement reads; fetch/load-more/load-all/search and move reconciliation; create/fork/delete session; guarded blank-session cleanup; fetch/load agents/providers; loadMessages/invalidation retry Captured attachment/client/native generation plus caller signal, request IDs/message intent and page lanes/controllers. Catalog refresh/agent/provider lanes join current owners; readiness, parent-chain retries, cursor pages and runtime status recheck the captured owner. Restore reads retain the caller's signal at dispatch and check placement evidence and move identity before publishing; deferred departures run after the chain reads and remove only the local projection. Inventory, cursor and search lanes defer to pending move reads; complete inventory revalidates retained placement under its request, and an exact missing result excludes that session from the current search even after the move settles. Blank-session cleanup passes the live signal to the backend's guarded deletion. Sent mutations retain captured client; publication/readback uses A.
stores/session-favorites.ts A+C favorites read/reconcile and save; storage invalidation and reconnect Instance-owned backend; effect and attachment signals cancel coalesced reads. Generation, read epoch and snapshot source/revision fence publication. A sent save retains its client; only the current owner publishes the acknowledgement and refreshes.
stores/session-message-pages.ts P listMessageWindow; message cursor/limit reads Caller client and AbortSignal; deferred-media request header.
stores/session-events.ts A terminal status reconciliation; fetchSessionInfo/ensureSessionStatus; created/moved/started continuations; exact move placement reads and revalidation; reconnect and worktree-publication retries; delayed worktree/session/message refresh; terminal inbox/message follow-up; qualified notice actions Event authority captures signalForInstance/client/native generation; fetchSessionInfo checks it after SDK read. pendingSessionFetches joins only a current owner with the same attachment signal under the instance/native generation/session key; finally checks pending-entry identity. Move timers cancel with the attachment and settlement checks the latest move for that instance/session. Reconnect re-admits unresolved IDs on the same attachment with a fresh generation and an exact read. Worktree publication admits retries under current authority; catalogue revalidation also checks its caller's signal and retained placement evidence. Exact reads distinguish a served placement, a typed departure and a missing session; departure or absence removes the projection while retaining drafts. Notice lifetime and navigation retain the event attachment; backend-qualified claims and bubbles separate homonymous native IDs. An action targeting a suspended occurrence selects its existing restore placeholder, preserving its drafts and explicit recovery ownership.
stores/session-model-reconciliation.ts A reconcileSessionModel; catalog load → model choice publication Captured signalForInstance, native generation, client/current session-model snapshot; delegated catalog reads.
stores/session-models.ts A getDefaultModel captureBackendOperation; delegated provider/agent/default model ownership.
stores/session-fork.ts P+C forkAfterMessage; paginated source messages; native fork; abandoned fork removal Caller isCurrent predicate and captured SDK client; fork/removal is durable sent mutation; caller must supply attachment guard.
stores/session-actions.ts A+C admit/start/revert/send/command/shell; abort/wait; agent/model switch; rename/compact/background; technical-part/group deletion captureBackendOperation plus client/native generation/current predicates and action queue; admitted sent mutations retain captured client, subsequent UI effects/readbacks require current operation.
stores/session-archive.ts A+C serialize native archive flag and authoritative list readback Attachment captured before the action queue; client/generation/session membership fence dispatch and readback; sent native mutation retains its client.
stores/session-state.ts A cleanup queue; catalog/inbox/message checks; deleted-session surface reconciliation Backend operation, client/native generation and request ownership fence cleanup and passive occurrence reconciliation.
stores/blank-session-cleanup.ts A+C cleanupBlankSession; message/session/inbox/list/active checks; blank removal captureBackendOperation and client/native generation; dispatched deletion retains client.
stores/sessions.ts A reconnect session refresh and model/catalog event delegation Captured signalForInstance passed into session reads.
stores/session-list-restoration.ts P restored session selection/catalog hydration Delegated session store lifetime; restored view/session identity.
stores/commands.ts A fetchCommands; command catalog coalescence signalForInstance, SDK client/location/request ID.
stores/opencode-data.ts A transcript get/syncMessages/syncAuthoritative; authoritative resync/rotation/drain queue; inbox sync; seed messages; delayed projection/reconnect follow-ups captureBackendOperation, client/native generation, transcript entry identity, controllers and projection epoch; captured authority checked through sync/queue work.
stores/opencode-data-read-testing.ts P+COMPUTE readFixture/list/settleSync; seedStatus; test seam construction Synthetic client/timers; delegated production status handling retains its source authority.
stores/history-window.ts P readHistoryWindow Caller AbortSignal and stable history window request.
stores/history-search-sessions.ts A openHistoryMatchSession/openListedSession; get session/parent chain/messages; navigation captureBackendOperation, gesture, view predicate/controller, client/native generation.
stores/session-history.ts A+C ranked/history pages/walk/find; plan/execute technical-part deletion; prune history captureBackendOperation, client/native generation and parent signal; each cursor page owned by same request; sent prune mutation retains client.
stores/session-outline.ts A createSessionOutline; delayed outline read; cursor/checkpoint delta pages; catch-up retry captureBackendOperation plus view/controller, client/native generation and outline-work identity checked per page/publication.
stores/timeline-previews.ts A createTimelinePreviews; debounce; batches of 12; bounded cache captureBackendOperation plus view/controller/current scope; cache records attachment signal; per-batch check.
stores/session-pruning.ts A+C pruneMessageContent; read authoritative message after pruning captureBackendOperation, client/native generation; server prune is durable sent mutation, readback/publication attachment-owned.
stores/session-pruning-events.ts A refreshSessionContent; native prune event → messages/inbox captureBackendOperation/current with supplied signal.
stores/mission-content.ts A content adapter; backend event invalidation/detach captureBackendOperation at caller adapter; store demand retained separately.
stores/mission-creation-drafts.ts A reconcile an uncertain creation by its exact receipt Scoped in-memory hold retains the original request. Reads coalesce by request and client/generation, use the owning backend and a captured attachment/controller, and confirm only the matching current receipt.
stores/missions.ts A Mission panel/task API adapters; coalesced event/reconnect refresh scheduler captureBackendOperation plus generation/current; queued refresh retains admitted owner.
stores/mission-calendars.ts A programmed Missions list; save, pause, resume and delete, whose answer is the list One read at a time with one trailing read; instance/directory identity fences a late answer; the list read carries its own timeout signal.
stores/mission-task-session-reads.ts P demand; bounded session/parent-chain hydration and metadata loads Supplied signal plus client/native generation/current view demand.
stores/mission-task-sessions.ts A session-reader adapter; generation/client session lookup captureBackendOperation with native client/generation; retained task view demand.
lib/mission-coordinator-message.ts A+P+C sendMissionCoordinatorMessage; owner-routed admission read then session send captureBackendOperation plus caller current predicate and captured SDK client; rechecked after admission/hydration; sent prompt retains client.
lib/mission-cleanup.ts C+P deleteMissionRequest; status/error bodies Request ID and supplied fetcher/signal; durable server deletion transaction.
lib/mission-lifecycle-request.ts C+P missionLifecycleRequest; status/error reconciliation Request ID and supplied HTTP signal; durable server lifecycle transaction.
lib/mission-mutation.ts C+P missionMutationRequest; status/error reconciliation Request owner and supplied HTTP signal; durable mutation transaction.
stores/permission-receipt-cache.ts A startRead/demand; cached receipt pages/coalescence captureBackendOperation, read controller/cancel/current and retained cache demand.
stores/shell-store.ts A+P list/output/load; dirty trailing refreshForEvent; remove Captured signalForInstance, request signal/current and lane identity; API callback gets signal; sent remove retains SDK client.
stores/shells.ts A native Shell SDK adapter; event refresh captureBackendOperation/current and location-scoped SDK client.
stores/session-goal.ts A+P goal reads; event/open/reconnect refresh scheduler; runSessionGoalCommand Factory supplies signalForInstance to the goal store; reconnect timers capture the scheduling attachment signal; session commands use action authority and guarded readback.
stores/session-automations.ts A+P automation reads; execution/shell/open/reconnect refresh scheduler; runSessionAutomationAction Factory supplies signalForInstance to the automations store; reconnect timers capture the scheduling attachment signal; mutations use captured backend and fence earlier reads.
stores/integrations.ts A catalog/binding factories; event debounce/reconnect/open; connection/session epochs; detach cleanup Both factories receive signalForInstance; reconnect scheduler captures attachment signal; backend owner guards connection epochs and revokes bindings while retaining their demand.
lib/integrations-api.ts A+P+C fetchIntegrations/fetchIntegrationBinding/installIntegration/attachment request Instance-owned backend HTTP and captured attachment/caller signal checked before dispatch and after response/body reads; raw workspace id at HTTP boundary; sent mutations retain their server-side outcome.
stores/plugin-controls.ts A+C controls read/cache/demand; activation; instance-owner API adapter Backend resolved from instance key, raw workspace id at API boundary; captured attachment signal and cache request generation fence reads/publication; sent activation retains selected client.
stores/plugin-controls-events.ts A+P config/plugin/reconnect event refresh dispatch Attachment/event owner delegated to controls store.
stores/plugin-sources.ts A+C sources read/demand/event debounce; add/install/remove Instance-owned backend API and raw workspace id at boundary; captureBackendOperation/signalForInstance through callbacks; removal deduplication and cleanup use captured signal/attempt identity; sent mutation retained, follow-up refresh checks admitted signal.
stores/plugin-package-actions.ts A+C runPluginPackageAction; native check/update captureBackendOperation/current and SDK client; dispatched update retains client.
lib/panel-extensions-api.ts A+P+C extension list/panel/assets/work-items/API4 request adapter; activate/install/remove/consent Contextual calls use lib/panel-extensions-backend.ts to capture instance-owned transport/attachment; raw workspace id at wire boundary; request checks composed signal/current before dispatch and after response/body; standalone local factory retains its transport, sent mutations retain server-side outcome.
components/panel-extensions/api4-channel.ts A+C grant-scoped images/conversations/preferences/notes; work-item branch lookup, checkout and family move; prefill; backend events; request/timeout/reply Captured attachment, per-request controller, session and connection fences; invalidations stay on the owning backend. Host dialog and branch revalidation gate checkout/move. Sent mutations retain request ownership.
components/panel-extensions/assets-channel.ts A asset list/cursor/read; thumbnail conversion; request/timeout/reply captureBackendOperation plus request controller, connected/generation/disposed/current; thumbnail is local bitmap computation.
components/panel-extensions/work-items-channel.ts A+P work-item list and URL lookup → external URL open/reply Production caller supplies captureBackendOperation; request controller/disposed and target identity; supplied operation checked across read/open/reply.
components/panel-extensions/use-panel-extensions.ts A+C coalesced/trailing list refresh; activate → refresh; reconnect/reactive attachment refresh Instance-owned adapter; captureBackendOperation with controller/generation/disposed, instance/active/connected checks; generation-owned read and activation records fence deduplication/cleanup; lifetime resets manager presentation; sent activation is retained mutation.
components/panel-extensions/extension-panel.tsx V+A panel HTML load; local srcdoc construction; iframe handshake; channel factory and cleanup HTML read and frame messaging share captured attachment/view signal; revocation closes port and clears document; generation/current/disposed fences publication/handshake; channel requests independently capture A.
components/panel-extensions/extension-manager.tsx A+C catalog load/refresh; inspect ZIP/catalog; install/installCatalog/remove; consent and runtime refresh Controller captures project backend/attachment before administration; lifetime-keyed view generation/disposed/controller and abortable FileReader fence presentation; runtime current guards results and rereads; admitted install/removal runs once.
stores/images-conversation.ts A+C resolve/show/openImagesConversation; agents and session navigation captureBackendOperation/current for read/navigation/publication; conversation creation uses the owning backend API and signal, retaining its admitted client.
stores/session-instructions.ts A+C syncVoiceModeInstruction/syncSessionInstructions; native instruction entry put captureBackendOperation and caller signal/current; sent instruction mutation retains captured SDK client.
stores/session-previews.ts A+C occurrence preview open/restore/dismiss; capability issuance/deletion; lifecycle and pagehide cleanup Qualified instance/session identity, original gesture and attachment fence publication. Captured client/token owns cleanup; dismissal keeps saved logical history, and pagehide deletes with keepalive.
stores/sidecars.ts C ensureSidecarsLoaded/openSidecarTab; pending load; storage/event reconciliation Local client cache and pending identity; local-source events; tab demand retained.
stores/speech.ts C loadSpeechCapabilities; shared promise/cache Local API/client capability cache and pending owner retained through reconnect.
stores/conversation-speech.ts V+C runConversationQueue; Classic summary playback Conversation playback queue and AbortController; playback request/controller owns stop.
lib/hooks/use-speech.ts A start/toggle; manual playback captureBackendOperation plus playback controller and content identity; owner disposal stops playback.
lib/speech-playback.ts V+C playSpeech; binary synthesis and audio playback The renderer's own backend serves speech even for an attached project. The caller's signal covers the request, buffered body or stream, and audio cleanup.
lib/hooks/use-live-voice-conversation.ts A+V local speech WebSocket and session controller Renderer server origin and matching local session/client, provider engine and explicit consent; target change or disposal stops audio and socket.
lib/live-voice-consent.ts C persist accepted provider notice Renderer server origin, provider and notice version own the write; native profile HTTP or browser storage.
lib/live-voice-session.ts V provider socket, audio and agent turn callbacks Captured audience, run and socket lifetime; signal fences pending work and stop releases capture and connection.
stores/live-voice-agent.ts A+C scoped native session context/message reads and prompt delivery Captured session/client and current conversation predicate; native request signal and prompt admission.
stores/voice-conversation-engine.ts C native engine read/write and storage-driven refresh Renderer server and desktop profile; read/write sequence fences publication. Browser engine stays in origin storage.
stores/opencode-setup.ts C status/read/update/reload/start; continueOpenCodeSetup; workspace-resume callback Local server bootstrap client, setup generation/epoch/current; retained recovery demand.
lib/hooks/use-remote-server-profiles.ts C legacy saveServer/connectSavedServer/proxy/native window; submitServer/removeServer; SSH validation; probe/connect/forget and persistence Local host client; strict flag and mounted view; captured id/origin/TLS/SSH before waits, rechecked before each continuation; host secret-entry capability checked before pairing work and again after waits before credential dispatch/native handoff. Guarded serialized profile edits and sent writes retain durable results.
lib/hooks/use-desktop-connection-launch.ts C+IPC connect launch queue → remote profile flow; register/acknowledge Launch/disposed/current attempt; HTTP probes/proxy delegated to retained client; native registration cleanup.
lib/hooks/use-commands.ts A+C workspace/session/Mission/settings actions; revert-clear; navigation captureBackendOperation/current for native session work; workspace-open/admin/persistence delegates retain client lifetime.
lib/filesystem-events.ts A+P queueFilesystemInvalidation/publish; passive 100ms/5s merge; workspace-stop cleanup; createDebouncedRefresh Event merge captures signalForInstance; abort cancels/removes only its pending timer; callback checks signal/pending-entry identity before publication. Generic createDebouncedRefresh owns its caller's callback/view timer.
components/agent-selector.tsx V+P hydration gate → fetchAgents; handleChange Selected instance/component callback; fetchAgents supplies attachment/client guards; post-hydration continuation uses view selection.
components/model-selector.tsx, components/thinking-selector.tsx V+P hydration gate → fetchProviders; model/thinking change and focus timers Selected instance/view demand; provider read supplies attachment/client authority; local focus timer is DOM.
components/directory-browser-dialog.tsx C initialize/loadDirectory/navigateTo/path submit/open/create folder; directory cache Local filesystem API client; openingGeneration/open guard and per-directory request identity; dispatched folder creation retained.
components/remote-server-dialog.tsx C listSshHosts in the legacy dialog and Servers editor Retained local server administration client; open dialog/multiBackend effect lifetime fences host-list publication through its cleanup predicate. The editor also cancels its read on cleanup. Both editors reject pairing input/submission when the host secret-entry capability is refused, retaining address-only administration.
components/new-instance-dialogs.tsx C+IPC clone repository; browse destination; clone completion → open Local clone API/client and submitted destination; native picker; workspace-open callback ownership.
components/opencode-binary-selector.tsx C+IPC validateBinary/debounce; native browse; validate-and-add/custom submit Local server binary probe/client and validation request/view state; native filesystem picker.
components/settings/opencode-logs-action.tsx C+V explicit host log snapshot opening/refresh Host settings client; view AbortController fences publication and aborts on close, executable change, refresh and disposal.
components/instance-service-status.tsx A+C toggleMcpServer connect/disconnect captureBackendOperation/current and captured SDK client; sent MCP mutation retained.
components/instance/instance-shell2.tsx A+C draft agent/model defaults; draft session create/activate; first prompt/command/shell; preview open; server metadata; elapsed UI timers captureBackendOperation plus current instance/draft and creation promise identity; first sent action retains client; metadata uses client cache; DOM timers separate.
components/history-message-preview.tsx A preview session/message reads; open search match captureBackendOperation plus controller, client/native generation and view-current predicate.
components/history-search-results.tsx P reactive search-match session labels Delegated history-search session-label reader owns attachment, view and request cancellation.
components/environment-variables-editor.tsx, components/settings/opencode-settings-section.tsx C environment and log-level preference updates Durable preference/storage client owns persisted writes.
components/instance/shell/useInstanceSessionContext.ts, lib/shortcuts/navigation.ts P session/tab selection Delegated session/tab request, attachment and client owners; keyboard dispatch stays local.
components/instance-tab.tsx C+DOM keep temporary workspace Submitted keep operation retains its workspace client; tab rendering stays local.
components/interruption-dock.tsx A+C+DOM form reply/cancel Delegated pending-request operation owns admission and publication; sent replies retain their client.
components/message-timeline.tsx A+DOM timeline preview demand Delegated timeline-preview controller owns attachment and view/request authority.
components/instance/shell/right-panel/RightPanel.tsx, components/instance/shell/right-panel/RightPanelCustomizationPopover.tsx A+C+DOM extension demand and activation Delegated extension request/view controller and attachment; dispatched activation retains its client.
components/instance/shell/right-panel/tabs/FilesPanel.tsx, components/instance/shell/right-panel/components/WorkspaceTree.tsx A+C+DOM files/tree/Git demand, refresh and mutations Delegated tree/Git request lanes, attachment and view authority; sent mutations retain their client; native file open stays IPC.
components/prompt-input/PromptAsideWindow.tsx A+C+DOM aside submission Delegated aside action owns session/view/attachment; sent prompt retains its client.
components/settings/notifications-settings-section.tsx, lib/native/view-menu.ts, lib/theme.tsx C+DOM+IPC persisted notification, timeline and theme preferences Preference/storage client owns writes; rendering and native menu dispatch retain local lifetime.
components/git-diff-view.tsx A worktree/commit diff load and invalidation reload; Monaco import captureBackendOperation, effect AbortController and current view; import is COMPUTE.
components/workspace-file-view.tsx A load/explicitRefresh; file preview and filesystem-triggered reload; Monaco import captureBackendOperation plus effect controller/current path/view and signalForInstance.
components/workspace-file-editor.ts A+C save; fresh preview/conflict check → write → readback captureBackendOperation, generation/disposed/current path; sent file write retains client, readback/view effects retain operation.
components/worktree-selector.tsx A+C handleChange/create/delete; ready reload; path copy/native open captureBackendOperation/current for selection/follow-up reads; durable sent mutation; copy/picker is IPC.
components/instance/shell/right-panel/useWorkspaceTree.ts A load/listWorkspaceFiles; directory/invalidations captureBackendOperation plus controller/current tree scope; retained visible tree demand.
components/instance/shell/right-panel/useGitChanges.ts A+C loadGitStatus/reconcile selection; SDK VCS timeout/fallback; diff open; passive refresh; stage/unstage/commit captureBackendOperation, controller/generation/disposed/current and background read signal; sent Git writes retain client, follow-up selection/read owned by request.
components/instance/shell/right-panel/useGitHistory.ts A refresh/select; history and commit pages captureBackendOperation plus effect controller/selection identity.
components/instance/shell/right-panel/useGitInit.ts A+C initialize → refreshAfterAttempt → sessions/worktrees captureBackendOperation/current/disposed; sent init retains client; subsequent reads retain admitted operation.
components/instance/shell/right-panel/core-runtime.tsx A runtime/catalog refresh callbacks captureBackendOperation/current and captured instance/client.
components/instance/shell/right-panel/tabs/StatusTab.tsx P+C removeShell; background Shell demand and actions Delegated Shell store attachment/current; sent remove retains client; focus microtask is DOM.
components/instance/shell/right-panel/tabs/MissionControl.tsx A+V+P openActor/session hydration; map/task/activity reads; actor/conversation open; refresh/Mission navigation captureBackendOperation is captured before actor/scheduled-conversation hydration and passed through its reads. Navigation, error catches and map-refresh continuations combine that signal with view/intent/conversation epoch/client/native generation/selected schedule, while the view's retained intent remains independent.
components/unified-picker.tsx A workspace snapshot/search; debounce/retryFileSearch; skill list captureBackendOperation, signalForInstance, controller/request ID and selected directory/view; compatible snapshot cache owner.
components/session-list.tsx A+C catalog load-all/more/reload/search debounce; delete/bulk-delete/rename; favorites demand and toggle captureBackendOperation/current for handler continuations; catalog and favorites stores guard their own reads; durable submitted mutations; age/focus timers are DOM.
components/session/session-view.tsx A+C inbox sync; send/manage queue/run Shell/abort/background/revert/fork; renamed fork → messages captureBackendOperation/current for explicit action follow-ups; delegated inbox/message/action owners; sent mutations retain captured client.
components/session/conversation-permissions.tsx V+C read and change the conversation permission mode; refresh on matching native events and reconnect The conversation view owns its subscriptions and coalesced, abortable reads. Writes target the owning backend and conversation; only the live view publishes and reconciles their result.
components/session-preview-view.tsx A+C+IPC preview/history/comment target; remote dismissal Instance/backend-owned capability and isolated source map to application addresses; same-application navigation reuses the capability, other destinations use guarded creation. Store attachment/navigation authority fences requests and retained-client cleanup; native history/locations map to logical addresses.
components/prompt-input.tsx A handleSend; voice start callback; submission follow-up captureBackendOperation/current plus delegated recording/action ownership; UI timers separate.
components/prompt-input/usePromptAside.ts A ask; side conversation read/send captureBackendOperation, controller/generation/current, client and signalForInstance.
components/prompt-input/api-recording-controller.ts V+C recording finalization/transcribeAudio Per-capture abort controller and microphone lease own encoding, transcription and result; retained local transcription client.
components/prompt-input/usePromptVoiceInput.ts A+V dictate start/toggle and transcript application Captured backend attachment, session and draft revision; recording controller owns microphone and inference.
components/live-voice-conversation-window.tsx V controller start/consent/stop and playback actions Displayed live voice owner and provider conversation lifetime.
components/prompt-input/usePromptState.ts C composer state; delayed history record/persistence Physical directory/project history identity and storage client; view timer cleanup.
components/provider-auth/provider-manager-modal.tsx A+C load/refresh provider data; key/OAuth/command authorization; code submission; attempt cancel; URL open/copy captureBackendOperation, client/location/load version, controller/disposed and signalForInstance; admitted auth attempts have explicit attempt IDs and cancellation; native URL/clipboard separate.
components/provider-auth/provider-accounts.tsx A+C read; setAutomatic; activate/remove/update/rename/select credential/account captureBackendOperation, view controller/disposed/current and location/client; persisted credential/account mutations retain admitted client.
components/provider-auth/provider-model-visibility-manager.tsx C single/provider model visibility changes Serialized persisted preference writes in preferences store; UI focus microtask separate.
components/session/provider-usage-panel.tsx A usage interval/manual refresh and source change captureBackendOperation with client/generation/current; view-owned polling timer.
components/integration-row-binding.ts A+C demand binding; passive open-document reads; named-document activation; attach/detach Action captureBackendOperation with controller/epoch/generation/current/disposed; binding demand tracks view identity/catalog IDs while the binding store retains/rebinds demand across attachment change; passive offers acquire the row's current attachment and controller; reactive signal effects clear obsolete offers; sent mutation has target/request owner.
components/integration-state-line.tsx P application installation, attachment, detach and offer selection Delegated installation/row-binding handlers retain captured action, offer and attachment authority.
components/integration-host-installation.ts A+C open installation/consent workflow captureBackendOperation, epoch/controller/generation/disposed/current; submitted install retained.
components/plugin-activation-controls.tsx P integration binding and application installation from Plugins rows Delegated binding/installation handlers capture backend attachment and exact Location/session; row disposal and invalidation revoke pending consent.
components/session/session-goal-line.tsx P runSessionGoalCommand Session goal demand and delegated session-action attachment authority.
components/session/session-automations-block.tsx P runSessionAutomationAction Session automations demand and delegated attachment-scoped confirm and action authority.
components/mission-tracking.tsx P onOpenActor callback Captured actor/selected Mission view; parent navigation callback owns session hydration.
components/mission-selected-actions.tsx P onAdmitted; missionStore.refresh; briefing.ask Selected Mission view predicate; delegated map/admission/action owner.
components/tool-call.tsx P+DOM tool header/IO copy; action-menu callbacks; speech toggle/playback Delegated useSpeech operation owns synthesis; selected tool/header callback owns action; clipboard/renderer/cache/focus stays view-local.
components/tool-call/output-images.tsx P+V mounted tool image source resolution Instance/source accessor delegates HTTP, attachment checks and object URL release to createMediaSource; image loading/error presentation remains element-owned.
components/opencode-setup.tsx, components/settings/opencode-update-card.tsx C refreshOpenCodeSetup Local setup/bootstrap client with setup generation/current predicate.
components/locale-selector.tsx, components/settings/advanced-settings-section.tsx, components/settings/chat-settings-section.tsx C updatePreferences Storage client persists locale, advanced and chat settings.
components/settings/image-settings-card.tsx, components/settings/websearch-settings-card.tsx P+C settings.save Delegated settings captureBackendOperation/current; durable submitted settings mutation.
components/settings/saved-remote-servers-card.tsx C connectSavedServer Delegated probe/proxy/native handoff attempt with retained local client.
lib/keyboard.ts P+C handleCloseActiveTab Delegated tab identity and workspace-close client mutation; keyboard dispatch is DOM.
components/plugin-row-actions.tsx A+C runRemove; check/update; source mutation and refresh captureBackendOperation plus generation/controller/disposed/current; sent package/source mutation retained.
components/permission-receipts.tsx A load/read receipt pages captureBackendOperation, request ID/generation/controller/disposed/current.
components/message-block.tsx A+C background running work; delete message/group; copy reasoning captureBackendOperation/current and delegated session/history action owners; clipboard/layout timers separate.
components/message-item.tsx A+C attachment download; copy; delete technical parts Attachment resource fetch and selected message identity; deletion uses captureBackendOperation/current; clipboard/download owns resource lifecycle.
components/message-section.tsx A restore/loadMore/copy selection/pageWindow/locate; ranked search and cursor windows captureBackendOperation plus controller, view/session generation/current and signalForInstance; per-page operation retained.
components/tool-call/renderers/task.tsx A child-message demand/load; child transcript copy captureBackendOperation/current; caller signal passed to child-message reader.
components/markdown.tsx A+V+COMPUTE renderSnapshot/highlighter import; local-image candidates; route session/external links; metadata read Render request/disposed/current and deferred-render timer; instance-owned preview and project metadata demand; mounted media source owners fence body reads and revoke blobs; rendering is local.
components/markdown-session-links.ts A+V open session preview or project-file reader Qualified instance and backend attachment own preview state; current attachment gates routing and fences late errors; worktree/session directory resolves file paths.
components/markdown-bare-paths.ts A+V existence-gated bare-path file links Session-bound markdown walks re-read the container at wrap time; one coalesced TTL-bounded directory listing per worktree directory fails closed and never converts missing files.
components/version-pill.tsx C metadata read Retained server metadata client/cache.
components/mission-briefing.tsx A+C ask coordinator captureBackendOperation, client/generation/current; delegated admission/send mutation.
components/mission-cleanup.tsx A+C retry preflight; delete; reconcile conflict receipt Captured backend and exact request identity retain the cleanup transaction; receipt reads settle without replay.
components/mission-creation-start.ts A+V+C explicit creation ACK continuation to one Play Captured attachment, view/client/native generation and project/directory; consumed continuation and durable lifecycle request identity; selected backend owns dispatch.
components/mission-task-preview.tsx P+V expanded-row map/task/native conversation demand Exact instance/mission/unique view owner; Mission store and task-session reader own captured attachment, bounded pages, publication and release.
components/mission-editor-schedule.ts A+C readText/reload/saveJournalEdit/reconcile; capability/content reads captureBackendOperation, controller/generation/current/request ID; persisted Mission edit retained, continuation follows operation.
components/mission-editor-sources.ts A read local branches/schedules; cursor/source reload captureBackendOperation plus view controller/generation/current and signal.
components/mission-editor-repository.ts A repository discovery/retry captureBackendOperation, view controller/generation/current and signal.
components/mission-editor.tsx A+C useSavedDefaults/save/reopen; Mission create/edit/delete/reconcile captureBackendOperation plus view generation/controller/current/request ID; durable sent mutation and default persistence.
components/mission-lifecycle-controls.tsx A+C checkStatus/act/confirmStop/reconcile captureBackendOperation, epoch/current/request ID; lifecycle receipt/transaction retained.
components/mission-model-library.tsx A+C save/remove/reload/reset/select captureBackendOperation/current for view work; persisted model preference writes retain storage client.
components/mission-playbook-reader.tsx A playbook list/load and openGuide captureBackendOperation/current with view cleanup.
components/mission-preferences.tsx A+C commit/reload/resetProfiles/repair; serialized preference write captureBackendOperation/current and parent signal for view; storage CAS/client owns durable persistence.
components/mission-profile-controls.tsx A profile catalog/default hydration; delayed read and selection captureBackendOperation, controller/generation/current; retained profile view demand.
components/mission-reader.tsx A retryTarget/openActor; map/task more/load; conversation navigation captureBackendOperation, generation/current/disposed; delegated page and session readers receive signal; clipboard/layout separate.
components/mission-recovery-button.tsx A+C recover captureBackendOperation/current/disposed; durable recovery mutation retained.
components/mission-subagent-depth.tsx A+C read/save; delayed depth settings request captureBackendOperation, controller/epoch/generation/current; persisted depth mutation retained.
components/preferences-window.tsx C+IPC flush; applyRequest; project SDK context; request/persistence queues; close/scroll flush Native preferences request generation, sequential queues and current window request; durable storage flush; instance SDK cache cleanup.
components/auth-recovery-dialog.tsx C signIn Retained auth client/login generation; component cleanup for view.
components/interruption-permission.tsx C+P submit/cancel/respond Request/permission/form identity and delegated response authority; durable admitted response; focus animation is DOM.
components/folder-selection-view.tsx, components/instance-tabs.tsx C+P browse/drop/open; rename or remove a recent Local workspace client and delegated preference/native project mutation; view callback ownership. Empty tabs render remote recents and folders in separate panels and keep Settings as the profile editor.
stores/project-names.ts C renameProject Captured project/instance identity; SDK project update and persisted recent-folder name.
components/settings/config-files-settings-section.tsx C loadContent/loadFiles/file-change/reload/save; discard confirmation Local server configuration client; selected file/open editor demand and dirty state; durable config-file write.
components/settings/opencode-login-start-card.tsx C load/change login-start configuration Local admin client; disposed guard; durable setting mutation.
components/settings/remote-access-settings-section.tsx C refreshMeta/toggleExpanded/allow-connections/password submit Local admin client and auth/settings request state; durable server configuration.
components/settings/remote-control-settings-section.tsx C load/refresh/poll; start/stop/previews; pairing/create/copy/revoke Retained local server administration client; view cleanup/current polling state; durable device/control mutations.
components/settings/sidecars-settings-section.tsx C create/delete SideCar Retained local SideCar API client; durable server mutation and SideCar reload.
components/settings/sidecars-direct-https-card.tsx C read serving-backend metadata; set host SideCar HTTPS opt-in Serving-backend local-request metadata gates the card; the local server preference document queue owns its mutation. Project-backend selection leaves this host-only control unchanged.
components/settings/opencode-setup-panel.tsx C install/start/restart/reload; explicit check Local setup client and component lifetime; explicit maintenance retains dialog ownership.
components/settings/preferences-project-context.ts A backend admission; owner workspace list; coalesced project refresh Qualified instance key and durable server identity; captureBackendOperation plus view/controller/epoch/disposed/current; scheduler callback signal. Missing and replacement owners stay inactive.
components/settings/usage-settings-section.tsx A load; owner discovery/cached usage/fresh usage; coalesced event refresh captureBackendOperation, epoch/disposed/current and signal; verified owner/identity/connection tuple and freshEpoch fence.
components/settings/useImageSettings.ts A+C load/mutate settings Captured backend API and raw workspace ID; captureBackendOperation, effect controller/disposed/current, revision and reading/writing/trailing lane; HTTP carries operation.signal; submitted write retains client, publication/follow-up uses A.
components/settings/useWebSearchSettings.ts A+C load providers/integrations/settings; mutate settings/key connection/remove Owner backend API/raw workspace ID and qualified SDK client; captureBackendOperation, controller/disposed/current and caller signal; persisted settings/credentials retained.
components/settings/notification-routing-table.tsx C serialized routing preference writes Writes promise tail and storage client; durable preference persistence.
components/settings/hotkeys-settings-section.tsx, lib/hotkeys.ts C behavior/hotkey preference mutations Storage client persistence; local current row/focus guards.
components/settings/voice-conversation-card.tsx V+C voice configuration and engine reads/writes; reconnect and storage refresh Renderer server preference owner, exact provider draft, mounted publication and engine write sequence.
components/settings/voice-manual-credentials.tsx components/settings/voice-playback-card.tsx C speech credential and playback settings saves Renderer server preference owner and mounted draft publication.
components/settings/theme-scheme-settings.tsx, components/transcript-filters.tsx C theme discard/select/color/reset/save/delete/mode/queue; filter save queue Storage preference client, per-setting serialization; view selection/dirty guard.
stores/releases.ts, components/settings/info-settings-section.tsx C metadata/release refresh/interval; feed change; copy/open sponsor Metadata/storage client plus current view/timer cleanup; native update/link actions separate.
lib/hooks/use-app-lifecycle.ts C+IPC startup/cleanup; storage lifecycle and desktop event subscriptions Application/client bootstrap; native listener cleanup.
stores/desktop-updates.ts C+IPC update feed settings/metadata; native check/install/failure Client-owned server metadata cache; native update request and failure callback lifetime.

Transport method families and IO authority

Project consumers resolve backendOf(instanceId) from the global instance key and fail closed if it has no owner. The owning SDK cache serves root and attached OpenCode clients; HTTP boundaries unwrap raw workspace IDs and keep physical directory paths. Instance teardown clears the owning SDK cache; an absent owner still permits local view cleanup. The registry starts with the local backend and admits saved profiles through the host's multiBackend flag.

Feature contracts: Files and Git, Missions, Plugins, Integrations, Panel Extensions, Provider Accounts, Settings, Previews and Transcript.

Native folder selection and folder drop open local projects. Device attachments transfer bytes. Keep remote project paths out of local filesystem, editor and workspace-target actions. Settings → Info, releases, desktop updates, host version, SideCars and notification routing keep their host owner.

Tool, Markdown and attachment images follow the passive media contract.

createServerApi methods below retain their BackendHttp. S passes the supplied signal into HTTP/queued work; scope also carries current()/deadline for each transfer; C uses that captured client's request lifetime. S+C accepts request cancellation while retaining the admitted mutation's durable server-side outcome. Feature rows above separately specify admission/publication authority. Native SDK methods pass caller request options through createInstanceFetch, which composes any active attachment signal with Request/init cancellation. A dispatched mutation can commit server-side; durable receipts/resource cleanup retain client/request ownership, while runtime projection and rereads check the captured A.

Adapter family Exact methods IO authority
Transcript/navigation/history fetchPermissionReceipts, fetchHistoryWindow, fetchSessionOutline, fetchOutlinePreviews, querySessionHistory, queryRankedHistory, pruneSessionHistory, fetchSessionGoal, fetchSessionAutomations S; background queue for secondary reads
Session automation mutations pauseSessionAutomation, resumeSessionAutomation, deleteSessionAutomation C; captured backend and session own the mutation; callers fence pre-mutation reads
Background Shell inventory fetchBackgroundShells S; owner backend, raw workspace boundary and public directory; secondary queue and attachment-owned watch/read lane
Transcript mutations pruneSessionMessage C; callers fence publication with their operation
Conversation permission mode read readConversationPermissionMode S; owning backend, conversation view cancels stale reads
Conversation permission mode write setConversationPermissionMode C; captured backend and conversation own the write; the live view reconciles afterward
Session favorites inventory readSessionFavoritesInBackground S; secondary queue, attachment-owned reads
Session favorite writes saveSessionFavorite C; captured client owns the write
Blank-session cleanup cleanupSession S+C; caller signal owns the request, backend owns guarded deletion
Images conversation imagesConversation S+C; owning attachment signal; sent creation retains the admitted client and callers fence publication
Provider usage fetchProviderUsage S; usage coalescer/view generation fences publication
Workspace reads/creation fetchWorkspaces, fetchWorktrees, fetchLocalGitBranches, fetchRepositorySource, createWorkspace S (createWorkspace takes options.signal)
Workspace lifecycle createWorktree, deleteWorktree, moveSessionFamily, cancelWorkspaceCreation, releaseWorkspaceCreation, deleteWorkspace, createTemporaryFolder, abandonTemporaryFolder, keepTemporaryWorkspace, discardTemporaryWorkspace, cloneWorkspaceRepository C; original mutation/creation request owner
File reads listWorkspaceFiles, searchWorkspaceFiles, previewWorkspaceFile S; search retry/queue belongs to supplied signal
Files/config/filesystem readWorkspaceFile, listConfigFiles, readConfigFile, writeConfigFile, listFileSystem, createFileSystemFolder C; callers retain selected file/opening generation; sent writes retain client
Workspace file mutation writeWorkspaceFile S+C; options.signal owns request; original file/revision owns durable outcome and A fences publication/readback
Git reads fetchWorktreeGitStatus, fetchGitHistory, fetchGitCommit, fetchGitCommitDiff, fetchWorktreeGitDiff S; background budget for secondary reads
Git mutations stageWorktreeGitPaths, unstageWorktreeGitPaths, initializeWorkspaceGit, commitWorktreeGitChanges S+C; supplied signal owns IO, captured workspace/request owns submitted mutation
Plugin/depth/usage/settings/account reads getPluginControls, getSubagentDepth, getServiceUsageOwner, getCachedServiceUsage, getServiceUsage, getWebSearchSettings, getImageSettings, getProviderAccounts S
Settings/accounts signal-aware mutations setWebSearchSettings, setImageSettings, setProviderAccountSelection S+C; feature A fences admission/publication/readback
Depth/plugins/source mutations setSubagentDepth, setPluginActivation, addPluginSource, removePluginSource C; feature A fences admission/publication/readback
Persistence fetchConfigOwner S; owner/epoch guards in storage
Persistence writes/state/instance data patchConfigOwner, patchMissionPreferences, fetchStateOwner, patchStateOwner, readInstanceData, writeInstanceData, deleteInstanceData C; storage queues/owner CAS and instance identity
Pending recovery/heartbeat getPendingRequests, sendClientConnectionPong S; pending request/connection generation owns the signal
Server metadata/auth/remote connection fetchServerMeta, fetchAuthStatus, setServerPassword, probeRemoteServer, listSshHosts, browseRemoteServer, connectRemoteServer, forgetRemoteServer, createRemoteProxySession, deleteRemoteProxySession S+C; auth/login/connection attempt owns probes and handoff; browse/connect/forget require the host transport and caller signal, with captured profile policy and guarded durable persistence at the consumer
Remote placeholder authentication connectRemoteServer S+C; local client, captured profile id and supplied view signal; admitted login retains its backend-side profile authority
Remote Control fetchRemoteControlStatus, startRemoteControl, stopRemoteControl, createRemoteControlPairing, setRemoteControlPreviews, fetchRemoteControlDevices, revokeRemoteControlDevice C; local administration client
Local runtime/bootstrap validateBinary, fetchOpenCodeUpdateStatus, getOpenCodeLoginStart, setOpenCodeLoginStart, updateOpenCode, startOpenCode, reloadOpenCodeConfiguration C; setup/client generation
Host log snapshot fetchOpenCodeLogs S; explicit host settings reader owns cancellation and publication
Speech client services fetchSpeechCapabilities, getDesktopVoiceConversationEngine, setDesktopVoiceConversationEngine C for renderer-server capabilities and profile-owned engine preference
Speech capture/playback transcribeAudio, synthesizeSpeechStream S for the caller's capture or playback lifetime; both playback modes consume the binary response.
SideCars/previews fetchSidecars, createSidecar, updateSidecar, deleteSidecar, createPreview, deletePreview, createPreviewCapability, deletePreviewCapability C; resource token/session/client ownership; remote capability deletion retains its original proof and supports pagehide keepalive
Native browser holds holdNativeBrowser, releaseNativeBrowser C; the view's hold ID owns the session hold, renewed while the view shows the session and released when it stops
Conversation permission mode readConversationPermissionMode, setConversationPermissionMode S for reads, C for writes; the conversation and attachment fence publication
Mission display windows fetchMissionPanel, fetchMissionTasks scope: supplied signal/current and capped deadline; per-transfer checks and secondary queue
Mission content fetchMissionContent S
Mission schedule reads fetchMissionSchedules, fetchMissionScheduleCapability, fetchMissionSchedule S; secondary queue
Programmed Missions missionCalendars S for the list read, on the secondary queue; a save, pause, resume or delete runs to its own deadline
One-time Mission creation receipt missionCreationReceipt S; bounded read of the exact original request
Mission client-lived reads/receipts fetchMissionPlaybooks, fetchMissionAdmission C; request ID/revision receipt or caller A publication guard
Mission held-request reads fetchMission S+C; the automatic held-request reread supplies its view/owner signal and deadline; other callers keep the request ID/revision receipt or caller A publication guard
Mission mutations createMission, editMission, deleteMission, controlMission, recoverMission C; request ID/revision/admission transaction owner
Event connection connectEvents Captured backend EventSource; ServerEvents owns generation/close/dispose
Panel-extension reads list, catalog, panel, assets, assetRead, workItems, workItemUrl; API4 images, imageRead, imagesStatus, prefillReferences, conversationStatus, conversation, preferencesGet, preferencesSet Supplied signal in createPanelExtensionsApi; API4 authority includes instance/extension/digest/session
Panel-extension administration inspect, inspectCatalog, install, installCatalog, activate, remove C; owning backend's client and operation captured at admission (panelExtensionsFor), with consent/digest
Native catalogs/metadata rootClient.agent.get/list, rootClient.provider.list, rootClient.model.list/default, client.command.list; client.location.get/project.list/mcp.list SDK active attachment plus caller Request/init signal; catalog/metadata publication uses captured client/location/generation/attachment
Native sessions/messages client.session.list/get/active/create/fork/remove/update/revert/prompt/command/shell/wait/interrupt/switchAgent/switchModel; client.message.list; client.session.message.get/sync; client.session.inbox.list; instructions.entry.put SDK active attachment plus caller Request/init signal; admitted mutation outcomes retain SDK client; page/read/current guards listed in session/transcript rows
Native provider/configuration/Shell client.integration.list/connect/OAuth/command; client.credential.activate/remove/update; client.mcp.connect/disconnect; client.websearch.providers; client.plugin.check/update; client.shell.list/output/remove; client.vcs.status SDK active attachment plus caller Request/init signal; auth attempt/credential/location/client owner and feature A/current predicates
Native authorization attempts authClient.integration.connect.key/external, integration.oauth.connect/status/complete/cancel, integration.command.connect/status/cancel; authClient.integration.list/model.list/provider.list/websearch.providers Auth modal captures SDK client/location/attempt ID and A; each read/cancel uses its request options/signal; accepted credential mutations retain client
Native interruptions client.permission.list, client.session.form.list, getRootClient(instanceId).permission.reply, session.form.reply/cancel Pending discovery request/client/native generation and recovery tokens; sent replies/cancellation retain captured request/client; subsequent pending-state reconciliation uses its own listed authority

Feature Ownership

Feature Owner
Sessions, messages, permission/question APIs OpenCode V2
Shell mode client.session.shell
Conversation instructions client.session.instructions.entry
Background Shell management Native experimental.job.list running shell IDs joined to the selected Location's shell.list through the owned background-shells route; output/removal through the ownership-checking shell.* proxy. Tool-shell authority comes from its originating session. Status panel uses one row per command.
Interactive PTY management Separate OpenCode V2 pty.* API
Workspace lifecycle and directory authorization CodeNomad
Git status/diff/stage/unstage/commit CodeNomad server
Permission evaluation and settlement; session rule block ownership OpenCode; CodeNomad server
Browser SSE multiplexing CodeNomad server
Desktop inspection, CDP feedback and browser previews CodeNomad desktop host/browser controllers and the bundled automation plugin
Remote Control transport, pairing and admission OpenTunnel SDK route plus packages/server/src/remote-control/ (REMOTE_CONTROL.md)

The Status panel refreshes background Shells on Shell events/reconnect and allows removal. The proxy verifies Shell cwd ownership before ID-scoped operations and preserves native output cursor pagination.

Persistence

CodeNomad configuration resolves through packages/server/src/config/location.ts: config.yaml, state.yaml, remote-control-devices.json, and instances/ under ~/.config/codenomad/. config.json is read only as migration input.

The backend logger (packages/server/src/logger.ts) prints to stdout, where info lines are limited to the lifecycle components and desktop hosts read the shutdown handshake. With the stdout destination it also appends every emitted line, timestamped, to logs/server.log in that folder (log-file.ts): written synchronously before stdout, moved to server.previous.log at 5 MiB, and abandoned silently when the file cannot be written. An explicit --log-destination file receives the raw JSON lines instead of both.

Backend shutdown closes SSE and upgraded sockets in Fastify's preClose hook and drains accepted local HTTP handlers before releasing workspace and native-parent authority. Completing responses close their keep-alive connection, including streams whose headers preceded shutdown, through a shutdown-only response-finish idle sweep. Permission recovery reads are cancelled and queued receipt writes settle before workspace cleanup. Plugin leases and workspace cleanup run concurrently, and the success handshake follows resource cleanup. Native-parent responses remain readable through this drain. Mission mutations persist through their native RPC handlers in the shared OpenCode service.

Tauri revokes backend-generation capabilities before requesting shutdown. Its stdout and stderr readers retain their pipes until EOF, recording ordinary output with the launch generation while filtering bootstrap tokens and native-request frames. Revoked generations cannot publish readiness, navigate or dispatch native requests. Confirmed shutdown requires process containment and successful completion of both readers within the same absolute stop deadline (32 seconds on Unix, four seconds on Windows, clipped by the shutdown coordinator's deadline). Reader errors, panics and missing EOF retain ownership for retry and fail shutdown. Server COMPLETE/INCOMPLETE lines remain native diagnostics; process containment and stream completion are tracked separately from the server's functional cleanup status.

Implementation Map

Server entrypoints are packages/server/src/index.ts and server/http-server.ts; shared-service authority lives in workspaces/opencode-service.ts and workspaces/manager.ts, event routing in workspaces/instance-events.ts, and bundled automation provisioning in opencode/automation-plugin.ts. UI native calls use stores/opencode-client.ts, session-api.ts and session-actions.ts; CodeNomad routes use lib/api-client.ts. Current integration conventions are in AGENTS.md and the area documents it indexes.

Agent conventions

  • SideCar proxy cookies use sidecars/proxy-cookies.ts: authenticate locally first, then remove the actual auth cookie, the codenomad_session desktop namespace and paired-device cookie upstream; filter the same names from HTTP and WebSocket response cookies, preserving service cookies. Handshakes go through Node's bounded HTTP parser in server/proxy-websocket.ts, including non-101 responses and coalesced binary data. Same-origin SideCar scripts keep full application access: SideCars are trusted extensions by design.
  • SideCar content and WebSockets use the host's server.sidecarsOverDirectHttps opt-in for authenticated requests from a verified direct HTTPS origin (server/sidecar-direct-https.ts, rule in remote-control/direct-https.ts). Keep browser backend exceptions in isBackendUiRoute() and their authenticated-UI guard; never widen the shared host-only prefixes or the verified HTTPS origin rule (REMOTE_CONTROL.md).