diff --git a/dev-docs/BROWSER_AUTOMATION.md b/dev-docs/BROWSER_AUTOMATION.md index aa0b912090..1eed7cf679 100644 --- a/dev-docs/BROWSER_AUTOMATION.md +++ b/dev-docs/BROWSER_AUTOMATION.md @@ -17,6 +17,10 @@ Browser previews are an ordinary desktop feature and must work in user projects - `browser-execute` validates the browser action and forwards `browser.probe` or `browser.execute` over the fenced native-parent request channel. The bridge is loopback-only, token-authenticated, bounded, and session-location gated. +Owner discovery considers local-shared workspaces before accessing the local +service client. Explicit OpenCode bindings, including loopback profiles and +homonymous session IDs or directories, have the deferred `automation` capability; +host window and preview access requires a local-shared owner. ## Desktop instrumentation @@ -95,5 +99,7 @@ The UI routes an autonomous open request to the one loaded instance containing t ## Agent conventions +- Configured execution projects keep CodeNomad previews and automation closed in E1. The source shell guards preview actions and central guest mounting; autonomous UI routing considers admitted local owners only and retains that captured owner across native claims. Native chat shell execution and server-provided agent catalogues keep their independent chat scope. + - Native session previews behave as tabs in one browser: share the persistent preview profile's cookies/site storage across sessions and projects within a CodeNomad data profile/config pair, but never with the trusted app renderer, remote-window profiles or the other desktop engine. Keep documents, navigation stacks, history cursors and automation attachments session-owned. Electron uses `persist:codenomad-browser-shared-v1`; Windows Tauri uses `browser/shared-v1`. Leave per-session preview profiles found on disk in place and never merge them into the shared profile: they can hold conflicting accounts. Iframe fallbacks keep their sandbox; never grant guests native capabilities. - Browser preview state is keyed by project folder and session ID. Keep explicitly opened guests mounted in stable DOM order across chat/session/Info/project visibility changes; the preview's X also hides it and returns to chat without discarding history. Only their lightweight session shells remain: inactive transcripts and composers still unmount and the transcript memory budget stays independent. Hidden guests must stop being automation targets (Electron unregisters, Tauri hides). Saved project-wide URLs migrate once to the first restoring session. Across renderer restart, restore URL history/cursor only on explicit browser opening; never eagerly visit saved pages or persist native pageState/forms/POST bodies. Reuse owned CDP history IDs for live traversal and load just the selected saved URL when its native entry no longer exists. History is bounded to 32 credential-free HTTP(S) URLs/session within the 4 KB aggregate layout budget; trim history before evicting saved previews. diff --git a/dev-docs/CACHE_REFRESH_CONVENTIONS.md b/dev-docs/CACHE_REFRESH_CONVENTIONS.md index ea86b7022e..bfb4efb6a3 100644 --- a/dev-docs/CACHE_REFRESH_CONVENTIONS.md +++ b/dev-docs/CACHE_REFRESH_CONVENTIONS.md @@ -31,6 +31,92 @@ through every semantic slice, automatic restart and revalidation. Fulfillment en operation; a later user extension/Retry can admit a fresh budget. Validate assembled content before promoting it, and retain the last good display on expiry. +### Execution-server foundation contracts + +`opencode/servers/connections.ts` implements the active-target contract and +`opencode/servers/types.ts` supplies its constants: +four explicit targets plus one reserved local target, atomic admission shared by +target across projects/windows, release on last project close, and retention while +an admitted target is offline. Restore order follows the existing queue; an excess +target stays reconnectable with a quota reason, without eviction. Explicit +Connect/Disconnect intent stays in memory; Disconnect cancels and fences work, +preserves tabs/drafts and never stops OpenCode. Connect without a project retains +its slot until Disconnect/shutdown or its first attach/last-close cycle. + +The administrative probe contract uses a separate single lane, 5 s and 8 MiB, +without active slots, streams or retries. Aggregate event constants are 2,048 +jobs/32 MiB/60 s, reserving 256 jobs/4 MiB for local work and assigning each +explicit source a fixed 448-job/7-MiB share without borrowing; secondary browser +reads remain two globally. Local-only operation retains 2,048 jobs/32 MiB. +Activating explicit shares shrinks new local admissions while already admitted +local work drains inside the aggregate ceiling. A denied admission during this +transition marks a gap, drains grandfathered work and then reconnects. +Generation-qualified capability snapshots are transient; +durable execution bindings use server ID and opaque directory. +Workspace metadata reads derive explicit capabilities from the connection owner's +already validated current connection, with zero acquisition, discovery or provisioning. +Invalidation and pending/failed negotiation expose unverified native E1 capabilities; +successful reacquisition publishes the current connection generation for all its +projects. Issued descriptors keep their historical capability snapshot. Relay event +source generations and connection capability generations have independent owners. + +Explicit live interruption envelopes pair that captured connection generation with +the relay attempt and an occurrence's `liveGeneration` status boundary. Ownership +gap pulses advance the boundary even on one attempt. The relay snapshots it per +recipient before queueing and includes it in prepaid envelope bytes; publication +after ownership waits preserves that capture. Cached/replayed statuses retain the +same identity. The UI validates the correlation before delivery and retains its +backend-transport lifetime. Matching late metadata qualifies only current captured +interruption candidates, without scans, re-admission or network work. Prompt, +inventory, transcript and media owners keep their existing generation and ordering +rules. See [Native interruptions](NATIVE_INTERRUPTION_UX.md). +Capability snapshots retain the backend-transport owner captured before their +HTTP request or at workspace-event ingress, before restore deferral. Each ingress +has a distinct shallow capability snapshot; descriptor selection and display clones +retain that snapshot's owner. Absent capabilities preserve the displayed snapshot. +Publication consumes this provenance. A fresh current-transport snapshot qualifies the +matching current candidate; cached numeric equality across transport lifetimes +stays display-only. Retired occurrence boundaries remain held for that transport, +with new boundaries required for same-ID replacement admission. + +Session placement owners live at the `session-state.ts` publication boundary. +Captures retain exact directory/workspaceID scalars and an opaque token; accepted +placement transitions replace that token synchronously before subscribers run, +including inner-Map mutations, HTTP merges and an A→B→A within one turn. Removal +retires the token and reinsertion starts a fresh owner. Equal placement and unrelated +metadata preserve it. Cold live requests may retain their event Location through +matching first hydration. Session actions, media continuations and Form admissions +consume this shared placement owner independently of native/connection generations. +Occurrence destruction retires its captured tokens while preserved session rows +remain display data for restoration. + +Renderer restoration follows that durable binding for tab reconciliation, +occurrence numbering and preserved-state merges. A runtime tab ID can claim a +saved tab only with a matching server/directory identity. Local-only normalization +is shared in `lib/project-identity.ts`; explicit paths retain exact spelling. +Session catalogs, outline chunks, attachments and session IDs inherit the saved +workspace shell's server identity, keeping existing per-instance reducer keys. +Optional chunk corruption keeps its current bounded degradation behavior. +Accepted tab removal publishes after fallback selection and captures immediately; +ordinary edits retain the debounced capture. Both paths honor restoration, +ownership and native shutdown gates. +Explicit tabs restore through their saved server/directory binding. Unknown targets +stay preserved for repair. Recognized development credential references are +discarded during import; live connection authority stays in memory. + +The backend/config `SettingsService` shares the connection owner across windows. +Target reservation happens synchronously before negotiation; same-target callers +share one pending promise. Initial admission failure releases its reservation; +invalidation of an admitted target retains it for retry and credential rotation. +`retainProject(binding)` returns an idempotent occurrence lease; the last release +aborts requests and releases the slot, including a prior Connect pin. Disconnect +fences immediately; held leases and opportunistic workspace reads require explicit +Connect before resuming. New project/restoration intent and Connect acquire slots; +plain reads never reserve one. The caller's existing restoration queue determines +admission order. Captured transports check their generation at dispatch, after +negotiation/body preparation and on response/stream completion. Late results and +retired invalidation callbacks cannot affect replacement generations. + | Area | Current behaviour | Implementation | | --- | --- | --- | | Session catalog | Per-window, per-workspace persistent display metadata for every known root and descendant. Byte-sized native partitions bound it, independently of session count and the draft string budget. Seed titles, ancestry, locations, selection and expansion before HTTP hydration. Cached rows carry unknown runtime status; the selected chain is revalidated directly, while the owned project inventory refreshes asynchronously. Partial/failed/directory-only initial pages never evict saved workspace families; a complete owned inventory reconciles absent rows with concurrent-update fences. | `stores/session-catalog-persistence.ts`, `session-catalog-hydration.ts`, `client-state-catalog-partitions.ts`, `session-api.ts` | @@ -41,7 +127,8 @@ content before promoting it, and retain the last good display on expiry. | Session goal | Per instance/session snapshot of the shown session's `/goal`. The goal line's demand (Status shown) reads through the secondary budget: one read plus one trailing follow-up. `rpc.opencode.goal.changed` publishes at once and fences replies requested before it (per-session version); an unreadable change reads again. Reconnects (`server.connected`, connected status, stream open) re-read demanded sessions; the line's commands read their outcome. A failed read keeps the last goal; deletion and workspace stop drop it. | `stores/session-goal-store.ts`, `session-goal.ts` | | Integration binding | Demand-only authority for the shown instance/Location/session/integration, shared across Status sections and their picker through the secondary budget. Invalidations immediately publish `unknown` and fence older replies; events coalesce over 300 ms with one trailing follow-up. Reconnect/open reconcile demand, disconnect revokes authority, and read failures publish `unknown`. Last-demand release aborts and drops state. Every admitted attachment mutation invalidates and rereads its captured target in `finally` while demanded. | `stores/integration-bindings-store.ts`, `integrations.ts` | | Stats | Backend-owned `state.ui.serviceUsage`; rules in [SETTINGS.md](SETTINGS.md), restoration below. Reads follow explicit demand, terminal hints (shared five-second activity cooldown), reconnect and visibility; never poll. Hiding/disposal fences in-flight publication. | server `opencode/service-usage-cache.ts`, `service-usage.ts`; UI `settings/usage-settings-section.tsx` | -| Session model selection | Native selection events invalidate the displayed selection and never overwrite it, because SSE echoes can lag successful HTTP writes. Coalesced authoritative reads share the session admission queue with prompts and explicit selections; client/generation and captured-selection checks fence late responses. Catalog merges preserve pending optimistic choices; successful writes publish a fresh model object so pre-confirmation snapshots lose authority. Read failures retain display state until the next event or reconnect refresh. | `stores/session-model-reconciliation.ts`, `stores/session-action-queue.ts`, `stores/session-generation-recovery.ts` | +| Session model selection | Native selection events invalidate the displayed selection and never overwrite it, because SSE echoes can lag successful HTTP writes. Coalesced authoritative reads share the session admission queue with prompts and explicit selections; captured instance request authority fences dispatch and publication, including explicit connection rotation. Returned session identity and explicit Location are validated; captured-selection checks retain newer choices. Catalog merges preserve pending optimistic choices; successful writes publish a fresh model object so pre-confirmation snapshots lose authority. Read failures retain display state until the next event or reconnect refresh. | `stores/session-model-reconciliation.ts`, `stores/session-action-queue.ts`, `stores/session-generation-recovery.ts` | +| Instance preferences/history | Per-key write owners and publication epochs fence HTTP cache publication before subscriptions run. Newer same-context writes supersede older ACKs; captured action authority also gates preference writes after rotation. Every accepted server snapshot advances the epoch, including equal data. A current ACK crossed by an event uses up to three 10-second authoritative reads to resolve ordering; retired writes publish nothing and never replay. The cache/subscription is the single accepted mutation publisher. Subscription and load cleanup remove only their captured owners; explicit retirement invalidates cache/read/write owners before reuse. Incoming valid snapshots retain their own authority, independent of the action that installed a subscription. | `lib/storage.ts`, `stores/instance-config.tsx` | | OpenCode setup | Shared in-flight status read plus coalesced trailing refresh for focus/visibility/reconnect demand. Executable changes and explicit actions fence old responses. Failed reads retain version/path diagnostics but revoke the connected claim and stale reload/restart controls; Continue checks again before retrying the pending workspace. Activation requires a successful pre-action status read. | UI `stores/opencode-setup.ts`, `components/settings/opencode-setup-panel.tsx` | | Filesystem invalidations | Host directory observations and native filesystem events coalesce before cache publication: 100 ms quiet-case delay, then at most once per five seconds in continuous activity; timers run only during activity. Explicit mutations/recovery invalidate immediately. Workspace versions target the browsing root and listed directory; only changed visible directories reread. Hidden/collapsed caches stay stale until demand. Bounded metadata falls back conservatively to full invalidation. | `filesystem-events.ts`, `useWorkspaceTree.ts`, server `workspaces/file-watches.ts` | | Git changes | Shared filesystem cache invalidations debounce locally for 100 ms; one passive refresh plus a pending follow-up; hidden project/panel marked stale. Queued reads cancel on deactivation/disposal and request versions fence late status/diff results. Reads share the secondary HTTP budget. Server shares only in-flight status requests and runs status/diff process creation in the Git worker. | `useGitChanges.ts`, `filesystem-events.ts`, server `workspaces/git-status.ts` | @@ -54,7 +141,10 @@ content before promoting it, and retain the last good display on expiry. | Mission panel inventory | Live picker/cleanup discovery uses explicit 50-row logical windows through `panelPage`. Content digests verify that window; a separate order digest covers the collection's row values and fences further selections. Only selected/reader-wanted missions load bounded headers and task windows; root collection/extension descriptors permit exact field reads. Every window retains its own revision and failed selector. A failed middle window stays failed through unrelated successes; changed cursors park for explicit restart/Retry. Passive refresh reads first windows and wanted headers, preserving expanded displays without replaying every read after unrelated revisions. Initial discovery point-reads the durable finish counter before hints; completion seeding happens once, independently of partial summary maxima. Exact cleanup reconciliation keeps its existing single-mission path. Every transfer retains the shared secondary slot through bounded stream cleanup, with one 30-second logical deadline and source-specific preallocation limits. Hints serialization/order work remains in the append lane and linear in the whole chosen collection per transfer. | UI `stores/mission-panel-inventory.ts`, `lib/mission-task-page-read.ts`; server `missions/mission-panel-page.ts`, `mission-panel-header.ts`, `MissionControl.panelPage` | | Opt-in Mission live windows | `panelPage` activity selects at most 160 actors of one mission; marks select at most 16 hint contexts of 10 actors. Native observation reuses existing budgets and root/connection/deletion fences after the append exclusion. Every continuation re-observes and refuses changed content; zero automatic restarts and no retained observation cache. Partial/unknown family and request coverage stay explicit, including off-page actors. Consumers park failed windows, retain last-good display and restart changed rows from their first piece explicitly. | server `missions/mission-activity-context.ts`, `mission-panel-observation.ts`, `activity.ts` | | Mission task transport | One requested window or named read through `panelPage`, 64 KiB per response and 16 KiB per selector. Each secondary slot covers headers plus bounded body consumption/cancellation; one 30-second deadline starts before the store queue and covers final hash/validation/publication. Window text admits at most 8 Mi UTF-16 units, 24 MiB UTF-8, 64 MiB cumulative wire bodies and bounded JSON structure/nested compact shapes. Digest/length/header, semantic selector/report/counter checks and UTF-16LE SHA-256 precede publication; WebCrypto and the pinned browser-safe fallback cover secure and HTTP-only origins. Partial text is operation-local; failures park with Retry, while supersession stays distinct from empty success. Last-owner release advances a monotonic mission lifetime; concurrent owners preserve it. Live readers own reconnect refresh demand independently of the panel. | UI `lib/mission-task-page-read.ts`, `mission-task-page-schema.ts`, `mission-task-window-budget.ts`, `mission-task-read-lifetime.ts`, `stores/mission-store.ts` | -| Render cache | Explicit versioned values scoped to instance/session, invalidated by version only. | UI `lib/global-cache.ts` | +| Internal explicit transcript pages | One native page per demand, up to 200 messages. Originating order and captured client/binding/native/connection-generation authority stay in the existing window owner in memory. Selected-session navigation is foreground; other page reads share the two secondary slots. Same-intent consumers share current reads; a replacement authority starts fresh. Pages merge native live changes without polling; historical membership stays bounded. Failed/empty probes preserve the resident passage and saved anchor. Cold unsupported anchors keep their position pending explicit latest-page recovery. | UI `stores/session-api.ts`, `message-v2/message-window.ts`; [SESSION_HISTORY_NAVIGATION.md](SESSION_HISTORY_NAVIGATION.md) | +| Render cache | Versioned display values scoped to instance/session. Explicit Markdown stores sanitized HTML with its producing binding and reauthorizes before publication; mismatched/unqualified snapshots use the unknown-source policy. The instance owner's memory-only `renderBinding` survives component remounts and cache eviction. Native-reference Markdown reparses on demand. Cached tool diff HTML shares the publication filter. Local-image candidates for explicit content are reauthorized against current held native references; legacy scans retain their per-object/revision cache. | UI `lib/global-cache.ts`, `lib/markdown-html-policy.ts`, `lib/markdown-local-images.ts` | +| Deferred media HTTP | One captured connection per user-demanded media read. Every upstream envelope is buffered within 16 MiB of decompressed bytes before SDK parsing, with cancellation on overflow, 30-second deadline, socket close or retired authority. Session/Location/undo/digest are revalidated before immutable-byte publication. | Server `opencode/session-media-fetch.ts`, `server/routes/session-media.ts` | +| Known Form verification | One explicit source-editor gesture, one native Form GET; Session GET before/after for session Forms, exact encoded directory for globals. Two existing global secondary slots, ten seconds including queue/acquisition/profile, four MiB per decoded success/error response before SDK parsing. Captured source, immutable binding, client/native/connection generation, backend transport, request revision and attempt fence publication. Terminal/indeterminate results retain drafts; changed editor fields stay indeterminate. Coverage stays unknown/live-only and retry requires another gesture. | UI `stores/form-verification.ts`; server `explicit-form-verification.ts`, `opencode/bounded-response-fetch.ts` | | Background HTTP reads | Worktree display, Git status/diffs, project/location/status maps, composer catalogues, Shell lists and pending-request scans share two browser request slots across instances. Queued scans observe cancellation; per-request timeouts start at dispatch. Session/message reads and mutations stay independent so catalogue fan-out cannot occupy all HTTP/1.1 connections. | UI `lib/background-read-queue.ts`, `lib/sdk-manager.ts`, `stores/instances.ts`, `stores/worktrees.ts` | | Virtualized lists | Session list, transcript and timeline use `virtua/solid`; virtualization bounds rendered rows only. | UI `session-list.tsx`, `virtual-follow-list.tsx`, `message-timeline.tsx` | @@ -111,23 +201,48 @@ Beyond the relay rule in [OPENCODE_COMPATIBILITY.md](OPENCODE_COMPATIBILITY.md) order includes move/delete, unrelated sessions have no global order, other scoped events keep FIFO per complete native location and global notifications have their own lane. `server.connected` is relayed with a `daemon` field: an -opaque token held only for the current source by the relay, issued randomly -per source, stable across verified same-source reconnects, rotated when the -source is replaced (the superseded credential-bearing key is dropped with it) -and released when the relay disposes; it is absent from an unattributed -stream. The UI gates reconnect transcript continuity on a matching token and -keeps a hard reset otherwise. Ownership -promises/2 s -results are shared per recipient and full location. Ingestion-time worktree +opaque token held only for the current source by the relay, issued randomly. +Local tokens remain stable across verified same-source reconnects and rotate +with the source (the superseded credential-bearing key is dropped with it). +Explicit tokens are attempt-local. Tokens release on disposal and are absent +from unattributed streams. The UI gates reconnect transcript continuity on a +matching token and keeps a hard reset otherwise. Ownership promises/2 s +results are shared per source, recipient and full location. Ownership/session +caches retain at most 1,024 entries each; PTY/Shell/global-Form placement caches +retain at most 1,024 entries each with a 60-second idle TTL. Ingestion-time worktree invalidation and local inventory changes fence pending ownership checks; stopped/reopened workspaces and disconnected stream generations cannot publish late work. Budgets: 2,048 retained jobs, 32 MiB conservatively counted serialized -payload, 60 s per routing job including queue wait; a breach fails that -subscriber, clears its queue and emits the normal error/reconnect statuses. Never +payload including each delivery envelope. Resolution and all recipient delivery +capacity are charged together at ingestion; unused reservations release on +resolution and prepaid deliveries keep their original deadline. The deadline is +60 s from ingestion through resolution and delivery; a breach fails that source, +clears its queue and emits attributed error/reconnect statuses with a structured +gap reason. FIFO drains and ingestion yield every 32 events/jobs. Never silently drop a delta or restart the shared daemon. Rate-limited slow-routing logs separate event age, location resolution, queue wait and ownership time (type/recipient metadata only). +The connection owner's synchronous admitted-slot snapshot/observer owns relay +membership. Each admitted explicit target has one runner, including a Connect pin +without recipients. Initial failures, reservations, probes and excess targets have +no runner. Offline retry retains the slot with exponential jittered backoff capped +at 30 seconds; rotation revokes the current iterator and queued work. Last release, +Disconnect and disposal cancel the runner without stopping OpenCode. Credential +changes interrupt an offline retry timer immediately. Per-next abort listeners +release on settlement. Late project +attachment receives its current status and native connected marker. Source and +relay-attempt generation are captured before enqueueing, separately from workspace +epochs, connection assertions and the daemon token. Locationless session reads use +the captured source client. Unknown deletions/placements trigger a bounded gap pulse +only for that source's occurrences. Native worktree events invalidate local +inventories only when sourced from the local service. + +The event bus retains only current occurrence statuses for new subscribers. +Workspace stop/error evicts that occurrence's statuses synchronously, including +when last-lease release has already disposed its relay. Offline admitted projects +retain their current status; relay source/occurrence fences govern late work. + ### UI event stream liveness `lib/server-events.ts` restarts the shared UI event stream once a connected @@ -141,6 +256,60 @@ intervals. ## Initial session hydration +Instance-config readers share a cold load while its initiating caller remains current. +A surviving reader whose shared owner retires joins a current replacement (at most +three joined loads) or starts one read under its own authority before returning. +Failed current replacement loads reject before dependent model/default selection and +leave the snapshot unloaded for explicit recovery. Ordinary first-load failures keep +their existing best-effort default. Load cleanup removes only its captured owner. +Preference saves retain their best-effort publication contract; history callers keep +their ordinary predicate, independently of OpenCode session authority. + +Native explicit transcript page coalescence includes the existing load signal/epoch +and current source window alongside instance authority. Superseded reads release +new same-intent demand before their promise settles. The pre-read row snapshot is +merged again after a dependent model read; empty native latest replies with +residents retain their passage and reading anchor before any live-row merge. +Receipt enrichment admission precedes component mounting, cache acquisition and +queued receipt dispatch for explicit bindings. + +Explicit occurrences use the internal exact-Location session policy in +`stores/session-inventory-scope.ts`. Their first bounded page publishes independently +of project/worktree discovery and runtime activity. Continuations run on demand +through the shared two-slot secondary queue, with cursor-only native requests. +Passive first-page refreshes share their in-flight read and coalesce demand into +one trailing refresh; strict/cancelable operations retain their own request owner. +Selected first pages and selected restored ancestry keep foreground promotion. +Client, binding, native-data generation and connection-capability generation fence +dispatch, publication, targeted lookup and absence reconciliation. Saved cursors +from a superseded traversal remain unusable until a fresh first-page read. +The traversal owner holds its captured-row references and fetched IDs until the +terminal page qualifies exact absence reconciliation; concurrent row changes win. +Snapshots survive partial pages and read failures. Native title search is one +bounded page with an incomplete-result notice. Ordinary session listing has its +own authority, separate from pending-request recovery. + +The session traversal also owns failed-continuation provenance. Retry keeps that +cursor and snapshot while the traversal remains current; a fresh first-page read +clears the continuation failure. Native event metadata lookups reuse the inventory's +client/binding/native/connection-generation fence before dispatch and publication. +Pending status lookups coalesce only while that captured authority is current. +Their status/retry continuations also check the latest native lifecycle order, +including newer events on the same connection. Metadata merges compare the row +captured before the read with the live row, preserving runtime authority supplied +by concurrent hydration and subsequent native events. +Inventory, ancestry, search and targeted metadata reads share request ordering. +Weak row provenance retains their HTTP snapshot through pending/status projections +and native/local edits: a current lookup can update fields supplied by an earlier +read while preserving fields changed since that snapshot. Runtime authority keeps +its separate pre-read baseline; runtime-only projections retain metadata provenance. +An external move updates the held native Location before exact-scope projection, +preserving its native parent and draft. Debounced move refreshes recheck their +captured occurrence before dispatch and after dependent reads; candidate projects +share the source server. Explicit candidates require the exact opaque directory, +and their refresh reads only the bounded session page. Local worktree discovery +keeps its existing scope. + App-tab records retain identity across metadata refreshes, reordering and restoration of sibling projects. Their payload getters stay reactive; Solid's identity-keyed rendering must not remount existing shells or restart their Git readers on each update. diff --git a/dev-docs/COMPOSER.md b/dev-docs/COMPOSER.md index 74317261e5..7c03cfa378 100644 --- a/dev-docs/COMPOSER.md +++ b/dev-docs/COMPOSER.md @@ -4,7 +4,22 @@ The prompt composer: context selectors, height, focus after send, alternate deli ## Agent conventions -- The composer reserves `/btw` for native `session.generate`, outside ordinary prompt/command submission. Its ephemeral question/answer window uses `DismissibleWindow` and `styles/components/session-aside.css`; cancellation and inactive/session transitions fence late results without interrupting the main session. +- The worktree selector admits its owning project before constructing its inventory, dialogs or handlers. Native chat shell commands and server-provided agents retain their separate chat authority. + +- The composer shows no upload destination text. Device bytes travel with the message to the source composer's execution server; selection only reads them on the device. The existing device-read epoch includes server/directory binding and source disappearance, fencing pending pickers/reads on same-directory retargets while retaining settled drafts and attachments. + +- Explicit-server chat uses the captured target's native agent/model/command/skill catalogues. Catalogue continuations and dependent built-in reads retain instance/binding/native/connection authority; a stale admission never acquires a replacement target. The mention menu explains unavailable project file references and guards discovery, synthetic roots, selection handlers and prompt admission independently. Device byte uploads retain their separate attachment path. Queued edits and failed sends preserve draft protections and never replay a mutation automatically. + +- A send's failure restores its initiating draft only while its source occurrence and durable binding remain held and its draft has not changed. `usePromptState` advances the local text revision synchronously, including edit/clear cycles and hydration; attachment state has its own captured owner. Changing the displayed target preserves that target's newer typing; recovery writes the original source's draft/attachments without moving focus. Source lifecycle retirement fences recovery into a reused occurrence. Same-target catalogue read demand can recapture after a first native connection invalidates its initial read; queued mutations retain their first capture. + +- Queue editing captures the real composer draft, attachment owner and known native payload before cancellation. Acknowledged cancellation restores the known payload only into that unchanged active draft, preserving intervening user focus. A changed draft, displayed target or failed acknowledgement keeps the known payload in the open source view through `usePromptRecovery`; the person checks the queue, clears the current draft/attachments and explicitly restores it for editing. Recovery copy keeps cancellation outcome conditional. Restoration uses the ordinary draft/attachment stores and never sends. These source-local recovery entries retire with the view or occurrence. Undo prefill follows the same draft/focus checks. A first-prompt creation captures its draft before awaiting and activates the created conversation only while that draft remains unchanged; registration captures its new composer's draft before a pending first-send failure can restore it. + +- Retired actions and uncertain HTTP outcomes use one deduplicated, polite, non-modal source-conversation notice in `PromptRecoveryNotice`; known ordinary action errors retain their existing error dialog. Late callbacks preserve user focus. The notice distinguishes refused remaining steps from an earlier request that may already have been accepted, with an explicit conversation check before retry. Native multi-request actions keep their per-request fences. + +- The CodeNomad explicit workspace proxy reports its uncertain 502 outcome with `explicit_request_uncertain`. The SDK adapter recognizes that structured envelope only on workspace-native proxy URLs and retains its code through the client's cause chain. Known environment/account admission failures retain their ordinary error identity through that same chain; transport wrapping keeps their dialog treatment. + +- The composer reserves `/btw` for native `session.generate`, outside ordinary prompt/command submission. Its ephemeral question/answer window uses `DismissibleWindow` and `styles/components/session-aside.css`; cancellation and inactive/session transitions fence late results without interrupting the main session. Response publication requires captured instance authority; settling `pending` requires ownership of that question's controller. A retired connection's settled owner becomes explicitly retryable with contextual feedback, while a cancelled/closed owner leaves a newer question untouched. +- The aside's Markdown receives its instance owner. Explicit or unowned aside content accepts validated, bounded embedded images only: its ephemeral answer holds no qualified native-message reference. Explicit attachment display/download uses the transcript media policy; device selection budgets and sending bytes retain their existing independent controls. - Keep agent, model and thinking controls in the composer footer via `PromptContextControls`, on one row with the actions on desktop and touch (truncate selector labels, never wrap the footer); adapt it with the named `prompt-composer` container rather than viewport-only breakpoints. Dense conversation toolbar/footer controls and the session list header actions use `--touch-target-size-compact` (the latter must fit five actions plus the panel-toggle reserve in the 220 px minimum sidebar); timeline markers use the compact control height rather than the global touch target. Toolbar touch spacing lives in `styles/panels/session-toolbar-touch.css`. - Composer height limits depend only on the visible conversation height: minimum 8% (44 px floor), maximum 60% (never below that minimum). `prompt-input/usePromptViewport.ts` observes the conversation and its intersection with `visualViewport`, including keyboard resize/pan. Store manually chosen heights as proportions so the field itself follows viewport changes; saved pixel heights convert to a proportion on the first valid measurement. Viewport-driven changes never overwrite the saved proportion; pointer and keyboard resize controls share the same limits and long drafts remain scrollable. - On desktop a send moves focus to the conversation stream for keyboard reading (arrows, paging, Space); a printable character typed there resumes the composer with that character (`prompt-input/type-to-focus.ts`), while fields, controls, IME composition and plain-key shortcuts keep their keys. Touch-only devices keep the keyboard closed. Do not add delayed refocus timers or a preference for this. diff --git a/dev-docs/DESKTOP_DATA_PROFILES.md b/dev-docs/DESKTOP_DATA_PROFILES.md index 8d3f09fdef..1b45a9ea64 100644 --- a/dev-docs/DESKTOP_DATA_PROFILES.md +++ b/dev-docs/DESKTOP_DATA_PROFILES.md @@ -14,6 +14,8 @@ OpenCode sessions and messages live in the shared OpenCode daemon and are the sa ## Selecting a profile +Workspace-open authority belongs to the project execution binding. Both desktop hosts fetch the active occurrence from their authenticated local CodeNomad backend and reject explicit OpenCode bindings before resolving host paths or launching applications. This applies equally to explicit loopback profiles and paths matching host folders; unbound legacy descriptors retain local behavior. Renderer availability and native guards share the `explicit_capability_unavailable` / `files` / `localOnly` refusal contract. + Precedence, evaluated by both Electron (`electron/main/data-profile.ts`) and Tauri (`src-tauri/src/data_profile.rs`) before any profile path, singleton or WebView storage is fixed: 1. `CODENOMAD_PROFILE=` — explicit profile. @@ -29,6 +31,15 @@ After trimming ASCII whitespace and lowercasing ASCII letters: 1–64 characters ### Storage +Both hosts retain the V3 window envelope and V2 content-addressed partition graph. +Each workspace shell can carry `serverId`, scoped to that window's existing tab +occurrence. Imported unknown server IDs remain attached to their saved data. +The shared renderer codec validates these IDs and retains exact remote directories; +native hosts validate the enclosing document and partition hashes. Runtime source +generations, connection tokens and credential availability stay in memory. The +server registry persists labels/origins separately; restoration retains only the +server ID and directory. Backend restart requires fresh credential entry. + The default profile with the default config uses the unscoped locations (`~/.codenomad/client-state/v2`, Electron's `userData`, Tauri's stable identifier and WebView directory). Every other profile/config pair uses ` = -sha256(key + "\0" + configIdentity)[0..16]`, i.e. `%APPDATA%/CodeNomad/scopes/` (Electron `userData` and both hosts' client state) and `…-v2/scopes/` (Tauri WebView), plus a scoped Tauri identifier. The default profile's key is `stable`, so existing folders such as `dev-` and `dev-v2-` are reached with `CODENOMAD_PROFILE=dev` / `dev-v2`. On Windows, Tauri runs each profile under its identifier as AppUserModelID, and its system notifications carry that ID. Windows shows a desktop app's notifications only under an ID it knows, and the installer's Start menu shortcut carries the stable one, so every launch registers the running ID under `HKCU\Software\Classes\AppUserModelId\` (`DisplayName` CodeNomad, `IconUri` the bundled web app icon `resources\server\public\pwa-192x192.png`; `windows_notification_identity.rs`). Electron always uses the stable ID. @@ -39,6 +50,52 @@ Non-ASCII config paths on Windows: each host folds the config identity's case di Every backend launch (the default profile included, as key `stable`) receives the resolved scope that the backend uses as its Mission profile scope: `CODENOMAD_UPDATE_CHANNEL=`, `CODENOMAD_PROFILE_CONFIG_IDENTITY=` and the selected `CLI_CONFIG`. Tauri applies these only to the backend `Command`, never through a process-wide `set_var`. They are backend-only: the backend strips them and `CODENOMAD_PROFILE` from the environment of the shared OpenCode daemon it starts (`workspaces/host-opencode-service.ts`), so agent shells never pin a desktop launched from them to this profile. +### Private attachment inventory + +The native-parent methods `projects.attachments.read` and +`projects.attachments.current` expose bounded metadata within the running +backend/profile/config scope. Electron serializes retained projection on its +client-state queue; Tauri takes its publication lock before the state mutex. +V1/V2/V3 envelopes use the existing migration owners. Partitioned snapshots load +only the verified session manifest; workspace documents, conversations and blobs +remain with restoration. Each host issues opaque memory-only owner/tab handles +and receipts. Publication admission, rollback uncertainty, window replacement, +observed document-token resets, private-transport backend replacement and ownership +loss retire captured observations. A fresh read also +retires the previous native receipt. Conservative invalidation includes unrelated +client-state writes. Corruption, missing manifests, unsupported versions and +secondary ownership retain unknown coverage. Live registrations contribute window +presence with unknown tab membership, including restore-disabled windows. + +Manifest file reads retain at most 1 MiB and inspect at most one additional byte, +through a fixed 64-KiB scratch buffer. Accepted raw bytes keep SHA-256 verification +before decoding. Tauri publication admission holds a distinct memory-only owner +through waiting, root commit and rollback; receipts require every admitted writer +to have left that phase. Electron retains its serialized publication queue. + +The two private attachment methods use opaque `attachments-` request IDs, +echoed unchanged by both native serializers. Their canonical v1 responses begin +with `v,id`; stdin classifies at most 256 header bytes before retaining the body. +The serialized result allowance is 8 MiB plus the exact prefix/success-envelope +overhead for that ID (and optional CR/LF framing). Overflow drains to LF and releases +the matching pending owner; direct responses apply the same pre-parse limit. +Owned 64-KiB body blocks bound per-frame storage metadata; concatenation and UTF-8 +decoding each use an additional copy bounded by the frame allowance. String adapters +encode in bounded pieces and preserve split surrogate pairs. +Ordinary native methods retain their own response contracts. Each read/current +request has its own five-second monotonic settlement deadline alongside the +wall-clock wire deadline consumed by the host. Caller expiry fences publication; +host I/O retains its existing execution lifetime. + +Browser participation is a separate backend-memory owner. A dedicated named event +delivers a random capability only to its authenticated SSE response; publication +requires that capability, the same current cookie/device principal and trusted +Origin/Fetch Metadata. Publication rejects raw `?` and `;` query delimiters, including +empty queries, before body parsing or capability admission. Every declaration stays scoped to this running backend's +profile/config identity. Native application, Preferences and remote desktop windows +keep their native owners. Browser declarations preserve unknown global coverage; +native window linkage and pre-mutation fencing retain their qualification gates. + ## Automatic choice On a packaged launch without `CODENOMAD_PROFILE`/alias and without a usable remembered choice, the host decides alone, without asking: @@ -94,6 +151,34 @@ Known limits: the Tauri singleton itself is not file-based; a Tauri instance is ## Validation +### Explicit OpenCode credentials + +Explicit OpenCode credentials are scoped by resolved data profile/config identity, +server ID and normalized origin. Pairing tokens and manual passwords persist in +the private backend `opencode-server-pairings.json` (0600), beside `config.yaml`. +Saved configuration retains the server's name and URL. Secrets must never enter +public config, events, logs or browser storage. Restart reuses the private secret; +expiry, HTTP 401, origin replacement and server removal erase it. + +`opencode/servers/credentials.ts` owns a private backend-owner Map keyed by +profile/config scope, server ID and origin. Its asynchronous mutations perform +their changes synchronously. Reading invalidates an entry when the origin differs +or the server is missing; `clear(serverId)` also works after metadata removal. +Errors use fixed codes: `unknown_server`, `invalid_credentials`, +`metadata_unavailable` and `closed`. Static config summaries conservatively return +`hasCredentials: false`, `needsCredentials: true`; the owning service's status +provides live booleans through `SettingsService.getOpenCodeServerSummaries()`. + +`SettingsService` retains one registry, credential owner and connection owner for +all backend windows. Registry origin changes/removal clear credentials before +publication and subsequent ID reuse. Rotation, forgetting, Disconnect and shutdown +abort owned HTTP/streams and fence captured clients, transports and late results. +`WorkspaceManager.shutdown()` disposes the owners and private memory before cleanup. + +Electron and Tauri use the same backend contract. Their packaged restart checks +must verify retained name/URL, reconnection with the saved token or password, +and removal/401 revocation. + - Electron: `data-profile.test.ts`, `profile-transition.test.ts` (including unwritable choices/lock and the leftover-folder sweep), `startup.test.ts`, `data-profile-cleanup.test.ts`, `data-profile-cleanup-ipc.test.ts`, `preload/index.test.ts`. - Tauri: `data_profile`, `profile_transition`, `client_state::restorable`, `identity`, `data_profile_cleanup` tests. - UI: `tests/browser/data-profiles.test.ts` (the profile manager in Preferences and inline, pinned launches, plain browser). diff --git a/dev-docs/FILES_PANEL.md b/dev-docs/FILES_PANEL.md index 975004253a..f48adddf92 100644 --- a/dev-docs/FILES_PANEL.md +++ b/dev-docs/FILES_PANEL.md @@ -89,6 +89,11 @@ preview replaces the file reader; opening a file returns the browser to chat mod Cancelling or hiding a view fences pending reads. Workspace/local-diff readers refresh on filesystem invalidation, while commit contents remain immutable. +Project Markdown callers pass their owning `instanceId` to the shared `Markdown` +surface, including resident content and replies from an already-started local read. +An actual transcript owner additionally supplies its native `sessionId`; file +preview selections keep their independent reader scope. + ### Hide whitespace-only changes Stored with the UI settings; the rules are in Agent conventions. Beyond them: @@ -137,6 +142,15 @@ insertion into the composer remain available. ## Backend boundaries +The renderer admits Files before constructing tree, history, changes or initialization hooks, and admits central previews before either file reader exists. Worktree inventory and mutations share the source policy; retained local handlers and queued responses keep their originating authority through dependent reads. Host filesystem, Git and desktop bridge admission uses the owner-held project policy. Local reader lifetimes survive ordinary metadata refreshes and mode/tab changes; source retirement fences their queued work and late publication. + +Workspace Files and Git operations require their workspace's `files` or `git` +capability before host filesystem or Git access. Worktree inventory, creation, moves and removal +require `worktrees` before native discovery, path identity reads or local Git; +direct manager callers share these gates. Refusals carry +`explicit_capability_unavailable`, the capability and its structured reason. +Git initialization checks this policy before resolving the submitted path. + Listings register their watch before reading the directory, because native filesystem events miss some browsed folders; this path needs no initialized OpenCode client. Each `workspace.filesChanged` batch carries the workspace ID and @@ -165,6 +179,35 @@ opaque device/inode identity distinct from mtime. timeout and output bound. Renames use their original path; gitlinks show their object IDs rather than reading another repository. Binary diffs use a fallback. +### Projects on an explicit OpenCode server + +A validated explicit connection makes `files` and `git` available for native +reads only; `opencode/servers/remote-workspace.ts` serves them through the +project's single server connection, never the host disk, Git or file watches. + +- Files list, search, preview and content (`/files`, `/files/search`, + `/files/preview`, `GET /files/content`) accept only paths relative to the + opened folder (no absolute, drive or `..` segment) and only that folder as + `directory`. Native entries outside it (absolute, `..`, non-direct children) + are dropped: `fs.list` can name entries reached through links, so the filter is + an exactness rule, not a security boundary. Reads stream with a 5 MiB cap + (`too_large`, 413) and JSON answers with a 32 MiB cap; every answer must name + the exact folder. +- Git status and diff (`/worktrees/root/git-status`, `git-diff` with scope + `unstaged`) read `GET /api/vcs`, `/api/location` and `/api/vcs/diff?mode=working`. + Native paths are relative to the Git worktree root (`project.directory`), so + they are brought back to the opened folder and rows outside it are dropped. + No provider is `not_repository`; an unknown root or an untraversed ancestor + folder (`more`) is `ambiguous` (409): an incomplete state is never an empty + list. A diff requests whole-file context and rebuilds both sides from one + hunk; an empty, partial or mode-only patch is `ambiguous`, never unchanged. +- Writes, history, staging, commit, initialization, other worktrees and host + Git (including forge work items) return `explicit_capability_unavailable` + before host IO. The UI shows one Changes section, no Commits, Save or + Initialize Git (`hostGit`, `fileWrite`), the branch from native `vcs.get`, and + maps the fixed codes to `filesPanel.contentUnavailable` or the not-repository + text (`lib/remote-read-error.ts`). + ## Validation - `workspaces/file-watches.test.ts`: real host file operations, replacement, diff --git a/dev-docs/MISSIONS.md b/dev-docs/MISSIONS.md index eab9c4e3e7..8946b15e86 100644 --- a/dev-docs/MISSIONS.md +++ b/dev-docs/MISSIONS.md @@ -19,6 +19,12 @@ the execution journal retains its task, report and lifecycle contracts. ## Ownership +Missions is available for workspaces bound to the local shared service. Explicit +OpenCode bindings return `explicit_capability_unavailable` for `missions` before +connection acquisition, host inventory, Git, environment or plugin RPC work. +Authenticated bridge discovery considers local owners only, including for +ongoing Missions, managed roots, cleanup and human-answer verification. + | Concern | Owner | | --- | --- | | Root sessions, prompts, durable inbox, execution, Forms, permissions | OpenCode V2 | diff --git a/dev-docs/MISSIONS_RECURRING.md b/dev-docs/MISSIONS_RECURRING.md index 11a58f14a5..6261b8f3ff 100644 --- a/dev-docs/MISSIONS_RECURRING.md +++ b/dev-docs/MISSIONS_RECURRING.md @@ -348,6 +348,11 @@ settlement, original identity/correlation and completed-only source consumption apply to both paths; `lastDaily` and daily watched-cursor fields belong to the daily format. The Wayfinder UI-answer mark is shared by both paths. +Recurring schedules use the local shared service binding. Explicit OpenCode +workspaces fail the `missions` capability gate before preparation, snapshots, +current-passage reads, exact control status or authenticated proof callbacks +acquire a connection or read host state. + Creation stores a paused schedule, never starts work or arms a timer, and is never resent; Play requests carry the then-current revision so CAS refuses a duplicate. New titles follow the 1–60 Mission title rule; stored schedules keep their diff --git a/dev-docs/NATIVE_INTERRUPTION_UX.md b/dev-docs/NATIVE_INTERRUPTION_UX.md index 0842a543b9..128bd13ba5 100644 --- a/dev-docs/NATIVE_INTERRUPTION_UX.md +++ b/dev-docs/NATIVE_INTERRUPTION_UX.md @@ -54,6 +54,109 @@ when known. Receipts are read-only transcript annotations. A source message anchors the receipt; requests without one remain available as session receipts. Reads are bounded and ownership-checked. +Explicit-server E1 message and session receipt readers stay unmounted; direct cache acquisition +and queued dispatch also require local history enrichment. The server's receipt +gate remains closed. Native request coverage stays live-only, with unknown +coverage after a disconnection. Loaded native question/tool text remains readable. + +Manual replies retain the exact request, metadata, source client, execution binding, +native/connection generation and native Location before dispatch. Permission callers +must supply the queued session owner. Global Forms retain their encoded native +directory, including Unicode and percent signs. Replacement, close, disconnect and +backend restoration retire admissions while keeping current editors and drafts. +Current live events admit only their own request. Late acknowledgements leave newer +requests and settlement markers untouched; already observed settlement needs no +second publication. Ambiguous explicit replies retire their admission and preserve +the editor. Local replies retain their authorized settlement reconciliation. + +Explicit live-only coverage is unknown even when the local queue is empty. A +disconnect or backend restoration retires known requests' reply authority without +any project notification. A live request grants only that request's +reply authority; project coverage remains unknown. The dock's native disclosure +provides the server label plus stable ID (or ID alone), direction-isolated directory +and live-only reason. Equal display labels remain distinguishable in notices and details. +Stale fields remain editable and their guarded reply/cancel controls share an +accessible explanation. Opening views and explicit mutation errors schedule zero +pending discovery reads. A held explicit-server Form offers its own explicit status +check in the source editor. Permissions retain live-event-only admission. + +`stores/form-verification.ts` captures the held Form object and its registered source +before entering the shared two-slot secondary budget. One gesture dispatches one +native Form GET; session placement is checked before and after it at the backend. +Global Forms use one GET with the captured once-encoded directory header. The whole +operation has a ten-second deadline, including queue/acquisition/profile waits, and +each native success/error response has a four-MiB decompressed ceiling before SDK +parsing. Native status, JSON envelope, field families/codecs, exact IDs and placement +are validated on the wire; extensions outside the consumed schema are stripped. +An answered payload and cancellation message are validated transiently and discarded +before the renderer receives Form info plus status. + +Verified pending state admits only that captured Form with matching editor fields. +Changed fields, absence, authentication, transport, malformed data and exhausted +bounds leave the result indeterminate. Answered/cancelled states retain the editor +and draft for consultation with response actions inert. The source has one polite +status region and an explicit retry; checking leaves its fields editable. Replies +remain separate user gestures. The check control stays mounted and focusable while +checking and after pending verification, with guarded `aria-disabled` state and the +source status as its description. Keyboard focus therefore keeps its source owner; +user focus moved elsewhere stays there. The Form editor owns the single polite +region composing verification with retained uncertainty from an earlier reply. +Pending native state leaves that earlier attempt uncertain. Ordinary errors keep +their separate alert treatment. Connection/backend-transport lifetime, immutable +binding, native-data generation, source registry, current metadata, local request +revision and check attempt fence dispatch/publication. A newer native event wins, +including an equal payload. General coverage remains unknown/live-only. +The actual deferred SDK callback rechecks capture and monotone deadline immediately +before dispatch. Accepted session placement publications retire captured owners on +each exact directory/workspaceID transition, including an A→B→A within one turn. +Equal placement hydration preserves them. Live session Forms share this retirement; +global Forms keep their captured directory owner. + +Dock selection/editor keys include occurrence, server/directory, kind, session and +request. Unchanged Form fields retain their DOM identity through metadata refresh, +and DOM labels/controls have unique mounted-editor identities. Cross-project dock +placement compares server, request/session owner and exact source directory. +The human-answer gesture hint is scoped to the shared local service; confirmed +Mission marks remain owned by the authenticated local backend path. + +Status and native-delivery envelopes carry the relay attempt, its captured +`source.connectionGeneration` and an occurrence's `liveGeneration` boundary. +CodeNomad owns these independent counters. The backend advances the live boundary +on status transitions, including ownership error/connected pulses on one attempt. +Recipient snapshots retain that boundary at ingestion through queued ownership +work; byte reservations include the complete envelope. Cached statuses retain their +boundary. The UI captures the accepted correlation and backend-transport lifetime +before native dispatch, fencing old creation/settlement events and stale markers. +Transcript deltas keep their existing ordering and membership rules. + +A current live request may remain provisional while its matching capability +snapshot arrives. Matching server/connection metadata qualifies only that held +candidate, with its client, native-data, binding, Location and request identity +still current. Newer incompatible connection metadata retires the older handshake; +different-generation metadata retires incompatible candidates. Retired requests +remain stale through repeated old statuses. Metadata publication performs zero +pending discovery or queue re-admission. Client-wrapper attachment preserves the +same connection proof while each request captures its actual client/native owner. +Capability snapshots retain their originating backend-transport owner, captured +before HTTP dispatch or workspace-event deferral. Restore selection and descriptor +clones keep the selected snapshot's owner; missing capabilities keep the displayed +snapshot. Unattributed values remain display-only. Cached +snapshots from a retired transport stay display-only until fresh publication. +Current-transport metadata supersedes older native handshakes, including a first +delayed handshake. Occurrence close retains the retired status boundary across +same-ID reuse; a genuinely newer boundary establishes the replacement's admission. +Equal-boundary contradictory statuses or connection identities are rejected before +and after binding hydration. +Source rebinding clears that occurrence's settlement tombstones. A definitively +refused close restores only its exact, still-current request admissions; newer +events and intervening gaps retain precedence. +Uncertain or superseded replies carry structured interrupted-action identity and +render one polite status in the request editor. Ordinary failures retain their +alert treatment. Reply drafts, caret and other-target focus keep their owners. +UI and backend SSE diagnostics log event kinds, fixed failure categories and existing +numeric client identity. Parser, malformed-native-event and subscriber failures keep +answer and permission-feedback payloads and raw exceptions outside their entries. + Native permission events are ephemeral and replies omit the reason. CodeNomad therefore captures confirmed replies and observed native settlements separately, since a native settlement can come from another client or a cascade. Yolo @@ -62,6 +165,14 @@ a fabricated decision and is never replayed automatically. Decisions made while CodeNomad was offline have no receipt; never reconstruct one from a tool's success/error or from saved permission rules. +Yolo also runs for explicit OpenCode servers (capability `yolo`), replying on the +project's server connection without receipts. Their event stream is live-only, so +on each `connected` status `AutoAcceptManager.recoverPending` re-reads +`GET /api/session/{id}/permission` for the Yolo-enabled sessions it already knows +(at most 50), after an ownership check, and feeds them to the ordinary auto-accept +path. It publishes nothing to the dock and is not general recovery: local projects +and non-Yolo sessions keep the rules above. + Permission snapshots and receipts live under the CodeNomad profile's `permission-receipts` directory, in atomic per-request files. The namespace uses the execution host, native discovery root and authenticated service channel; @@ -76,6 +187,13 @@ uses the daemon's default directory as a substitute or triggers strategy discove ## Validation +The pending snapshot broker requires `pendingRecovery` before acquiring a native +connection or reading host paths. Explicit targets have the E1 `liveOnly` policy: +snapshot requests return a structured capability refusal. Native manual replies +keep their separate live-request admission path. Receipt reconnect enumeration +uses the same recovery admission before connection acquisition or loaded-location +and permission-list reads. + `tests/browser/interruption-dock.test.ts` exercises real Solid session, transcript, composer and panel components, the native event dispatcher and isolated HTTP fixtures: native answer rendering and history rehydration, dock-only pending questions, diff --git a/dev-docs/OPENCODE_COMPATIBILITY.md b/dev-docs/OPENCODE_COMPATIBILITY.md index ff1e958bb4..b3f837b8c1 100644 --- a/dev-docs/OPENCODE_COMPATIBILITY.md +++ b/dev-docs/OPENCODE_COMPATIBILITY.md @@ -81,6 +81,68 @@ reply the goal reviewer rejects, pausing the goal) runs in the minimum/latest CI ### Contract notes +- Internal explicit transcript navigation consumes `message.list` through the + existing session-owned proxy: initial `order: asc|desc`, `limit <= 200`, then + opaque cursor-only continuation options. Both cursor directions preserve their + originating order. Backend admission validates the qualified native + `{ id, order, direction }` shape and rejects unknown formats or mixed + cursor/order input. `scripts/test-opencode-message-pages-native.mjs` checks native + import/replay and message continuations using an owned runtime and synthetic + messages with zero provider requests. Enriched CodeNomad windows/outline/query + readers retain their shared-local capability gate. Runtime version is evidence + recorded by the check; feature admission follows the consumed API contract. + +- Explicit endpoints have one controlled dispatch seam in + `opencode/servers/transport.ts`; connection admission and probes supply its + fetch instead of issuing an independent network request. Registered and ephemeral + administrative probes share one read-only connection-owner lane, negotiating the + consumed E1 OpenAPI contract and reading canonical `server.info()`. One five-second + monotone operation deadline covers all phases. The shared bounded-response wrapper + buffers at most eight MiB of decoded bytes for every success/error envelope before + SDK parsing. The wrapper owns each Response at receipt, covering cancellation + before and during the header-to-reader admission wait. Body/reader cancellation + occurs once; late responses, held cleanup and cleanup rejection retain independent + retirement. The Form (four MiB) and media (sixteen MiB) consumers share that same + ownership boundary and keep their operation-specific deadlines. Cancellation and + cleanup release the probe lane independently. The result + projects negotiated feature policy, a validated numeric release or unavailable, + check time and fixed diagnostic categories/phases. Regular fetch preserves + streaming and native wire requests; the compatibility adapter continues to own + location-context serialization and feature-contract recognition. Explicit E1 + admission always negotiates canonical sessions/chat, replay (`native` and + compaction metadata), live Forms/permissions, catalogs and event routes. Agent/model + selection POSTs require their consumed request fields; MCP/skill catalogue GETs + require location selectors and the consumed response envelopes/entry fields. + Optional catalogue descriptions and error display details stay optional. Missing + required schemas/routes produce `missing_contract`; runtime release labels are + admitted by consumed API contracts. Session environment, bundled plugins and integrated + image enrichment retain separate capability policy. Local admission retains its + consumed runtime requirements. Connection generations revoke captured clients, + fetches, admissions, pending request-body readers and streaming responses on rotation/forget/disconnect/removal/shutdown; + origin changes clear memory credentials before metadata publication. Endpoint/transport regressions exercise isolated HTTP/TLS + servers, pinned DNS, trust and hostname verification, header isolation, redirect + refusal, probe limits and streaming cancellation. + `connections.test.ts` exercises independent targets, coalesced/fenced acquisition, + the four-target budget, project leases, probe isolation and retained old wrappers. + +- The internal event relay subscribes once per admitted explicit target and once + through the local adapter. Native `/api/event` covers all Locations on its + server; its connected marker confirms only the current attempt. The installed + client's lazy shared subscriber has a 4,096-event count bound; the relay applies + its own job, byte and ingestion-to-delivery deadlines. Captured source clients, + exact native Locations and occurrence epochs fence routing. Global notifications + reach only that source's occurrences; unknown deletions produce targeted gaps. + Backend receipt/automatic-reply/quota enrichment admits its local capability + before any deferred explicit work can reach local credentials or storage. + UI dispatch validates binding/source and the status-established relay generation + before wildcard and typed subscribers. A status arriving before occurrence + hydration waits in a bounded cache for its exact binding; only the status replays. + Legacy sourceless frames are local-only. Explicit daemon continuity tokens are + attempt-local; URL trust permits ordinary reconnection without a provenance gate. + Physical browser SSE health stays separate from target-native confirmation. + Explicit reconnect skips unavailable worktree reads and live-only pending + snapshots; the dock's source disclosure presents live-only coverage. + - Generated client URLs keep their `baseUrl` prefix and pass through unchanged; scheduling classifies API paths relative to the proxy prefix. - The generated `experimental.session` methods and their `session` aliases use @@ -99,6 +161,32 @@ reply the goal reviewer rejects, pausing the goal) runs in the minimum/latest CI Location map canonicalizes path flavor and trailing separators; pending recovery retains its existing-only leases and identity checks. Plugin setup remains activation-scoped; native services are acquired in the request graph. +- Internal explicit workspaces use the separate method/operation allowlist in + `server/explicit-proxy.ts`. Sessions, chat, catalogs and manual native interruption + replies share their captured endpoint/client/fetch and exact directory authority. + Directory cursors stay directory-scoped; project IDs and ancestry grant no extra + authority. Private workspace policy is checked before acquisition; workspace + lifetime, connection generation and native session placement fence asynchronous + work and response publication. Ordinary finite proxy responses are buffered up to 64 MiB + before publication. Cookies, redirects, authentication challenges and incoming + forwarding/auth/internal headers stay at the proxy boundary. Renderer chat actions send their captured explicit + connection generation in `x-codenomad-connection-generation`; the proxy validates + its single positive-integer value against current workspace capabilities before + acquisition and throughout dispatch. A stale value returns `409 explicit_action_superseded`, + localized by the renderer. The private header stays inside CodeNomad, allowing + multi-request instructions/profile/send actions to retain their starting + generation while renderer metadata updates are still in flight. Shared-local proxy + sanitization also strips this private header while keeping local admission semantics. + Uncertain mutations + are never retried. Native file/working-diff reads, scoped background Shell reads + and stops, and configured MCP connect/disconnect use the qualified explicit + allowlist. Moves, PTYs, administrative operations, generic RPC, pending recovery + and enriched receipts stay capability-gated. Session-media reads use the workspace + capture, native message ID, current Location, undo boundary and digest, with no + disk fallback. Public project opening selects a registered explicit server and + validates its native directory before publication. +- Explicit renderer media admission uses passive raster MIME qualification and canonical same-session native references correlated with held message positions and digest. The shared `embedded-asset.ts` validator checks complete data-URI length, MIME/prefix, base64 alphabet/padding and unused bits before decoding. The 8 MiB URI ceiling is distinct from the 32 KiB transcript deferral threshold. Backend finite-response transport and media-reader bounds retain their separate contracts. +- The media route's request-local `OpenCode.make({ baseUrl, fetch })` wraps only its captured connection fetch, retaining authentication, directory encoding and transport revocation. The lightweight `session-media-contract.ts` supplies `MESSAGE_LIMIT` (16 MiB) to this reader and the stored-asset reader. HTTP applies it to the whole decompressed response, success or error, before the official client's text/JSON parser. Native/Undici fetch supplies decoded gzip/deflate/br bytes; reconstructed SDK responses preserve status/statusText/content type and remove stale encoding/length headers. Local reads use the same bound with their existing connection policy. Overflow and cancellation release the upstream reader under the route's 30-second, workspace and socket lifetime. Request observers also bound their acquisition wait without cancelling shared connection work. - The proxy allowlist stays closed to pairing (`/api/pair`, `/auth/connect/*`), credential export/creation (`/api/credential`) and experimental voice (`/api/experimental/voice/session`); a runtime update never widens it or @@ -150,6 +238,49 @@ packed pruning plugin declares every bare import, including `@opencode/schema` ### Capability-checked loaded-only pending recovery +Explicit E1 manual interruptions retain request-local client, binding, native and +connection generations, metadata and native Location through dispatch and +acknowledgement. Global Forms use the once-encoded native directory on the captured +official client. Their human-answer hint remains local-service-only. Disconnect +and backend restoration retire admissions, retain editors and expose unknown +coverage in the dock's source details. Current live events admit only their exact +request. Explicit mutation failures and view activation schedule zero pending +recovery reads. A known explicit-server Form has an individually bounded native +GET through `explicit-form-verification.ts`: at most two Session GETs and one Form +GET, or one global Form GET. Its request-local official client wraps the captured +fetch with the shared `bounded-response-fetch.ts` seam. Every response, including +errors and Session placement reads, is limited to four MiB of decoded HTTP bytes +before SDK text/JSON parsing. One ten-second operation budget includes acquisition, +profile and pre/post placement checks. Non-200 status and invalid wire values remain +indeterminate. The consumed Form schema validates native special-number strings, +field conditions/options, state and complete answer before discarding answer and +cancellation message from the renderer projection. Permission GET remains closed; +stale permissions await their current live event. +The renderer revalidates at the deferred SDK callback's actual dispatch boundary. +Session placement tokens advance at accepted publication rather than at predicate +evaluation, keeping an old verification and its granted reply retired across +placement ABA. Equal placement refreshes preserve current owners. The source Form +editor keeps one composed polite result and a stable, guarded keyboard check control. +Receipt routes return structured `historyEnrichment` refusals before local/native +acquisition; local loaded-only recovery keeps its existing contract below. + +Explicit CodeNomad event envelopes carry the captured connection-owner generation +in `source.connectionGeneration`, independently of the relay-attempt `generation`. +`liveGeneration` identifies each occurrence's status boundary, including a +same-attempt routing gap. The relay retains that boundary from recipient ingestion +through ownership waits and charges it in the queued envelope. Status replay keeps +its original boundary. Explicit missing/invalid correlation fails closed; local +sourceless and legacy status compatibility keep their existing admission. + +The renderer captures source and transport-lifetime authority at dispatch. A +current creation can wait for matching server/capability metadata in either order, +without rereading or replaying its event. Matching metadata qualifies only its +captured current candidate. Gaps, stale statuses, incompatible metadata, client, +native-data, binding and Location changes retain their independent retirement +fences. Common prompt/inventory/media request owners retain their strict generation +contract. Form verification grants only the captured known identity; project coverage +retains the live-only policy. + Rules: [NATIVE_INTERRUPTION_UX.md](NATIVE_INTERRUPTION_UX.md). Pruning/history methods have their own support and write checks. diff --git a/dev-docs/OPENCODE_INTEGRATIONS.md b/dev-docs/OPENCODE_INTEGRATIONS.md index b731bd8bb1..d01e5e1ee7 100644 --- a/dev-docs/OPENCODE_INTEGRATIONS.md +++ b/dev-docs/OPENCODE_INTEGRATIONS.md @@ -241,6 +241,16 @@ request after an uncertain result: check the application, then require a fresh a ## UI read model +Explicit OpenCode projects admit read-only plugin inventory and integration status +through `plugins`. Integration attachment/binding, catalog installation and host +installation require shared-local execution admission. The Status module admits +`plugins` before context and inventory/status demand, and `pluginWrite` before +constructing host controllers or binding demand. Remote sections retain plugin, +application and connection status with read-only switches; the conversation line +requires its admitted attachment owner. Add and row-action +components gate before mounting their dialogs or subscriptions. The shared +activation switch rechecks `pluginWrite` at native activation and dispatch. + `createIntegrationsStore` (`stores/integrations-store.ts`, reading through `lib/integrations-api.ts`) is the read model for UI surfaces that show integrations. `demand(instance, directory)` reads that Location until its release; releasing its last demand aborts the read. A surface retains its demand across session navigation within the same diff --git a/dev-docs/OPENCODE_RUNTIME_SETUP.md b/dev-docs/OPENCODE_RUNTIME_SETUP.md index a7d013f124..490a1408dd 100644 --- a/dev-docs/OPENCODE_RUNTIME_SETUP.md +++ b/dev-docs/OPENCODE_RUNTIME_SETUP.md @@ -28,8 +28,94 @@ Missing APIs, explicit OFF, a masking block, failed activation or missing exact calendar registration keep the schedule paused or in an explained error state. Play of a Mission without launch criteria follows its own admission path. +## Internal explicit-endpoint admission + +`opencode/servers/origin.ts` supplies synchronous root-origin and literal-address +validation to both registry metadata and `opencode/servers/endpoint.ts`, rejecting +userinfo, query, fragment, subpaths and wildcard hosts. Explicit private addresses +are accepted; HTTP requires loopback, including every DNS answer for localhost. +Wildcard, multicast, link-local, cloud metadata and unsupported IPv6 transition +addresses are refused, including IPv4-mapped forms. DNS is resolved and all answers +validated on every dispatch; Undici dials one validated address with the original +hostname retained for TLS verification and SNI. Redirect responses are refused. +Registry metadata requires the normalized origin, including canonical IPv4-mapped +loopback literals; DNS checks belong to dispatch admission. +The shared local service keeps its own `assertLoopbackServiceUrl` admission. + +`createExplicitTransport` is a backend-only foundation seam. Its `fetch` preserves +native methods, paths, query, directory headers, bodies and response streaming; +`probe` permits only GET `/api/info` and `/openapi.json`, with a five-second overall +deadline and an eight-MiB body limit. Probe limits include DNS and body consumption; +cancellation/overflow close the owned dispatcher. Functional chat and SSE keep +their caller/lifetime cancellation without the probe deadline or buffering limit. +Request and response filtering removes hop-by-hop headers and fields nominated +by `Connection`; responses also strip upstream cookies and authentication challenges. + +TLS uses verified platform trust. A supplied profile CA returns the structured +`custom_ca_unsupported` diagnostic; use a recognized certificate chain or an +existing loopback tunnel. Endpoint diagnostics carry stable codes for translation. +The foundation is consumed internally; public profile testing and project opening +remain with their separately authorized routes. + ## Setup and recovery +### Internal explicit OpenCode credentials + +Explicit OpenCode credentials are scoped by resolved profile/config identity, +server ID and normalized origin. `credentials.ts` and `pairing-store.ts` retain +pairing tokens and manually entered passwords across launches in the private +backend `opencode-server-pairings.json` (0600) beside the profile's `config.yaml`. +The backend shares one credential owner across its windows; configuration stores +the server name and URL, while public config/events expose whitelisted metadata. +Static summaries conservatively return `hasCredentials: false` and +`needsCredentials: true`; live summaries use the credential owner's status. +Removal, origin replacement, credential expiry or HTTP 401 clears the secret. +`clear(serverId)` works after metadata removal. Errors use only `unknown_server`, +`invalid_credentials`, `metadata_unavailable` or `closed`. + +`SettingsService` retains a single credential and connection owner across backend +windows. Rotation and forgetting synchronously revoke the target's generation; +Disconnect releases its reservation and aborts owned HTTP/streams. Registry changes +clear credentials before origin retargeting or removal, including subsequent ID reuse. +`WorkspaceManager.shutdown()` disposes connections and private memory before cleanup. +Captured SDK clients, fetches and pending admissions are fenced at dispatch and completion. +Uncertain sends are never replayed. +The shared home/launcher Remotes disclosure pairs, browses and opens projects; +host-only addition and removal use the authenticated administrative routes. See +[DESKTOP_DATA_PROFILES.md](DESKTOP_DATA_PROFILES.md#explicit-opencode-credentials). + +`OpenCodeServerConnections` admits explicit E1 contracts using bounded read-only +OpenAPI negotiation through the protected dispatch seam. Missing required contracts +produce `missing_contract`, independently of the local runtime minimum. The explicit +contract consumes canonical session/chat/replay/Form/permission/event APIs; +environment projection, desktop plugins and integrated images retain separate capability +policy. Project-occurrence lease acquisition and explicit Connect share a target's +reservation and pending connection. Administrative probes share a separate single +five-second/eight-MiB lane. Registered and ephemeral candidate probes share its +`probe_busy` admission. One monotone operation deadline spans credential admission, +DNS, TLS, OpenAPI negotiation, canonical `server.info()`, decoded bodies and result +publication. The shared bounded-response wrapper charges success and error bytes +before SDK parsing. Request cancellation, socket close and owner disposal retire +the operation; reader/dispatcher cleanup runs independently of its completion. +Response ownership starts immediately at transport receipt and spans admission +before reader acquisition. Rejected admission cancels through the owned body or +reader exactly once, including a response received after cancellation; cleanup +rejection is observed independently of the operation's completion. +Candidate authentication lives only in operation-local backend memory. Probes use +GET `/openapi.json` and `/api/info`; active reservations, project leases and event +subscriptions keep their separate owners. + +`GET /api/opencode-servers` reads local-first validated metadata and live owner +state. The read matches captured reservation origins to current metadata and its +displayed summaries; a mismatch yields `unknown` with the real quota reservation +retained. Dispatch assertions retain their normal lifecycle authority. +`POST /api/opencode-servers/probe` tests a validated, unregistered root +origin with optional Basic credentials. Both require authenticated host admission, +a loopback peer outside Remote Control ingress, a known listener/configured Host +and trusted browser Origin/Fetch Metadata. Responses carry `no-store` and fixed +diagnostics; missing/unstructured info leaves version unavailable. Public opening +passes its explicit server ID through the qualified workspace creation path. + Startup recovery and Preferences share `OpenCodeSetupPanel` and its store, but missing installations, known incompatibility and optional updates expose different actions; installed/running/minimum/recommended versions and the diff --git a/dev-docs/PANEL_EXTENSIONS.md b/dev-docs/PANEL_EXTENSIONS.md index d9dfe63398..6849efe55b 100644 --- a/dev-docs/PANEL_EXTENSIONS.md +++ b/dev-docs/PANEL_EXTENSIONS.md @@ -21,7 +21,7 @@ bounded tool-result asset metadata and demand-only embedded bytes from the currently displayed session, never prompts, transcript text, arbitrary URLs, local files, credentials or a generic RPC proxy. API 3 adds the explicit `repository.workItems.read` permission: bounded issue and pull request pages of -the project's GitHub, GitLab or Gitea/Forgejo repository, read by the host, and +the shared-local project's GitHub, GitLab or Gitea/Forgejo repository, read by the host, and opening one item's page in the browser. API 4 carries `session.context` plus any non-empty subset of a finite permission set used by the independent **Design** image companion ([API 4](#api-4)): read-back images of the displayed conversation, their prompts, @@ -179,6 +179,16 @@ their metadata and demand-only full preview remain available to the addon. Use `apiVersion: 3` and its two permissions. Inspection shows the repository permission before the trust checkbox; the context also carries `colors` (API 2). +Both work-item routes require a project using the shared local OpenCode service. +After consent and workspace lookup, the current `WorkspaceManager` binding gates +access before `ForgeWorkItems.list` or `itemUrl`, including their caches, repository +discovery, CLI sign-ins and network. Every explicit binding, including loopback +and disconnected targets, returns HTTP 403 with `explicit_capability_unavailable`, +capability `git` and reason `{ code: "localOnly" }`. This host integration boundary +holds independently of the target's native Git capability. Unknown workspaces +retain HTTP 404; an omitted instance retains HTTP 400. Profile-wide installation, +activation, metadata, API 1 context and API 4 preferences keep their own authority. + ```js const page = await codenomad.workItems.list({ kind: "pullRequest", query: "", page: 1 }) // { status: "ok", repository: { provider, host, path, webUrl, access }, items, page, hasMore, total } @@ -408,6 +418,7 @@ node scripts/test-panel-extension-native.mjs --api3 node scripts/test-panel-extension-native.mjs --api4 node scripts/test-panel-extension-electron.mjs # real preload, createWindow webPreferences; Linux may add --no-sandbox node --import tsx --test packages/server/src/forge/forge.test.ts packages/server/src/server/routes/panel-extension-work-items.test.ts +node --import tsx --test packages/server/src/server/routes/panel-extension-work-items-boundary.test.ts node --conditions=browser --import tsx --test packages/ui/src/components/panel-extensions/work-items-channel.test.ts node --import tsx --test packages/ui/src/components/panel-extensions/image-bounds.test.ts node --import tsx --test packages/server/src/panel-extensions/api4.test.ts packages/server/src/server/routes/panel-extension-api4.test.ts packages/server/src/remote-control/panel-extension-remote.test.ts @@ -459,8 +470,10 @@ host, OS version and each summary's `real` line in the review. ## Agent conventions +- Project admission checks extension methods before constructing a channel or fetching a panel document. API 1 context and API 4 preference-only panels retain profile authority; API 2 assets, API 3 Git integration and API 4 Design/Images methods require their execution feature's admission. API 3 retains its independent local host guard in the backend. Native server-provided Design agents keep their ordinary chat catalogue authority. + - Right-panel customization keeps Extensions below a separator in a native disclosure, collapsed on each popup opening. Expanding mounts one compact searchable list combining installed and online addons, deduplicated by ID; collapse, dismissal and inactive/instance changes dispose its requests and confirmations; never add separate list modes or a floating extension window. The per-addon checkbox above the disclosure is the sole activation control, including for disabled installed addons; never add a manager switch or a per-window visibility gate. Reset changes built-in layout only, never addon consent. Keep metadata on hover/focus and technical consent details folded; retain explicit trust and digest-bound replacement/removal. Installation and activation are profile-wide. Legacy folder grants never become general consent. - External panel extensions use `components/panel-extensions/` and `styles/panels/panel-extensions.css`. The official online catalogue is in `NeuralNomadsAI/CodeNomad-Extensions`; metadata discovery never downloads author code. Inspect/install revalidate the exact index/manifest/digest and use bounded credential-free HTTPS GitHub release downloads, never client-provided URLs. Never import author JavaScript into the main renderer or expose native/OpenCode bridges. ZIPs contain only a manifest and a self-contained HTML panel; install/replacement revokes activation. API versions cover only the public `window.codenomad` contract; never make internal Solid modules or import paths part of it. -- Extension API 3 requires explicit `repository.workItems.read` consent. `work-items-channel.ts` takes only kind/query/page/number from addons; the project folder, remote, provider and credentials stay host-side in `server/src/forge/` (CLI sign-ins or anonymous REST on the public forges only, never stored tokens, never `--paginate`, never addon text inside forge query syntax, never anonymous requests to other hosts). Opening uses the server-built forge page through `openExternalUrl`, rate-limited; never open addon-supplied URLs. Each API version carries exactly its own capability. +- Extension API 3 requires explicit `repository.workItems.read` consent and the current owner-held workspace binding to the shared local service, before any forge/cache entry. Reject every explicit target with `git` / `localOnly`, independently of native Git capabilities. `work-items-channel.ts` takes only kind/query/page/number from addons; the project folder, remote, provider and credentials stay host-side in `server/src/forge/` (CLI sign-ins or anonymous REST on the public forges only, never stored tokens, never `--paginate`, never addon text inside forge query syntax, never anonymous requests to other hosts). Opening uses the server-built forge page through `openExternalUrl`, rate-limited; never open addon-supplied URLs. Each API version carries exactly its own capability. - Extension API 4 is a finite permission set (`PANEL_EXTENSION_API4_PERMISSIONS` in `panel-extensions/contract.ts`): one permission = one capability, fixed methods, one install sentence in every locale and its own server-side check. Adding a permission means a new contract entry, schema case, bridge object, route and sentence together; never a registry, a pass-through method or an author-chosen session/Location. `api4-channel.ts` owns the 19.5 s deadline, four-request cap and mount/session fencing for every API 4 method; keep APIs 1 to 3 on their exact tuples and channels. - Extension API 1 stays context-only; API 2 requires explicit `session.assets.read` consent. `assets-channel.ts` derives session authority from the current mounted host, never author selectors, and exposes only bounded asset pages/exact digest-bound embedded reads. Use the presence-owned history bundle's fixed `assets`/`assetRead` methods, never transcript stores, generic RPC, remote downloads or filesystem fallbacks. Recheck consent and Location ownership after IO; revoke old-port/session/reconnect results. Gallery HTML belongs in the independent catalogue repository; never add it to the application renderer. diff --git a/dev-docs/PLUGIN_CONTROLS.md b/dev-docs/PLUGIN_CONTROLS.md index a13dacf678..95577afe3b 100644 --- a/dev-docs/PLUGIN_CONTROLS.md +++ b/dev-docs/PLUGIN_CONTROLS.md @@ -315,4 +315,5 @@ guessed paths. - The Plugins Add menu (`components/plugin-add-menu.tsx`) uses stable item descriptors for **Add an integration…** and **Add a plugin…**. The integration catalog window (`integration-catalog-window.tsx`) uses shared window primitives, overlay surface, an upper-right close button and reviewed catalog IDs through `pluginSourcesStore.installIntegration`; native integrations lock the focusable scope selector to Global. Confirmation uses the shared 600 ms guard. Installation hints and reconciliation use the existing source store. - The Add plugin window (`components/plugin-source-add.tsx`) is a transient `.window-*` popover without a close button: a `--surface-field` spec input, the native scope select (Global default, Project disabled when unavailable), the trust sentence and the Project warning. It closes on success and keeps refusals inline; it never announces an active plugin. - Recognized integrations keep their Plugins row alongside their own Status section. Both use `PluginActivationSwitch` and `PluginRowActions` with shared mutation/in-flight state. Application installation and conversation attachment actions belong to the integration section. Source ambiguity labels its Plugins row **Non-conforming** and suppresses its integration section. Supplemental integration details use `InfoPopoverButton` or tooltips, with localized terse labels. +- A project on an explicit OpenCode server reads its snapshot from native `config.get` + `plugin.list` under `plugins` admission, with no write targets: rows and switch states render as for a local project, switches stay disabled, and the Add icon and row actions are hidden (`pluginWrite`). OpenCode has no API writing a server's plugin configuration; never write or proxy its documents. - Plugin packages that fail before exporting an ID remain visible by their native target with check/update actions and failure details in the name tooltip. Do not fabricate plugin IDs or activation switches for these entries; reconcile them into ordinary rows once native loading succeeds. diff --git a/dev-docs/PROJECTS.md b/dev-docs/PROJECTS.md index c05c97abd2..d45fe775ee 100644 --- a/dev-docs/PROJECTS.md +++ b/dev-docs/PROJECTS.md @@ -2,10 +2,117 @@ Closing project tabs, temporary workspaces, the new-instance launcher and the Git-unavailable degraded mode. +## Durable execution identity + +Saved workspace tabs carry an optional `serverId`; absence selects `local-shared`. +Reconciliation, occurrence numbering, close/reopen preservation and recent-project +metadata use server ID plus directory. Explicit directories keep their exact case, +separators and trailing characters; local paths keep the local normalization. +The live backend descriptor supplies the binding when capturing a tab. + +Local tab lifecycle events carry that same server/directory identity and a +server-qualified occurrence. An accepted close captures the window's remaining +membership and fallback selection immediately, independently of the backend +DELETE result. Other windows keep their own membership until a backend event. +Rename dialogs capture the initiating tab's server and directory when opened; +submission updates names for that binding's open occurrences and recent metadata. +The path-only home-page rename explicitly targets `local-shared`. + +Explicit tabs whose backend occurrence is absent stay in the saved restoration +graph with their drafts, attachments, selection and optional catalogs. Restoration +reopens registered explicit targets through their saved server/directory binding. +Unknown/deleted profiles retain the same saved binding for repair. +The home page and the launcher show one recent list, local and explicit entries +together (`getLaunchableRecentFolders`); a click reopens server and path. Both +mount `RemoteProjectMenu` (`components/remote-project-menu.tsx`): an inline +"Remotes" disclosure (Recents heading typography, leading chevron) listing explicit OpenCode servers, whose "+ Project" action and whole row open folders +browsed in place through `listOpenCodeFolders` (Backspace parent, Escape servers, +then collapse). Its existing navigation row reserves space for the bidi-isolated server name and the folder path; the full name remains in its text and tooltip. The server row is a single button, including its visible action. The disclosure has a host-only paste field reusing the add-server path and a +host-only row context menu to remove a server. Browse, Clone and Temporary stay local. Model recents and favorites +carry server identity, with absent IDs selecting the shared local service. + +## Explicit session inventory + +The internal explicit-project reader uses the binding's exact native directory, +including case, separators and trailing characters. Its first native session page +includes roots and descendants, with a 200-row request limit; subsequent demand +passes only the opaque `cursor.next`. Each page must contain sessions in that exact +Location. Project IDs, parents, nested directories and worktrees grant no expansion. +The sidebar loads the next page when its end becomes visible, without explanatory text; +after three automatic pages that add no visible row it waits for the user to scroll +again, and a failed page waits for Retry. Sorting works on the loaded subset. Native title search reads one bounded page and +identifies incomplete matches so the user can refine the query. + +Partial pages and errors retain saved display rows. Absence reconciliation requires +the qualified exact inventory's terminal page, including an empty terminal page, +and preserves rows changed concurrently. Targeted restored-session reads validate +the returned identity and exact Location; ancestry reads are bounded to 200 IDs. +An in-directory child with an unavailable parent becomes a display root while +retaining its native parent metadata. The inventory is exercised by store and browser +regressions and an isolated native inventory qualification. + +## Internal server attachment observations + +`WorkspaceManager.readServerAttachments()` captures unpublished workspace records +and the connection owner's occurrence leases before awaiting the private native +parent transport. The two views overlap and retain independent receipts. Lease +publication adds the real backend instance ID; failure, cancellation and release +retire their snapshots. Each view returns at most 512 reservations, with overflow +reported as unknown. An unresolved local path appears as in-flight coverage. + +Electron and Tauri project retained tab identities from their accepted window +records and verified session manifests, preserving unknown server IDs and exact +directories. Opaque memory-only handles bind to the native owner and manifest tab +index. The union of live native registrations and retained windows includes +ephemeral windows; Preferences and remote CodeNomad windows have separate owners. +Global coverage remains `unknown`. Browser application tabs publish bounded positive +declarations through their authenticated event-stream capability. The backend +captures this participant owner alongside both reservation owners before native +awaits and includes its epoch in current checks. Retained manifest coverage and +backend reservation coverage have their own complete/unknown states. Host removal +closes known project tabs, disconnects the target and forgets its secret and profile; +these internal observations retain their separate unknown global-coverage contract. + +`ProjectParticipants` holds at most 32 stream owners and 512 declared references, +with at most 32 references per update. Each reference carries exact server/directory +metadata and a memory-only tab-membership lifetime; supplied backend occurrence IDs +must match their current immutable binding. Reattaching a tab rotates its lifetime. +Native retained entries keep their separate handles and manifest-index identity. +Transport loss preserves bounded references and an unresolved owner; unknown slots +remain held until backend restart. Overflow retains unknown coverage. Declaration +observations and native observations share the reader's 32-owner/512-reference +ceiling; an excess returns an explicit overflow with unknown coverage while the +source owners retain their bounded observations. Declaration +admission rejects either raw query delimiter (`?` or `;`), including an empty query, +before body parsing or capability admission. Accepted declarations fence older pending updates and have a five-second +monotonic acceptance deadline. Revisions and stream capabilities fence replay. + +Live native coverage awaits sender/document-bound publication with pre-mutation +admission on both hosts. The synchronous tab and binding mutators require an awaited +native fence to qualify this coverage; post-mutation effects retain unknown. Global +participant coverage also requires admission on every project-use path, including +authenticated callers without an event stream. Current declarations qualify their +own metadata observations while these independent gaps stay unknown. + +Verified manifest reads accept at most 1 MiB, using 64-KiB scratch blocks and a +single overflow sentinel before retaining or decoding excess bytes. The private +read and current requests each have a five-second deadline; settlement checks a +captured monotonic expiry as well as the scheduled cleanup timer. + ## Agent conventions +- Native workspace opening reads the occurrence's descriptor from the authenticated local backend and accepts only `local-shared` (or a legacy descriptor without binding) before worktree lookup, filesystem resolution or application launch. Every explicit binding, including loopback profiles and homonymous host paths, returns `explicit_capability_unavailable` with capability `files` and reason `localOnly`. Unknown/stale occurrences fail closed. Electron and Tauri enforce this independently of renderer state. + +- `WorkspaceManager.requireWorkspaceCapability(workspaceId, capability)` is the synchronous shared admission gate for closed `ServerCapability` product operations, called before connection acquisition or adapter effects. It uses private workspace policy and returns the occurrence's abort signal; published capability descriptors are display snapshots. Explicit refusals carry `explicit_capability_unavailable`, the typed capability and `reason.code`. Each admitted native operation still captures and validates its current connection contract, generation and exact session Location. Local unknown initial capabilities retain the local admission behavior; host adapters keep their local-workspace guard. +- Explicit `list()`/`get()` descriptors snapshot the connection owner's existing validated connection synchronously. Native E1 features carry that connection's generation; absent, pending or revoked connections carry generation `0` and `unknown/contractUnverified`. Qualified reconnection restores E1 availability for every attached occurrence. Issued snapshots retain their captured capabilities; explicit request fences use the occurrence's immutable binding reference, abort signal and captured connection assertions. Local descriptors retain their existing identity semantics. +- The renderer instance owner installs a non-enumerable, memory-only `renderBinding` origin at occurrence admission and preserves it through metadata updates. Retained media consults that origin across component remounts and display-cache eviction; a changed live binding receives the unknown-source policy. Closing and opening a new occurrence installs its own origin. This field stays outside captured/persisted project metadata. +- Yolo admission uses `yolo` through the workspace-owned persistence adapter before state reads, native session access and automatic permission replies. Explicit occurrences are admitted on a validated connection: replies use that connection without permission receipts. Direct routes return the structured capability refusal when the capability is not available. +- A validated explicit connection also makes `files`, `git`, `backgroundShells`, `yolo`, `providerUsage` and `plugins` available. Files and Changes read the server through `opencode/servers/remote-workspace.ts` (`dev-docs/FILES_PANEL.md`); background shells go through the explicit proxy's closed operations with a working-directory filter. Host readers and every write (`worktrees`, host Git, file writes, configuration documents) stay refused; the UI-only `hostGit`, `fileWrite` and `pluginWrite` features are never granted to an explicit project. Temporary Keep/Discard require `worktrees` before consulting the host folder registry; Create/Abandon accept only the local target. Homonymous folders and native session IDs on explicit targets retain their separate authority. + +- The execution-binding parser (`opencode/servers/registry.ts`) preserves `serverId + directory` independently of workspace occurrence IDs. A missing server ID defaults to `local-shared`; an unknown ID remains a repairable reference. Explicit directories retain their exact spelling, separators and case. Public project opening selects the named server through `POST /api/workspaces`. +- Workspace creation accepts `WorkspaceCreateOptions.serverId`. Each explicit occurrence owns an immutable binding and a target lease acquired before asynchronous admission, retained through publication and released on failure, cancellation or closure. Occurrences share target admission across backend windows. `workspaces/explicit-workspace.ts` requires the captured connection's native Location and readable-directory proof with exact returned directory spelling, a five-second validation deadline and eight-MiB per-response limit. Missing, unreadable, mismatched or unqualified paths fail closed; host filesystem, Git, WSL, binary discovery and environment setup stay outside this branch. Attachment is exercised by `explicit-workspace.test.ts` and `scripts/test-opencode-explicit-location-native.mjs` with an isolated CLI. - Closing a project tab detaches it immediately and requests deletion of that occurrence's logical backend workspace record; failures notify and never retry automatically. Separate occurrences of the same folder are independent. A `workspace.stopped` deletion closes the same record in other windows and notifies only windows displaying it that did not initiate the close. CodeNomad never evicts native Locations; OpenCode sessions keep running and reopening finds them. Whole-window close, app quit, renderer reload and backend shutdown keep existing restoration behavior. Temporary discard and server stop events use local-only tab detachment, not another DELETE; Keep closes the retained project normally. - Git is a full-functionality prerequisite, with directory-only degraded conversations when the backend cannot find Git. Only the explicitly opened physical folder is session authority in that mode; never infer sibling worktrees from native project IDs. Keep ancestor/descendant mutation identities covered by the deletion fence across Git availability changes. Inform agents through the owned native `codenomad.git-availability` instruction before prompts/custom commands, remove stale context after recovery, and keep this advisory separate from fail-closed environment synchronization. Do not add a blocking Git setup UI. Validate with `scripts/test-git-degraded-native.mjs` using an isolated CLI/database and provider. - Temporary instances (`workspaces/temporary-workspaces.ts`, UI `stores/temporary-instances.ts`) are ordinary non-Git workspaces on CodeNomad-created direct children of `/temporary-workspaces`. Registry membership (`temporary-workspaces.json`), not location, makes a folder temporary; keeping only unregisters it and adds a named recent project. Discard deletes only registered children of that root, refuses running conversations and other open tabs of the folder, removes conversations deepest-first, closes the workspace before deleting the folder and keeps failed removals registered; such a folder is reachable only by browsing to it. Closing a temporary tab from the UI asks Keep/Discard/Cancel, except that an untouched one (no conversation, file or unsent draft) closes and is discarded silently (`onlyIfEmpty`: the server refuses with `temporary_has_conversations`/`temporary_not_empty`, and any failure of that quiet discard returns the choice without an error). Before the server stops it, a visible temporary tab yields to its neighbour (or closes if alone) and a refusal restores it in place; `workspace.stopped` likewise closes the tab first and clears the instance in a microtask, because clearing a visible shell's state in the same update as its tab freezes the window. Same-minute names get a `(n)` suffix. Registry changes broadcast `workspace.temporaryChanged`, which clears kept marks in every window. Open temporary tabs are saved and restored with the app state like any project tab (still marked temporary). Only the choice dialog overrides initial focus (to its last, non-destructive choice); confirms keep focus on Cancel. Refusals use stable `temporary_*` codes localized by the client. Validate with `scripts/test-temporary-workspaces-native.mjs` against an isolated CLI. -- The tab-bar new-instance button follows the last tab like a browser: the instance `TabScroll` frame only spans its tabs and the button sits after it, outside the scroller (so focusing it never scrolls the strip), ending up at the strip's end once tabs overflow. Dragged tabs stay visually within the tab list like a browser's (`KeepDraggedTabInStrip`), while the drop slot follows the pointer's unbounded position (`closestUnboundedCenter`). The button keeps its click (full home page, Cmd/Ctrl+N) while a long press, right-click, Alt+Down, Shift+F10 or Menu opens the anchored `NewInstanceLauncher` (`lib/long-press.ts`; only Escape returns focus to the button, never over another surface or the home page): search-first recent projects (an open project switches to its tab) and Browse/Temporary/Clone only. Remote servers, SideCar and management (rename/remove recents, servers, settings) stay on the home page. Browse/clone flows live once in `components/new-instance-dialogs.tsx` (with optional home-only add-server setup) and recent-folder display helpers in `lib/recent-folder-display.ts`, shared with `FolderSelectionView`; styles in `styles/components/new-instance-launcher.css`. +- The tab-bar new-instance button follows the last tab like a browser: the instance `TabScroll` frame only spans its tabs and the button sits after it, outside the scroller (so focusing it never scrolls the strip), ending up at the strip's end once tabs overflow. Dragged tabs stay visually within the tab list like a browser's (`KeepDraggedTabInStrip`), while the drop slot follows the pointer's unbounded position (`closestUnboundedCenter`). The button keeps its click (full home page, Cmd/Ctrl+N) while a long press, right-click, Alt+Down, Shift+F10 or Menu opens the anchored `NewInstanceLauncher` (`lib/long-press.ts`; only Escape returns focus to the button, never over another surface or the home page): search-first recent projects (an open project switches to its tab), Browse/Temporary/Clone and the shared "Remotes" disclosure. Remote CodeNomad servers, SideCar and management (rename/remove recents, servers, settings) stay on the home page. Browse/clone flows live once in `components/new-instance-dialogs.tsx` (with optional home-only add-server setup) and recent-folder display helpers in `lib/recent-folder-display.ts`, shared with `FolderSelectionView`; styles in `styles/components/new-instance-launcher.css`. - The clone dialog (`components/new-instance-dialogs.tsx`) suggests the repository's `git clone` folder name (`lib/clone-destination.ts`) inside a parent: the folder chosen with Browse, else the server-scoped `ui` state `lastCloneParent` (the folder above the last successful clone), else the folder above the most recent project. A destination the user types is kept as entered and sent unchanged; the server creates it. diff --git a/dev-docs/REMOTE_CONTROL.md b/dev-docs/REMOTE_CONTROL.md index 7463c51dd2..9832c0d5ca 100644 --- a/dev-docs/REMOTE_CONTROL.md +++ b/dev-docs/REMOTE_CONTROL.md @@ -58,7 +58,7 @@ browser ─TLS─▶ OpenTunnel relay (forwards ciphertext) ─▶ OpenTunnel SD or fragment, which the router would reinterpret) and judges the path the router routes (`server/routed-path.ts`). It denies host-only paths: login and token bootstrap, Remote Control management, remote windows/proxy, SideCars, - previews and the automation bridge. A live `/previews//…` capability + previews, execution-server administration (`/api/opencode-servers`) and the automation bridge. A live `/previews//…` capability is admitted without a device cookie or public `Origin` (its sandboxed document sends neither) while the host's **Web previews** switch is on, the default: `devices.ts` stores only the opt-out, `PUT /api/remote-control/previews` is @@ -96,6 +96,78 @@ browser ─TLS─▶ OpenTunnel relay (forwards ciphertext) ─▶ OpenTunnel SD ## Validation +The internal server-attachment reader retains unknown browser and paired-device +participation coverage. Native window registration and saved state contribute +their own bounded observations. Browser applications can opt into a dedicated +`codenomad.project.participation` SSE event. Its backend-issued memory-only capability +belongs to that exact authenticated response, independently of supplied connection +IDs. `POST /api/project-participation` admits that capability and its current +cookie/device principal before body parsing, under strict Host/Origin/Fetch Metadata +guards. Raw `?` and `;` query delimiters, including empty queries, are rejected before +body parsing or capability admission. It accepts bounded metadata declarations only; profile/config selectors +remain backend-owned. Errors and request logs use fixed diagnostics and redact +the complete target and body. The response uses `no-store`. + +Transport replacement, backpressure closure, revocation and shutdown retire the +capability and its receipts. Paired authorization is checked again during publication +and observation-current checks. Uncertain closed streams retain their bounded +metadata and unknown coverage without TTL removal. Each participant declares its +own occurrences; global coverage additionally requires owner-enforced admission on +all project-use paths and qualified native live-window linkage. Cookie logout uses +the existing browser session lifecycle, so stream closure remains the participant +revocation boundary for cookie sessions. Host removal closes known tabs and forgets +the registered server; global participation coverage retains its own unknown state. Attachment reads use +the backend's private native-parent channel within its current profile/config +scope, leaving the host-only administrative HTTP prefix unchanged. +The attachment pipe bounds the serialized result to 8 MiB plus its canonical +envelope before body retention or JSON parsing, including expired/replayed IDs. +Overflow drains the rejected line while preserving later responses and shutdown. +Read and current each use a five-second settlement deadline; conservative unknown +coverage persists through timeout or uncertain native publication. + +The internal explicit OpenCode transport accepts a backend-owned origin and +optional Basic credentials. It resolves and admits the target before injecting +authentication, pins the dial address and keeps TLS verification enabled. +Incoming Authorization, Cookie, Host, Forwarded, forwarding and hop-by-hop +headers are stripped; native directory headers remain. Response cookies, +authentication challenges/info and hop-by-hop headers are stripped. Transport +errors expose stable codes with sanitized messages. Each request owns its Undici +dispatcher until response completion/cancellation. Host execution-server administration +uses `/api/opencode-servers` for a metadata-only GET and an ephemeral-candidate +probe POST. Its early guard combines CodeNomad authentication, `isLocalRequest`, +configured/listener Host validation and trusted Origin/Fetch Metadata, including +authenticated host requests without browser headers. The ingress gate rejects +this complete prefix through `routedPath`, including encoded spellings, before +pairing admission. Paired project usage retains existing metadata summaries. +Administrative request logging redacts the complete target, query and body; +router-level malformed-URL diagnostics use fixed responses before request hooks. +Privacy classification conservatively includes encoded reserved separators and +nested encodings, with bounded decoding work. Routing authority uses its own +`routedPath` contract; non-routable administrative spellings receive the same +privacy protection. Ordinary valid routes retain their Fastify error semantics. + +Execution-server metadata at `server.opencodeServers` is reserved for the internal +SettingsService registry. Both generic config PATCH routes apply the same +patch/result protection to host and paired-device callers, including encoded +routes and conditional patch modes. Refused direct writes, ancestor deletion or +replacement and mixed patches leave persistence and events unchanged. Existing +config reads/events return whitelisted metadata summaries. Explicit OpenCode +credentials persist only in the private backend `opencode-server-pairings.json` +(0600), scoped by profile/config, server ID and normalized origin; static summaries conservatively report +`hasCredentials: false`, `needsCredentials: true`, while the owning service supplies +live credential presence through `SettingsService.getOpenCodeServerSummaries()`. +Saved name/URL and the private token or password survive restart. HTTP 401, +expiry, origin replacement and removal clear the secret. Connection +lifecycle integration aborts/fences captured old transports on rotation, +deletion, disconnect and shutdown, including pending body preparation and returned streams. +Registry changes clear credentials before URL retargeting, deletion or ID reuse; +manager shutdown disposes the live owner. Host-only addition/removal use the +administrative prefix; paired devices browse/open registered projects through +the host backend. Explicit-source SSE follows +admitted connection-owner membership. +Schema preprocessing safely discards recognized development +`credentialMode`/`credentialRef` fields; SettingsService normalizes valid metadata. + - `remote-surface.test.ts` drives the real `createHttpServer` through the ingress. It covers unpaired access, pairing, `Origin`/`Host` checks, host-only paths including encoded ones, loopback privileges, spoofed headers, diff --git a/dev-docs/SESSION_ENVIRONMENT.md b/dev-docs/SESSION_ENVIRONMENT.md index 88c10bdde9..959724c96f 100644 --- a/dev-docs/SESSION_ENVIRONMENT.md +++ b/dev-docs/SESSION_ENVIRONMENT.md @@ -1,10 +1,25 @@ # Profile environment at send time -The profile's `server.environmentVariables` apply on each conversation's next +For the shared local service, the profile's `server.environmentVariables` apply on each conversation's next send through CodeNomad (prompt, command, shell; Electron, Tauri and web share the server path), including resumed conversations and later-prompted forks: the server awaits `session.environment({ sessionID, variables })` before forwarding. +Explicit-server workspaces use their target's native environment. The closed E1 +proxy (`server/explicit-proxy.ts`) admits prompt, command and session-shell sends +on one captured current connection, including queued/restored payloads and sends +to resumed forks. It skips profile/environment reads, execution-host snapshots, +Git instructions and provider-account selection/activation. Direct environment +writes are refused by the `sessionEnvironment` capability. Background Shells and +PTY management have separate deferred capabilities. + +The renderer's named placement instruction branches on the explicit binding before +awaiting native writes. Explicit context names OpenCode as the execution boundary, +its native environment and exact Location scope, with the qualified integration +limits. Local repository/worktree-parent context stays on local submissions; voice +context remains an independent named entry. Instruction setup retains the action's +captured authority before and after each write. + ## Implementation - Both writes use the connection acquired after ownership and worktree-fence @@ -112,4 +127,6 @@ installation path. It never calls a provider or touches an existing conversation ## Agent conventions -- Profile environment variables are applied server-side before each native session prompt, custom command or session shell request, after ownership and worktree-mutation admission. Build a complete execution-host snapshot with `workspaces/session-environment.ts`; never send the profile environment through the browser or skip the per-send write using a cache. Reads and settings edits must never mutate native sessions. Keep native environment failures fail-closed and redact SDK request bodies. +- Advanced preferences labels the environment editor as a local CodeNomad backend control. An explicit or unresolved project scope first offers a deliberate local-management action; mounting and retained editor callbacks are fenced to that accepted target. The other shared Advanced preferences remain usable. Editing this local profile applies to subsequent sends on the shared local service; explicit-server sends use their native environment. + +- For local-service workspaces, profile environment variables are applied server-side before each native session prompt, custom command or session shell request, after ownership and worktree-mutation admission. Build a complete execution-host snapshot with `workspaces/session-environment.ts`; never send the profile environment through the browser or skip the local per-send write using a cache. Explicit workspaces retain their native environment through the separate E1 admission path. Reads and settings edits must never mutate native sessions. Keep native environment failures fail-closed and redact SDK request bodies. diff --git a/dev-docs/SESSION_HISTORY_NAVIGATION.md b/dev-docs/SESSION_HISTORY_NAVIGATION.md index 5866e50cf9..6c0dca9232 100644 --- a/dev-docs/SESSION_HISTORY_NAVIGATION.md +++ b/dev-docs/SESSION_HISTORY_NAVIGATION.md @@ -55,6 +55,69 @@ challenge as history queries. Never expose generic RPC or SQL access through the ## UI navigation +### Internal explicit-server transcript pages + +Explicit projects open through the home/launcher Remotes disclosure. Their +reader uses one native `message.list` page of at most 200 messages per demand. +Latest starts descending, oldest ascending; continuations send the opaque cursor +without `order`. `cursor.next` continues in the originating order and +`cursor.previous` returns in the opposite traversal direction while retaining that +order. The in-memory window retains that order and its captured instance/client, +binding, native-data generation and connection-capability generation authority. +Backend cursor validation accepts the qualified `{ id, order, direction }` native +shape; unknown shapes and CodeNomad window tokens fail before upstream access. + +Selected transcript pages have foreground priority. Other transcript-page reads +share the two-slot secondary budget and promote with selection. Cancellation and +authority checks fence queued dispatch and publication. Failed pages keep the +resident passage and reading position. An empty older boundary probe retires only +its older cursor; empty newer/reload probes keep the passage and offer retry or +latest. Native cursors can name an empty boundary, so a returned token keeps the +window conservatively incomplete. The explicit latest action selects the live tail. + +Same-intent consumers join only a read whose instance authority, internal load +signal/epoch and source window remain current. Resident navigation supersedes that +read immediately. A fresh demand starts independently while the cancelled read +finishes. Native empty replies are classified before adding live rows; a latest +empty reply with residents retains both passage and saved reading position. The +row snapshot taken before HTTP also covers any dependent model lookup: final +normalization/publication includes the live rows admitted during that await. + +Native paging uses one polite feedback region for loading and errors, outside +virtualized rows. An unavailable anchor offers latest-page recovery. A disappearing recovery control returns focus +to the transcript only while its view, request and binding remain current and no +other focus target has taken ownership. Local navigation retains its own controls. +Technical cleanup retains its direct-handler/store guards. Explicit rows keep receipt +readers unmounted and their cache lane inactive. Native request coverage remains live-only. + +The timeline and user-message shortcuts cover resident messages. Outline scans, +remote excerpts, full-text queries and pruning mount a localized explanation or +refuse in their direct handlers before reads. A nonresident anchor, including a +cold restoration, retains its saved position and offers an explicit latest-page +action. Resident navigation supersedes pending page loads. Around seeking stays +with the qualified local enriched-window reader. An all-hidden undo page returns +a visible limitation after its single native read; the saved position remains. + +`session-native-history.test.ts` exercises stores/reducers and multiserver request +ownership; `tests/browser/native-history.test.ts` exercises the real Solid +transcript, restoration, search shortcut and resident timeline. The owned-runtime +`scripts/test-opencode-message-pages-native.mjs ` imports synthetic +native messages, checks both orders and previous/next continuations against the +backend decoder, and asserts zero provider calls. Browser, native Windows runtime +and desktop-host qualification are separate scopes. + +Reflow checks cover 320 CSS pixels, including a compact RTL reason at DPR 2 with +the `session-center-column` context. The CSS-zoom check measures notice wrapping; +a reason-window overflow under CSS zoom remains a separate observed defect. +Native 200% page zoom awaits dedicated host qualification. + +Session-inventory pagination uses native opaque cursors independently of transcript +windows. Explicit bindings consume only `cursor.next`, on demand, and send only +`{ cursor }` for continuation. The renderer preserves tokens unchanged. Backend +authorization decodes the qualified native scope and requires the exact opened +directory. Unknown cursor formats fail closed. The isolated inventory qualification +checks daemon-issued continuations against that decoder with synthetic sessions. + `history-window.ts` translates this contract into explicitly namespaced CodeNomad window cursors. These are never forwarded to native `message.list`. Native page cursors are also supported. A truncated newer-page path switches to a diff --git a/dev-docs/SESSION_HISTORY_QUERIES.md b/dev-docs/SESSION_HISTORY_QUERIES.md index 70635084e8..72f851bac5 100644 --- a/dev-docs/SESSION_HISTORY_QUERIES.md +++ b/dev-docs/SESSION_HISTORY_QUERIES.md @@ -2,6 +2,21 @@ ## Entry points +Sidebar title search uses native `session.list`, independently of these body-query +routes. For an explicit binding it reads one page in the exact native Location; +`cursor.next` marks the result incomplete and the sidebar invites query refinement. +It performs no project/worktree discovery or exhaustive cursor traversal. Enriched +history queries remain governed by `historyEnrichment` capability admission. + +The internal explicit-server transcript offers a localized explanation when its +search shortcut opens. Native sidebar title search stays available; text-body +search, ranked queries, cross-session previews, structural outlines and technical +cleanup require the shared local enriched reader. Direct query, preview and +pruning handlers enforce this scope before native/RPC reads. Explicit timeline +navigation covers resident rows and native pages only +([SESSION_HISTORY_NAVIGATION.md](SESSION_HISTORY_NAVIGATION.md)). Projects open +through the shared Remotes disclosure on the home page and launcher. + The non-modal transcript search window (Ctrl/Cmd+F or the header toggle) can query the entire session or workspace. Conversation scope uses a literal phrase and chronological result pages. Workspace scope sends one debounced ranked request diff --git a/dev-docs/SESSION_PRUNING_RPC.md b/dev-docs/SESSION_PRUNING_RPC.md index 716a6510d7..4903efd608 100644 --- a/dev-docs/SESSION_PRUNING_RPC.md +++ b/dev-docs/SESSION_PRUNING_RPC.md @@ -256,4 +256,5 @@ An optional third argument tests an independently installed plugin package direc ## Agent conventions +- Workspace brokers admit `historyEnrichment` for history, ranked search, navigation and goal reads, `sessionPruning` for preview and deletion, and `integratedImages` plus `design` for Images conversations and Design gallery operations. Explicit connections receive a structured capability refusal before client acquisition, plugin readiness, local inventory or Git exclusion access. History scope helpers admit their capability before enumerating validated local worktrees or checking local ownership. Images creation checks Design admission again before appending `info/exclude`. - Session pruning is a narrow V2 plugin/RPC exception under `packages/server/src/opencode/session-pruning/`. Bundle it with the shared server for both desktop hosts and provision through normal native plugin discovery. RPC registrations follow backend presence; clean shutdown removes that backend's lease and crashes expire. Loading never deletes content. Deletion occurs only on an explicit pruning request, never behind an enable-write switch or version gate. Keep generic RPC proxy access closed. Writes validate actual storage, a fresh daemon-storage identity challenge and the native durable execution claim inside a synchronous SQLite transaction. Run isolated native concurrency/payload and client-cache regressions; tests must never target the shared daemon or a user's database. diff --git a/dev-docs/SESSION_RECOVERY.md b/dev-docs/SESSION_RECOVERY.md index ff5fdc42ab..29b7758424 100644 --- a/dev-docs/SESSION_RECOVERY.md +++ b/dev-docs/SESSION_RECOVERY.md @@ -2,6 +2,54 @@ ## Contract +Restored workspace state is keyed by execution server and directory. A missing +server ID selects `local-shared`; an explicit unknown ID retains its own saved +data. Seeding into a live occurrence checks that durable identity. Asynchronous +hydration additionally captures the client and native data generation and checks +the caller's removal/binding fence before publication. Replaced sources and closed +occurrences leave the preserved snapshot available for an authorized reopening. + +Explicit occurrences absent from the backend reopen on their saved server and +directory. Their saved drafts, attachments, catalogs and selected tab remain in the +window graph across capture/reload. Recovery uses the existing capability guards +for pending requests and worktree inventories. The backend connection owner reuses +the profile's privately persisted pairing token or password across restarts. + +Pending request display and reply admission have separate lifetimes. Known drafts +remain mounted through connection gaps; explicit live-only projects retain unknown +coverage after disconnect and backend restoration, including empty local queues. +Current live events restore their exact request's response admission. A held Form +also supports an explicit source-editor check of its native state; pending state +with matching editor fields admits only that captured Form, while terminal and +indeterminate states retain drafts with response actions blocked. One check uses +the shared secondary budget, a ten-second total deadline and four-MiB native +responses. Newer events and source/transport/placement retirement fence its result. +Placement retirement follows every accepted publication, so a move away and back +retains the retired result and reply admission until a new valid check or current +Form event. Matching initial hydration and same-placement metadata keep the owner. +The Form editor composes its check result and earlier uncertain reply into one +polite region; a pending read retains the earlier attempt's uncertainty. Its check +control keeps source keyboard focus while guarded and after pending completion. +Permissions await a current live event. Overall coverage remains unknown. Opening +a conversation reads its supported conversation state while leaving pending +discovery inactive. The dock's source details retain the server, stable ID and +opaque native directory. Current live candidates retain the captured connection and status boundary +while compatible metadata arrives, independently of HTTP/status publication order. +Matching metadata qualifies only those held candidates; older queues stay stale. +Backend transport, client, native-data, binding and session placement retain their +own fences. See [Native interruptions](NATIVE_INTERRUPTION_UX.md). +Capability snapshots also retain their backend-transport publication owner. A +fresh matching snapshot can qualify a current event after backend restoration, +including a reset connection counter; prior-transport display values stay stale. + +Explicit catalog seeding retains only rows whose native Location exactly matches +the occurrence binding. Targeted hydration rereads requested native identities, +checks Location and current request authority, and follows at most 200 ancestor +IDs. A missing or foreign ancestor leaves the in-directory child as a display root; +selection restoration uses that same truncated-chain projection while preserving +native parent metadata. Inventory pages arrive on demand, and only a qualified +terminal exact inventory reconciles absent rows with concurrent-update fences. + `scripts/test-missions-native.mjs` also runs this reconciliation against a private native session: `succeeded` clears a saved working marker; a queued `resume:false` synthetic keeps the historical outcome and does not resolve pending admission; @@ -46,6 +94,16 @@ when newer SSE/local authority supersedes the captured baseline. Deletion, instance/client-generation and abort fences apply. Recovery never prompts, interrupts, updates a session or replays anything automatically. +Metadata merges share inventory request ordering and retain a weakly held HTTP +row baseline through native/local edits and pending/status projections. Fields +from an earlier HTTP snapshot can be refreshed by a current targeted read; +concurrent metadata changes retain precedence field by field. Runtime merges +continue using the row captured before the read for their authority group, and +runtime-only reads retain the metadata snapshot's provenance. +Transcript-derived agent/model fallback and partial native creation updates inherit +the held row's baseline through `withSession`; native changes keep their field-level +precedence while untouched fields remain refreshable from that HTTP snapshot. + ## Display acknowledgement `session-interruption-seen.ts` owns per-window, per-project-tab acknowledgement diff --git a/dev-docs/SETTINGS.md b/dev-docs/SETTINGS.md index 9b7055d0a0..bcbd70e195 100644 --- a/dev-docs/SETTINGS.md +++ b/dev-docs/SETTINGS.md @@ -8,14 +8,39 @@ Settings rows and actions, the native Preferences window and its project context - General offers `autoExpandActiveSubsessions` (default true): a new working/compacting/input chevron state opens visible branches belonging to the selected conversation, including its descendants at every depth (`dev-docs/UI_SHELL.md`). Disabling it leaves activity indicators and explicit navigation available; the preference is stored with the shared UI settings. +- The internal attachment reader uses the private native-parent transport, workspace/connection reservations and the scoped browser-participant owner. Its memory-only receipts qualify captured metadata freshness after publication owners have drained. Manifest reads are capped at 1 MiB before excess bytes are retained; private results have an 8-MiB allowance plus bounded protocol overhead before framing/JSON parsing. Read and current each receive five seconds, with monotonic expiry checked at settlement. Browser declarations contribute positive metadata through an authenticated, revocable stream capability. Publication rejects both raw query delimiters (`?` and `;`), including empty queries, before body parsing or capability admission. Full coverage stays unknown pending native live pre-mutation fencing and exhaustive project-use admission. The public Remotes disclosure's host removal closes known tabs, disconnects and forgets the server independently of these observations. + +- Administrative GET projects the connection owner's private reservation state with the captured slot origin matched to current validated metadata and the displayed summary origin. An origin mismatch projects `unknown` while retaining the actual reservation count and captured connection lifetime. Credential presence remains origin-qualified. Lifecycle assertions belong to real acquisition/dispatch; metadata projection uses pure observations of slots, signals and local existing-connection state. + +- Backend execution-server administration uses `GET /api/opencode-servers` and `POST /api/opencode-servers/probe`. Authentication, loopback/non-ingress peer identity, a configured/listener Host and trusted Origin/Fetch Metadata admit these routes before body parsing or native work. Native Electron/Tauri pages use their backend origin; authenticated host requests can omit browser headers. GET projects validated local-first metadata, live credential-presence booleans and the connection owner's current state (`connected`, `connecting`, `admitted_offline`, `disconnected`, `unknown`), with four explicit and one reserved local target. Reads use existing owners and authoritative app configuration. Probe accepts an unregistered `{ origin, credentials? }` candidate, retains credentials only during its operation and returns observed numeric release metadata or unavailable, negotiated feature states, `checkedAt` and fixed category/phase diagnostics. Administrative responses use `no-store`; diagnostics and request logs retain only fixed categories and redact complete bodies, paths and queries. The Remotes disclosure uses host-only `POST /api/opencode-servers/add` and `DELETE /api/opencode-servers/:id` for pairing and removal. + +- Known-Form verification keeps its check control mounted and focusable during the read and after pending verification; `aria-disabled` accompanies a real action guard and the source status description. The Form editor composes verification with retained uncertainty from an earlier reply in one polite region. Pending native state leaves that earlier attempt uncertain; ordinary errors keep their alert. Source focus moved elsewhere stays with its new owner. Accepted placement transitions retire both in-flight checks and granted reply authority irreversibly, while same-placement metadata preserves them. + +- Explicit live-only interruption coverage appears in the dock's accessible source disclosure: metadata-only server label plus stable ID (or ID alone), direction-isolated native directory and live-only limitation. Known stale drafts remain editable; response actions require a current correlated live request and matching capability snapshot, or an explicit bounded status check of that known Form with matching editor fields. A check preserves unknown project coverage and leaves stale permissions on their live-event gate. Terminal/indeterminate checks retain drafts, inert response controls and one polite source status; retries require another explicit gesture. Uncertain/superseded replies use one polite source-editor status through structured action identity; ordinary failures keep their alert treatment. + +- `SettingsScreen` separates the accepted requested server from its resolved project context. Shared CodeNomad preferences stay usable while an unresolved, ambiguous, deleted or unknown project keeps native readers inactive. Qualified explicit catalogues read only native providers/models (and agents in Mission profile choices) on the captured project/Location; account, integration, Stats owner/cache/aggregation and depth readers mount only with local execution-settings admission. Capability changes and matching stream status revoke the context before inventory refresh; accepted request, binding and capability snapshot fence publication and retained handlers. Event-source epochs and service capability generations have independent owners. Preferences gives the event dispatcher its accepted request's server binding and releases deferred handshakes when that request changes, keeping event provenance independent of main-window hydration. The secondary renderer's setup observer waits for accepted local context. Keep unavailable sections selectable with persistent reasons and the selected server/folder in escaped, direction-isolated text. +- `LocalBackendSettings` identifies HOME files, profile environment and shared-service installation/binary maintenance as local backend controls. Explicit or unresolved project scopes require its deliberate local action before mounting those readers; the grant and callbacks belong to the exact accepted target. Shared Advanced behavior controls and Mission defaults remain available separately. Local catalogue/authentication flows retain existing credential integrations; explicit catalogue rendering mounts no authentication/account component. Read-only target selection and public server management/opening are owned by their separate delivery slices. +- The deliberate local action focuses its newly mounted, labelled control group; the next Tab enters its controls. Deferred focus checks the captured target's live grant and connected element. Initial mounting and external target changes preserve the window's focus ownership. +- `tests/browser/preferences-execution-scope.test.ts` measures Hebrew RTL long-target reflow in Chromium at 800×1200 CSS pixels and 400×600 CSS pixels with DPR 2 (the layout/raster equivalent of a 200% full-page zoom on that surface). Assertions compare target/reason/action rectangles with the actual visual viewport in CSS coordinates, exercise keyboard Tab/Enter and touch-enabled pointer dispatch, and save viewport captures and metrics under `.tmp/scr-1236/`. Native Electron/Tauri zoom, physical touch, screen-reader output and contrast require their own qualification. + +- Preferences opened-folder constraints reject supplied empty, NUL-containing, oversized or wrongly typed paths at request admission; optional absent/null paths retain legacy absence. The URL fallback preserves a supplied path for validation. Lifecycle invalidation shares the resolver's opened-folder predicate and revokes context synchronously when a ready occurrence changes that folder, before its metadata refresh settles. + +- Execution-backed settings admit the workspace's `executionSettings` capability before connection acquisition or local configuration/credential discovery. The shared plugin context covers activation, sources, image, web-search and native subagent-depth document reads/writes; image settings, subagent-depth settings and integrations also admit before their own acquisition. Provider account GET/PUT and service Stats (owner, cache and aggregation) share this local-only boundary. Explicit projects receive structured capability refusals; native chat catalogues retain their own admission. +- Three finer capabilities are also served by explicit servers. `plugins` admits plugin-inventory reads (`PluginControls.read`, integrations, MCP connect/disconnect through the explicit proxy); an explicit snapshot comes from native `config.get` + `plugin.list` with no write targets, so its switches are read-only, and every document read/write (activation, sources, images, web search, depth) keeps `executionSettings`. `providerUsage` admits the Usage route; an explicit project reads only native `/api/experimental/usage/limits` (OpenCode Go) and `session.stats` (Zen free estimate), never `credential.list`, host Claude Code files or provider APIs. `yolo` admits auto-accept (`dev-docs/NATIVE_INTERRUPTION_UX.md`). The UI-only `pluginWrite` feature hides plugin add/remove/update for explicit projects. +- Config files and filesystem discovery routes are explicitly host-only. Strict schemas reject `serverId`, `workspaceId` and binding selectors before filesystem access; Config files retains its fixed host allowlist. Project operations require their workspace identity instead of deriving authority from a path. + +- Static execution-server config summaries conservatively report `hasCredentials: false`, `needsCredentials: true`; `SettingsService.getOpenCodeServerSummaries()` supplies the credential owner's live status. Schema preprocessing safely discards recognized development `credentialMode`/`credentialRef` fields and SettingsService normalizes valid metadata. The private per-instance credential Map is keyed by profile/config scope, server ID and origin; async mutations change memory synchronously, reads invalidate missing-server/different-origin entries, and clearing works after metadata removal. Registry changes clear credentials before URL retargeting, deletion or ID reuse; manager shutdown disposes the owner. + +- `SettingsService.getOpenCodeServerRegistry()` is the writer for metadata at `config.server.opencodeServers`. Both generic config PATCH routes reject direct writes (including identical values), deletion and ancestor replacement that removes this subtree, before persistence/publication, for every caller. Ordinary settings patches preserve the profiles. The registry validates profile shapes and unique IDs; public config responses and owner/full-document events expose whitelisted metadata summaries. The backend persists pairing tokens and manual passwords in `opencode-server-pairings.json` (0600), scoped by profile/config, server ID and normalized origin. Restart reuses these secrets; expiry, HTTP 401, origin replacement and removal erase them. Live credential presence comes from the owning service. The shared connection owner aborts/fences captured old transports on rotation, deletion, disconnect and shutdown, including pending body preparation and returned streams. The home/launcher Remotes disclosure supplies host-only addition/removal and shared browsing/opening of registered servers. An absent registry implies the shared local profile without writing a migration. - Settings → Providers separates Models, Web search and Images into three shared `.settings-disclosure` groups (no icons): Models starts open, Web search and Images folded, and a folded group mounts nothing, so its connection metadata, configuration contract and image-model catalog are read only once opened. Models and Web search each start with a provider selector, Connect action and configured-provider list; Web search then shows its global default and project override. Images (`opencode/image-settings.ts`, `settings/image-settings-card.tsx`, `styles/components/image-settings.css`) edits the Global document's `experimental.image_generate` and `experimental.media_blob`. OpenCode reads `image_generate` per field from the highest-priority document that sets it (unset means on, with the automatic model; only `false` turns the image tool off), but `media_blob` (like `subagent_depth`) from the whole `experimental` object of the highest-priority document that has one, so writing a project block would hide inherited experimental settings. The document that decides each value is read from the native configuration entries and reported under its control when it is not the Global one. When the selected Location's own project document (the project write target) decides `media_blob` through its existing `experimental` object, the snapshot names it under `mediaStorage.project` instead, the box shows the effective value and saving also writes `media_blob` there; the edit is refused if that object has disappeared, because creating one would hide inherited settings. The Missions depth editor's Inherit removes a project object left holding only that `media_blob` when it equals the Global one (`dev-docs/MISSIONS.md`); Off is written as `false`, because removing the key would expose a lower-priority document that enables it. When the fresh Global write target has no `experimental` object while a lower-priority document has one, creating it would hide that whole object (subagent depth, todos) from every Location without its own, even when the selected Location overrides it, so the group is read-only and the backend refuses the write; never copy the inherited values into the Global document instead. Each control appears only when the connected daemon's `Config.InfoEncoded` declares its key, because the native `experimental` object rejects unknown keys; never write either key without that capability. Image models come from native `GET /api/model?types=image` for the selected Location. Reuse provider rows, selectors, inputs and action styles; do not add an API-key disclosure or a separate card design. Search-only integrations stay out of the Models group. Web search configuration lives entirely here. Read connection metadata while this Settings surface is visible, never credential secret values; keep API-key entry explicit and clear drafts on context changes. Use the authorized Global/Project document operations shared with plugin controls and `opencode/native-setting-document.ts` for targeted JSONC edits. Preserve unrelated fields, native discovery roots, WSL atomic writes and conflict/connection/deletion fences. Group/search styling lives in `styles/components/websearch-settings.css`; credentials use native integration methods and remain global. - Stats preferences explicitly aggregate the entire connected OpenCode service via `opencode/service-usage.ts`. Reserve the Usage label for the provider subscription panel. Native project IDs span independent clones, so never label native `session.stats` as physical-folder/Git-family scoped. Keep connection/workspace fences, `tools: "none"` and periods bounded to 366 days; never load transcripts for statistics or imply billing/quota precision. Last snapshots and period choices restore through backend-owned `state.ui.serviceUsage` (eight each/1 MiB, validated service/channel/folder identity), never a Preferences writer to main-window client state or a workspace-UUID cache. Native aggregation must not await optional discovery/cache reads; cached responses cannot replace fresh data. Backend authorized admission order, not completion order or client time, chooses the period across windows; optional publication is bounded and shutdown-fenced. Keep last-known-owner totals explicitly stale through disconnect/errors and revoke them on verified owner/discovery changes. Read while mounted and document-visible; hide cancels queued/trailing demand, activation revalidates once and terminal hints use the shared activity cooldown. Never treat document visibility as native minimize/occlusion detection or equate blur with hidden. See `dev-docs/CACHE_REFRESH_CONVENTIONS.md` for the remaining native scope. Styles live in `styles/components/usage-dashboard.css`. - Settings rows keep only a title unless a caption is essential; secondary explanations go behind `components/settings/settings-info-tip.tsx` (a focusable "i" with a hover/focus tooltip that a tap toggles on touch screens, a span so it never becomes a row label's control or toggles it), styled in `styles/components/settings-info-tip.css`. An explanation that must end with a link uses `settings-info-link.tsx` instead: the same "i" as a button named by its text, opening a popover named by its `title` (click, Enter or Space; focus moves to the link; Escape or outside interaction closes it). Links to a setting use `openSettingsRow(section, row)` (`stores/settings-screen.ts`) with the row's stable `id` anchor (such as `#opencode-login-start`), never its label, and the link's text is the setting's own title key so it follows any rename; the row (`tabindex="-1"`) calls `useSettingsRowTarget` (`components/settings/settings-row-target.ts`) to claim the target once, focus itself and stay in view while the cards above load, and the embedded Settings dialog skips its own initial focus while the shown section holds the targeted row (`settingsRowPending`); closing Settings drops an unclaimed target. Hosts carry only the section to a native Preferences window, so the row travels as a 15-second same-origin `localStorage` hint that the window adopts for its active section on each request and on `storage` events (`adoptSettingsRowHint`). A link never reads or changes the linked setting. Behavior settings opt in with `infoKey` instead of `subtitleKey`. Folded settings groups use the one `.settings-disclosure` (`styles/components/settings-disclosure.css`; a summary may hold an inline heading that keeps the summary's look): Missions gathers every agent/model choice under "Agents and models" with the current request in its summary, and Advanced ends with the environment-variable editor folded under a single title. - Settings update/install actions (OpenCode and Info), OpenCode's post-update service restart, and Remote Control start/pairing-link actions use the shared `.selector-button-primary` accent treatment. The shared `OpenCodeSetupPanel` keeps those same primary actions in startup recovery. Remote Control's header refresh is an icon-only `.window-icon-button`, retaining its localized accessible name, tooltip, disabled state and loading spinner. - The native Preferences window never owns client state. Its General startup card (`settings/opener-startup-state-settings-card.tsx`) targets the exact local window that opened Preferences: the host records that opener and an epoch (Electron `PreferencesWindowRegistry`, Tauri `PreferencesWindow`), forwards only the fixed commands in `lib/native/startup-state-command.ts` to that renderer, which runs them through its own `stores/client-state` transitions. Mutations carry the displayed epoch and degrade to a read after the opener changes. Startup state is per window: when the opener is unknown (Preferences restored at launch) or closed, the host adopts the most recently used local window as the opener (`startupStateTargetId` + `adoptOpener` / `startup_state_target` + `set_opener`), rotating the epoch so a change prepared for another window is only a read. The card re-reads a few times while the adopted window starts and stays disabled only when no local window can answer. - The native Preferences window shows no session, so it never reacts to session events: `stores/sessions.ts` wires the session event handlers (errors, TUI toasts, permissions, session and worktree updates) only outside it. A session alert, toast or notice therefore appears in the windows showing sessions and is acknowledged once there (`tests/browser/preferences-window.test.ts`). -- Native Preferences resolves its project context through `settings/preferences-project-context.ts` before Providers, Missions or Stats read project data. Backend workspace IDs are ephemeral: use the exact requested record while it exists; otherwise bind only one unambiguous exact-folder match from the backend's metadata-only inventory. Requests persist the opened backend-host folder as `workspacePath`, separate from the selected native `location.directory` (WSL/worktrees); keep the native directory for requests and drop any stale native workspace selector when rebinding. Requests without the backend folder match only their exact directory, never through guessed WSL translations or ancestors. A starting, missing or ambiguous project stays inactive. Read only on section demand, matching workspace lifecycle events or reconnect; never hydrate other workspaces, discover worktrees, create projects or poll. Record all deletion tombstones before filtering by the current binding so late inventory responses cannot publish deleted candidates, and revalidate when deletion resolves an ambiguity. Invalidation and newer native requests fence late reads, explicitly deleted occurrences never turn into sibling tabs, and rebinding persists through the existing Preferences request queue without resetting the section or newer scrolling. The shared renderer and request contract cover both Electron and Tauri; startup regressions live in `tests/browser/preferences-startup.test.ts`. +- Native Preferences resolves its project context through `settings/preferences-project-context.ts` before Providers, Missions or Stats read project data. The optional request `serverId` qualifies every context, queue and asynchronous fence; absence selects `local-shared`, malformed explicit IDs are rejected and unknown IDs remain repairable unavailable targets. Both hosts validate and retain this field through open/reuse/get/accept and the strict client-state envelope; legacy requests retain serialized absence. The fallback URL reader accepts one `preferencesServerId` and rejects duplicate context selectors. Backend workspace IDs are ephemeral: accept an exact record only on the requested server and, when supplied, opened folder; otherwise bind only one unambiguous same-server folder match from the metadata-only inventory. Remote directories retain their exact spelling; local folders use `projectIdentity` normalization. Requests persist the opened folder as `workspacePath`, separate from the selected native `location.directory` (WSL/worktrees); keep the native directory for requests and drop any stale native workspace selector when rebinding. With an absent opened folder, an existing same-server occurrence keeps its selected Location; rebinding matches only that exact directory, never guessed translations or ancestors. Resolved context exposes read-only binding and capability metadata to settings consumers; execution-backed settings admission remains in the backend capability guards. A starting, missing or ambiguous project stays inactive. Read only on section demand, matching workspace lifecycle events or reconnect; never hydrate other workspaces, discover worktrees, create projects or poll. Record all deletion tombstones before filtering by the current binding so late inventory responses cannot publish deleted candidates, and revalidate when deletion resolves an ambiguity. Invalidation and newer native requests fence late reads, explicitly deleted occurrences never turn into sibling tabs, and rebinding persists through the existing Preferences request queue before publishing the execution context, preserving section and newer scrolling. The shared renderer and request contract cover both Electron and Tauri; regressions live in `tests/browser/preferences-startup.test.ts` and `preferences-window.test.ts`. - Settings → Info's Support CodeNomad card, between Updates and Diagnostics, holds one `.selector-button-secondary` action that opens `helpUrl(locale, "sponsor")` through `openExternalUrl`, like the `open-sponsor` palette command and the native Help menu item; a failed opening shows the localized `commands.openSponsor.failed` alert in the card and is never replayed. Funding channels live only on the help site (`docs/help/funding.json`); never put payment links or amounts in the app. - Settings → Info's Report a bug opens the `bug_report.yml` issue form with its text fields prefilled by id (`BUG_REPORT_FIELDS` in `lib/bug-report.ts`). When the template changes, keep those ids and their input/textarea types in sync: `lib/bug-report.test.ts` checks the repository's template. The section warms a bounded read of the form published on the default branch; the click never waits for it (WebKit drops user activation after about 1 s), using the settled assessment or else the form while a background read retries. Only a proven incompatible form (missing, unparsable, prefilled field removed or retyped) falls back to a blank issue carrying the same Markdown report; an unreachable read keeps the form. Never prefill listeners, addresses, paths, credentials or conversation data. - Notification icon badges mirror the existing per-window bell/history unread count, never session status or native OS notification delivery. The browser favicon uses a dot; native Electron/Tauri hosts aggregate live primary-window counts and clear contributions on reload/close, keeping preferences and preview guests outside the badge authority. Keep UI projection in `lib/notification-icon-badge.ts` and host dispatch in `lib/native/notification-badge.ts`; do not add discovery scans or polling. +- Compaction notice claims use execution-server identity plus native durable position (or session/event ID), shared across project occurrences in each session window. Open bubbles replace only the same server/session's notice and expire through the existing handle lifetime; recent claims retain their bounded replay window. Notification category routing applies before retaining a displayed handle. - Notifications have one routing table (`lib/notification-routing.ts`): every `showToastNotification` declares a category, and Settings → Notifications chooses per category On screen / History / System (`components/settings/notification-routing-table.tsx`, `styles/components/notification-routing.css`). The history, and therefore the icon badges, holds only what is routed there; errors always reach the screen and the history; `transient` live feedback (progress, retry countdowns, "up to date") stays on screen only. The routing table is the only system-notification control: checking a System box requests permission, and saved `osNotificationsEnabled`, `notifyOnNeedsInput` and `notifyOnIdle` preferences only seed the routing until it is first saved. The bell (tab bar, or title bar in the macOS desktop app) is the history, independent of system notifications. System delivery is held back only while the window has focus (visible and `document.hasFocus()`), unless **Notify when the app is focused** (`osNotificationsAllowWhenVisible`) is on; a window left open behind another application or on another screen still notifies (`tests/browser/system-notification-focus.test.ts`). Classify new notifications by what the user would want to find later, not by their source file; a warning that must be seen once by default (the incomplete-recovery warning) uses a category that shows a bubble (`projects`), never `needsInput`, whose default is System only. diff --git a/dev-docs/TEXT_DISPLAY_BOUNDS.md b/dev-docs/TEXT_DISPLAY_BOUNDS.md index 829860a28f..73f32b4857 100644 --- a/dev-docs/TEXT_DISPLAY_BOUNDS.md +++ b/dev-docs/TEXT_DISPLAY_BOUNDS.md @@ -19,6 +19,20 @@ Structured tool values (an object input or output) larger than about 10 KB are never serialized for display: they show the explicit "Structured output omitted from rendering" message, without a reveal; copy returns them whole. +Embedded media has its own complete data-URI ceiling of 8 MiB in +`server/src/opencode/embedded-asset.ts`, applied before base64 validation or decoding. +Explicit image display qualifies passive raster MIME types and held native references +through `lib/media-policy.ts`. Image bytes remain excluded from tool text projections +even when display is refused. Encoded-byte limits and decoded image dimensions have +independent meanings; decoded dimensions remain browser-managed. + +The deferred-media route separately caps the **whole decompressed HTTP envelope** +at 16 MiB (`MESSAGE_LIMIT` in `session-media-contract.ts`), including success/error +bodies and unrelated metadata. Chunks are counted before retention or concatenation, +then the official SDK parses only an accepted bounded body. `Content-Length` remains +advisory. The 32 KiB inline deferral threshold controls presentation; the 8 MiB URI +limit controls encoded assets. Pixel dimensions and total decode heap remain separate. + Because prose parsing grows faster than linearly and highlighting costs about 5 µs per character: diff --git a/dev-docs/TRANSCRIPT.md b/dev-docs/TRANSCRIPT.md index 2323c23e88..a9b47c668b 100644 --- a/dev-docs/TRANSCRIPT.md +++ b/dev-docs/TRANSCRIPT.md @@ -2,15 +2,57 @@ Message content visibility and presets, token lines, tool renderers, native session lifecycle signals and transcript re-projection. +Session inventory and restored ancestry use the exact explicit-Location contract in +[PROJECTS.md](PROJECTS.md). Inventory pagination and its opaque native cursors have +their own traversal owner, separate from transcript windows and enriched history +queries ([SESSION_HISTORY_NAVIGATION.md](SESSION_HISTORY_NAVIGATION.md)). +Native move events update held explicit-session placement before projection, so a +moved-out session leaves the displayed exact inventory even while its historical +pages remain unloaded. Cold native-event metadata reads share the inventory's +captured client, binding and native/connection-generation authority; returned +identity and explicit Location are validated before publication or dependent +model/status reconciliation. +Model reconciliation retains that authority through its admission queue and its +dependent metadata read. Cold status/retry continuations follow native lifecycle +order while metadata hydration preserves concurrently published runtime state. +Shared metadata request ordering distinguishes a row published by an earlier +inventory from newer native/local edits, including a rename during cold hydration. + +Internal explicit-server transcript loads use bounded native message pages, with +the window's originating order and captured request authority kept in memory. +Every fetched explicit page merges changed resident native rows through the shared +row-snapshot merge; latest pages also retain new live rows, while historical pages +keep their own membership. Final normalization follows dependent model reads using +the original pre-HTTP snapshot. Native empty replies are checked before live rows +join them. Window commits preserve the current session metadata +provenance through `withSession`. Empty/failed historical probes retain resident +content and anchors. Cold nonresident anchors offer explicit latest-page recovery; +the existing saved position stays intact until that action succeeds. Navigation +and enriched-reader admission are specified in +[SESSION_HISTORY_NAVIGATION.md](SESSION_HISTORY_NAVIGATION.md). + +Explicit transcripts present one polite loading/error region and destination +recovery outside the virtualized header. Technical cleanup retains its capability +guard. Receipt readers stay outside explicit transcript mounts; live-only request +scope is available through the dock's source disclosure. + ## Agent conventions - Partial live projections preserve omitted resident message runs beside their preceding shared row, with leading history before the snapshot and pending optimistic sends at the tail. Shared rows follow the incoming native order. HTTP pages can contain later steps whose events are still in transit; message IDs and wall-clock timestamps remain identity/display data rather than transcript sort keys. +- Deferred-media reads construct a request-local official Promise client around the captured connection's authenticated fetch. `session-media-fetch.ts` bounds each complete decompressed HTTP envelope, including metadata and error bodies, at `MESSAGE_LIMIT` (16 MiB) before SDK text/JSON parsing. Overflow, the 30-second request deadline, socket close and workspace/connection retirement cancel the upstream body and release its reader. Shared embedded-asset validation precedes digest/base64 decoding; explicit serving additionally requires the UI's passive-raster MIME qualification. Native content, exact URI digests, session placement and undo-boundary authority remain separate checks. + +- Native chat mutations capture instance client, binding, native generation and explicit connection generation before queueing or any await. `captureSessionRequestAuthority` additionally retains the selected session's exact Location through instructions, agent/model writes and acknowledgement. Every dependent dispatch and metadata/optimistic publication rechecks that authority; queued work rejects after replacement and uncertain writes stay unreplayed. Native forks validate returned explicit placement before publication. UI continuations retain their initiating view through latest-page reads, queued edits and fork activation. Admission settlement keeps newer session metadata provenance intact through `withSession`. + +- Native cancellation and undo acknowledgements retain separate authority for their local draft continuation. Prefill requires the captured text revision, attachment state and source view; focus restoration separately requires unchanged user focus. Changed drafts remain intact. Known queued payloads offer explicit recovery in their open source composer, including after an uncertain cancellation acknowledgement. Late action errors use source-local feedback after authority or outcome uncertainty, preserving other conversations and external focus. A settled side-question controller releases only its own transient state, independently of permission to publish its response. See [COMPOSER.md](COMPOSER.md). + - The message-content popup and Chat settings share `components/transcript-visibility.ts` and the semantic icons from `components/message-content-icons.ts`; tool presentation metadata lives independently of renderers in `components/tool-call/tool-presentation.ts`. Popup styles live in `styles/components/transcript-filters.css`. Popup rows show a requested state at once and keep it until the save carrying it settles. Each save re-renders the transcript, so a drag sweep (`dev-docs/UI_CONVENTIONS.md`) saves its rows once, on release (`afterSweep`). Saves run in order, each built from the preferences the previous one returned; a batch of rows is sealed as it joins the queue, so a later click never jumps ahead of a preset change nor rides along with a sweep still held. - Transcript presets are Nothing (hides every row, including all tools), Minimal, Balanced and Everything (`TRANSCRIPT_PRESETS`); saved Detailed choices load as Custom with their effective tool column. Chat settings shows the four as buttons; the popup shows the same choice as a native select under its title, where a disabled Custom entry appears only after a manual row change. Escape closes an open list before the popup. Preset names and descriptions are localized in every locale; covered by `tests/browser/transcript-presets.test.ts`. - Status Tokens are independent of message token visibility. A collapsed section uses the non-interactive `renderSummary` slot for one ellipsized session input/output/cost line; expanded content shows session metrics then descendant-inclusive totals as separate wrapping groups. Keep this layout in `styles/panels/status-tokens.css`. - Message token disclosures keep one row in both states: collapsed shows the input/output/cost summary chips on a single ellipsized line; expanded swaps the same row to all six chips beside the chevron, which wrap onto further lines when narrow instead of truncating (expansion exists to read every value). Keep the metric renderer local and chip/row styles in `styles/messaging/message-usage.css`. -- Tool-result images retain native `state.content` and render through the shared `components/tool-call/output-images.tsx` surface, including MCP and specialized tools. Keep image bytes out of text projections (copy/search/speech); image styles live in `styles/messaging/tool-call/images.css`. +- Tool-result files retain native `state.content` and render through the shared `components/tool-call/output-images.tsx` surface, including MCP and specialized tools. Images use the shared image presentation; other files keep a label and an authorized explicit download action. Keep file bytes out of text projections (copy/search/speech); image styles live in `styles/messaging/tool-call/images.css`. +- Explicit content uses `lib/media-policy.ts` before source assignment or download. Its owner comes from the rendering instance/session through `createContentMediaPolicy`, including each nested tool's own session. Supported raster data URIs use the shared lightweight embedded-asset validator and 8 MiB complete-URI ceiling. Native media references require canonical segments, the current media capability and request authority, and an exact held message/part/content-index/digest match in that session. User file bytes remain native parts; valid non-image embedded files offer download only. Source refusal keeps the native content and the shared localized image-unavailable fallback. +- `lib/markdown-html-policy.ts` filters explicit HTML in an inert template immediately before publication, including raw tool HTML, malformed HTML, Markdown-generated images, local/global cache hits and owner changes. Raw HTML uses the shared tag whitelist; the publication profile additionally preserves generated code actions and passive Shiki/KaTeX geometry/styles. Every image is reauthorized; resource-loading HTML, handlers, source sets and resource-bearing CSS/SVG are removed. Explicit links retain user-initiated HTTP(S)/mailto navigation; host preview conversion and decoration are scoped to local content. Attachment thumbnails, hover previews and downloads use the same policy; async downloads retain source/session authority through publication and failures show locally. - Transcript pages carry large tool images by reference: the UI's native message list reads (`lib/sdk-manager.ts`) and history windows (`fetchHistoryWindow`) send the `x-codenomad-media: deferred` opt-in (`server/src/opencode/session-media-contract.ts`), and the server replaces each tool image data URI over `INLINE_MEDIA_LIMIT` (32 KiB) with a `/api/workspaces//session-media/////` path (`opencode/session-media.ts`). `toolImageSource` resolves that path on the API base, so the lazy `` loads only shown images; `routes/session-media.ts` serves the bytes of the owned session's native message, pinned by the digest and refused at or after an undo boundary, as an immutable sandboxed image. Single-message reads (`session.message.get`: pruning revisions, previews), live events, user attachments and requests without the opt-in stay whole, so revisions hash native content. - Markdown images of local file paths (`C:/…`, `file://`, absolute or relative POSIX paths) cannot load in the renderer. `lib/markdown.ts` renders them as their alt text in a `span.markdown-local-image`, and `components/markdown.tsx` swaps the label for an `` with the source of a completed tool image of the same path already in the session's loaded messages (`lib/markdown-local-images.ts`: the image's file name or its single-image tool's `filePath`; Windows paths compare case-insensitively, a relative path must match one known path's end). Only blocks containing such a label read and track the session's tool parts. Never fetch local paths through a backend route for this; an unmatched path keeps its alt text. - Code Mode reads native `metadata.toolCalls` in `tool-call/renderers/execute-data.ts`; keep call-list styling in `styles/messaging/tool-call/execute.css`, with native image/output ownership in the shared tool shell. diff --git a/dev-docs/UI_SHELL.md b/dev-docs/UI_SHELL.md index a5dd4ef85a..bd392ac858 100644 --- a/dev-docs/UI_SHELL.md +++ b/dev-docs/UI_SHELL.md @@ -4,6 +4,11 @@ Panel toggles, floating drawers, project/right-panel tabs, the session sidebar a ## Agent conventions +- Execution-backed readers use the pure `projectAvailability` decision and `ProjectCapabilityBoundary` before constructing hooks, readers, channels or frames. The decision consumes the source occurrence's binding and current correlated capabilities; explicit E1 policy keeps deferred host integrations closed even when native metadata says available. Known local/legacy occurrences retain their existing behavior. Unavailable project entries stay out of rendering and UI command lists; direct handlers and both command executors recheck admission silently. Source captures fence queued dispatch, dependent reads and publication. +- An admission-driven right-panel fallback preserves the shared saved tab preference; an explicit selection retains the usual persistence. Native data-generation changes retire and recreate admitted local readers through the same captured lifetime. + +- Native file/editor/explorer/terminal actions share `lib/workspace-open.ts`: project-scoped availability reads the instance binding and file capability, and dispatch rechecks the project before entering either native bridge. A call to `canOpenWorkspacePaths()` without an instance is host-global capability detection, used for command registration; every project action supplies its occurrence ID. Hosts independently validate backend authority. Refusals use the translated `commands.openWorkspace.localOnly` message. + - Docked panel resize handles follow the composer's Pointer Events design: capture the pointer on the handle and keep its `.is-resizing` highlight until pointer up/cancel, capture loss or the active handle's cleanup. Scope each handle's cleanup to its own side so resizing continues when the opposite panel closes. Keep event handlers local in `useDrawerResize.ts` and styles in `styles/panels/session-layout.css`; validate both sides, RTL and touch with `tests/browser/panel-resize.test.ts`. - Session rows keep actions inline until their measured title, badges, and controls no longer fit. Keep responsive action styles in `styles/components/session-row-actions.css`; hidden inline controls remain measurable but inert, and an open overflow menu stays mounted until dismissal. @@ -12,10 +17,11 @@ Panel toggles, floating drawers, project/right-panel tabs, the session sidebar a - Conversation header actions (inline and in their overflow menu) offer the web preview on every platform, with Full screen added on mobile. Remote Control clients hide the preview entry while their host keeps web previews off: `/api/meta` then reports `previewsUnavailable` (`previewsUnavailable()` in `lib/server-meta.ts`). Validate with `tests/browser/header-windows.test.ts`. - Session hierarchy geometry lives in `styles/components/session-tree.css`; connector axes follow the parent expander at every depth, including selection mode, RTL and touch layouts. - Session search/filter mode uses flat per-session results with an optional subsession switch; filters, sorting, worktree badges and selection use each result's own identity. Normal browsing retains the session hierarchy. +- Explicit session inventory loads another native page when the viewport reaches its end. Three consecutive pages adding no visible row wait for another user scroll; failures wait for Retry, which resumes the failed cursor while its traversal authority is current. Initial-page failures and retired traversals refresh the first page. When a focused Retry control disappears, focus stays in the session viewport. Restoration checks current request authority, visibility, component lifetime and intervening user focus/pointer interaction; a person who moved elsewhere keeps their focus. Page announcements are screen-reader-only, and title-search demand clears its prior result. - Project and right-panel tabs share `components/tab-scroll.tsx` and `styles/components/tab-scroll.css`. Keep their native scrollbar above upright content without mirrored transforms, negative border overlaps or permanent compositing hints. Validate shared scrollbar styling and adjoining edges at fractional zoom in the browser and isolated Electron renderer fixtures (`tests/browser/tab-chrome.test.ts`). - The Status tab starts with the shown session's goal line (`components/session/session-goal-line.tsx`, `styles/panels/status-goal.css`) only while that session has a `/goal`: one row above the sections with the status badge (`.session-goal-badge` in `styles/components/badges.css`), the objective truncated with its full text and the reason in its tooltip (the reason is also the row's accessible description), the rounds, one Pause/Resume button that keeps focus as the status flips, and Clear. While a command runs its actions are `aria-disabled` and ignore activation, never `disabled`, so the focused button keeps keyboard focus. Never add it to `CORE_STATUS_SECTION_ITEMS` or the right-panel customization, and never show a hint, empty state or gap without a goal. Contract, commands and freshness: [OPENCODE_COMPATIBILITY.md](OPENCODE_COMPATIBILITY.md) (Session goal). Validate with `tests/browser/session-goal.test.ts`. - Built-in right-panel tabs are constructed directly in `right-panel/core-runtime.tsx` (never add a first-party plugin loader for them); external sandboxed panels keep their independent consent/loading path. -- Integration Status sections are registered by `right-panel/integration-status-module.tsx` under stable `integration:` IDs, in catalog order after Plugins. Saved order and hidden IDs retain absent sections; dragging moves only the source, and Up/Down in customization uses the same ordering for every section. Stable section objects preserve focused DOM across refreshes. Expected-action changes expand once, respecting subsequent user collapse. One attachment owner and one grouped polite live region belong to each Status tab; disappearing focused sections hand focus to the Plugins accordion trigger. Conversation attachment controls and binding labels live exclusively in these sections. +- Integration Status sections are registered by `right-panel/integration-status-module.tsx` under stable `integration:` IDs, in catalog order after Plugins. `plugins` admission precedes context and inventory/status demand; `pluginWrite` precedes attachment/install controller construction and binding demand. Explicit projects retain read-only plugin, application and connection status; the conversation line requires its admitted attachment owner. Saved order and hidden IDs retain absent sections; dragging moves only the source, and Up/Down in customization uses the same ordering for every section. Stable section objects preserve focused DOM across refreshes. Expected-action changes expand once, respecting subsequent user collapse. One attachment owner and one grouped polite live region belong to each admitted Status tab; disappearing focused sections hand focus to the Plugins accordion trigger. Conversation attachment controls and binding labels live exclusively in these sections. - Embedded floating session drawers use `instance/shell/HostedDrawer.tsx` so their SUID modal roots are direct children of the existing geometry host. A Solid Portal wrapper must not become an ARIA-hidden ancestor of visible controls. Preserve SUID's modal stacking, sibling isolation, focus policy, Escape/backdrop handling and scroll restoration; validate with `tests/browser/drawer-accessibility.test.ts` rather than overriding ARIA or disabling modal enforcement. - Floating-panel outside-pointer and Escape dismissal leave ARIA menus, listboxes and dialogs to their own selection/dismissal handlers (`shell/drawer-events.ts`). Their portals are outside the drawer DOM, and closing the drawer on pointerdown destroys a menu before touch pointerup selects its action. Both the shell's capture listener and SUID's Escape policy defer to nested surfaces; focus and isolation stay with SUID. Keep this guard shared in the shell, not in individual menu actions; validate the real session Delete confirmation with `tests/browser/session-delete.test.ts` and Status menus with `tests/browser/integration-attachment.test.ts`. - Each side panel has exactly one open/close control: `instance/shell/ShellPanelToggle.tsx` (`PanelLeft`/`PanelRight`, `.icon-toggle` with `aria-expanded`/`aria-controls`), absolutely placed at the shell's outer header corners (`--space-xs` from the window edge) in `.session-shell-frame`, outside the drawer host so modal sibling isolation never hides it, and above floating drawers. The frame is an isolated stacking context: toggles stay above in-frame drawers but below body-portaled dialogs, scrims and utility windows. Both toggles precede the shell content in tab order and use the fixed View-menu labels (`window.menu.leftPanel`/`rightPanel`) with `aria-expanded`, never an Open/Close label flip. They are strictly fixed: no horizontal or vertical movement between docked, floating and closed states in any layout; the sidebar header, right-panel tab bar (both edges when floating) and the conversation header (`data-{left,right}-toggle-reserve`) reserve their footprint instead. Every header's action row (session list header row, right-panel `.tab-strip-shortcuts`, conversation side groups and status indicators, with or without the title row) and the toggles centre on one shared line, `--panel-header-action-center` in `styles/tokens.css`; never measure per-state offsets. The session list header holds a single action row; never add a keyboard-shortcut footer below the session list. Opening one floating drawer closes the other; the outside-pointer handler ignores the toggles. Styles live in `styles/panels/shell-panel-toggles.css`; validate with `tests/browser/shell-navigation.test.ts`. diff --git a/dev-docs/WORKTREE_SESSION_PLACEMENT.md b/dev-docs/WORKTREE_SESSION_PLACEMENT.md index 7384a36a4b..8461990573 100644 --- a/dev-docs/WORKTREE_SESSION_PLACEMENT.md +++ b/dev-docs/WORKTREE_SESSION_PLACEMENT.md @@ -146,8 +146,10 @@ queued/restored prompts), slash command and session shell command. Existing sessions receive it on their next submission, as do newly created sessions on their first submission. -The entry uses the user's current choice and appends the catalogue's default -creation parent when available. It survives independently of the voice-mode +For the shared local service, the entry uses the user's current choice and appends +the catalogue's default creation parent when available. Explicit-server bindings +receive exact-Location execution context and their deferred integration limits. +Each branch survives independently of the voice-mode entry and is reapplied on every submission, never skipped by a browser-side success cache. A failed write propagates through the action failure path. Other instruction keys and session metadata stay intact. @@ -160,6 +162,26 @@ block the proxy for it. ## Directory spelling +### Internal explicit-server authority + +An explicit workspace binds one exact `{ serverId, directory }` to its occurrence. +Its native client and generation come from that target's connection owner. +Location ownership compares the exact validated directory and rejects workspace +selectors and clients pinned to another target. Each session requires its own +native placement read through the captured connection; a moved session outside +that directory loses authority. Family ancestry, native project IDs, repository +roots, lexical descendants and alias metadata never expand that scope. An +out-of-scope location requires a separate opening. Local worktree discovery and +family-move helpers stay behind the local-workspace boundary. + +`scripts/test-opencode-explicit-location-native.mjs` qualifies the Location and +readable-directory contract on an isolated runtime. It checks absent and +permission-denied folders, directory aliases and native session placement, and +records runtime metadata with its evidence. A readable alias retains its own +Location spelling; repository canonical metadata grants no additional authority. + +### Local directory comparisons + Do not lowercase paths globally (including case-sensitive hosts) or broaden project authority to hide native directory-filter discrepancies. When diagnosing an absent conversation, compare `session.get`, the actual directory-scoped list and the diff --git a/dev-docs/architecture.md b/dev-docs/architecture.md index 1fe6198527..668aae0c5e 100644 --- a/dev-docs/architecture.md +++ b/dev-docs/architecture.md @@ -64,7 +64,18 @@ Yolo state endpoints live at `/workspaces/:id/yolo/sessions/:sessionId`; Yolo no `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 and Yolo 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](OPENCODE_COMPATIBILITY.md), whose Agent conventions also specify relay ordering and ownership fences. +The server holds one `client.event.subscribe()` stream per admitted execution +target, shared by all its project occurrences. `InstanceEventBridge` retains the +local adapter and observes explicit admission from the existing connection owner. +Each source owns its runner, retry, FIFO lanes, placement caches and status, within +the fixed aggregate [budgets](CACHE_REFRESH_CONVENTIONS.md). Records carry server +ID and relay-attempt generation before routing; `/api/events` multiplexes them with +workspace and Yolo events for the browser. Heartbeats use +`POST /api/client-connections/pong`. UI dispatch checks the occurrence binding and +the generation established by a source status before notifying subscribers. The +stream is volatile: reconnect reconciles only available capabilities. Local pending +recovery uses the loaded-only broker; explicit E1 recovery retains unknown/live-only +coverage. See [compatibility](OPENCODE_COMPATIBILITY.md) for routing fences. 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`. @@ -90,6 +101,62 @@ Session Shell and conversation instructions are native features. Session Shell i 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. +### Execution-server metadata foundation + +`SettingsService.getOpenCodeServerRegistry()` owns `server.opencodeServers` in the +current config document. The registry validates discriminated local/explicit +profiles, unique IDs and normalized root origins. Saved metadata includes the +server name and URL. An absent registry implicitly contains `local-shared`, without a +migration write. Public workspace creation uses the shared local service. + +Internal explicit workspace creation uses `workspaces/explicit-workspace.ts` and +the backend-wide connection owner. A per-occurrence lease precedes admission and +native validation; connection generation and occurrence cancellation fence each +asynchronous result and publication. Validation reads native `/api/location` and +`/api/fs/list` through the protected transport, with exact directory comparisons +and bounded response size/time. The lease survives publication and releases on +the last occurrence closure across windows. `WorkspaceDescriptor` exposes the +immutable execution binding and capability snapshot; local binary metadata is +optional for explicit occurrences. Workspace client acquisition is target-bound, +and host filesystem, worktree and environment helpers reject explicit workspaces. +The public workspace POST accepts a registered explicit `serverId` and validates +its directory through that target's native API before publishing the occurrence. + +The internal binding parser preserves `{ serverId, directory }`, defaults a +missing server ID to `local-shared`, and retains unknown IDs for repair. Explicit +directories stay opaque. Connection generations belong to transient capability +snapshots, separately from durable bindings. The closed E1 capability template +marks native contracts unverified, pending recovery live-only and deferred +integrations unavailable. Static config summaries whitelist metadata and conservatively +report `hasCredentials: false`, `needsCredentials: true`; the internal +`SettingsService.getOpenCodeServerSummaries()` derives live booleans from its shared +credential owner. Explicit pairing tokens and manual passwords persist in the private +backend `opencode-server-pairings.json` (0600), scoped by profile/config identity, +server ID and normalized origin. Backend restart reuses them. Registry changes clear credentials before origin changes or +removal; credential changes revoke owned requests and captured transports synchronously. +`WorkspaceManager.shutdown()` disposes the backend owner before workspace cleanup. +The home/launcher Remotes disclosure shares pairing, folder browsing and project opening. + +`opencode/servers/connections.ts` supplies the internal target resolver, isolated +clients/fetches, coalesced admission, generation fences and project-occurrence leases. +`SettingsService` retains one registry, credential owner and connection owner for all +windows. The published local workspace connection reader delegates through this resolver +to the existing local lifecycle. Explicit acquisition requires a server ID and an +admission intent; workspace reads require an admitted target. Explicit project opening, +administrative routes and user-facing integration have separate qualification boundaries. +Active-target limits and release rules are in [CACHE_REFRESH_CONVENTIONS.md](CACHE_REFRESH_CONVENTIONS.md). + +Generic config PATCH operations reserve this subtree for the registry, for both +host and paired-device callers. Patch/result checks reject direct writes and +ancestor replacements that remove it before persistence or event publication. +Document and owner responses/events share the public sanitizer. + +Schema preprocessing safely discards recognized development `credentialMode` and +`credentialRef` fields; SettingsService normalizes valid metadata through the +registry. The credential service uses a private per-instance Map and synchronous +memory changes inside asynchronous mutations, with origin/missing-server +invalidation on read and clearing usable after metadata removal. + ## 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](../AGENTS.md) and the area documents it indexes. diff --git a/docs/help/de/browser-sidecars.md b/docs/help/de/browser-sidecars.md index 5d3a2aab34..5fbb616e94 100644 --- a/docs/help/de/browser-sidecars.md +++ b/docs/help/de/browser-sidecars.md @@ -1,5 +1,7 @@ # Browser-Vorschauen und SideCars +Links im internen Chat expliziter Server bleiben externe Links, die Sie selbst öffnen, einschließlich Loopback-URLs. Sie behalten die angegebene Adresse und nutzen den Netzwerkkontext Ihres Browsers. Host-Vorschauen bleiben in diesem Chat unverfügbar; ein Tunnel zum Ausführungsserver wird nicht bereitgestellt. + ## Sitzungsbrowser öffnen {#session-browser} 1. Wählen Sie in der Symbolleiste einer Unterhaltung **Web-Vorschau öffnen**. diff --git a/docs/help/de/conversations.md b/docs/help/de/conversations.md index b199228d63..1b48607e06 100644 --- a/docs/help/de/conversations.md +++ b/docs/help/de/conversations.md @@ -1,11 +1,17 @@ # Unterhaltungen +Der Chat expliziter Server zeigt unterstützte eingebettete Bilder oder geprüfte native Medien derselben Unterhaltung. Andere Quellen erhalten einen Nicht-verfügbar-Hinweis. Lokale Bildpfade finden nur bereits in dieser Unterhaltung gehaltene Bilder; `/btw` akzeptiert nur eingebettete Bilder. Gültige eingebettete Dateien bieten einen ausdrücklichen Download. + CodeNomad stellt native OpenCode-Sitzungen als Unterhaltungen dar, mit einer Hierarchie für delegierte Arbeit und separaten Bedienelementen für Ihre nächste Eingabe. Nachrichten stellen Markdown, Code, Diffs und unterstützte Bilder aus Werkzeugergebnissen dar. Textkopie, Vollverlaufssuche und Sprachausgabe verwenden Textprojektionen, keine eingebetteten Bildbytes. **Nachrichteninhalt** ändert die Sichtbarkeit, ohne gespeicherte Teile zu löschen; [Verlauf](history.md#operation-reference) unterscheidet Anzeigeeinstellungen und Bereinigung. Kopfzeilen von Denkprozessen und Werkzeugen zeigen, wie lange jeder Schritt gedauert hat, und zählen live mit, solange er läuft; Dauern unter einer Sekunde werden nicht angezeigt. Wenn **Tokens** in **Nachrichteninhalt** angezeigt wird (die Voreinstellung **Alles** zeigt sie), endet jede Agentennachricht nach ihrem letzten Text mit einer Token- und Kostenzeile. Diese Zeile summiert die Nachricht und die Nachrichten mit den Werkzeugen und Denkprozessen, die ihre Aktion **Tools und Denkprozesse aus dieser Antwort entfernen** abdeckt, innerhalb des geladenen Verlaufs; klappen Sie sie für Denk- und Cache-Zähler auf. Schritte, die nur Werkzeuge ausgeführt haben, haben keine eigene Zeile. +Im internen Chat mit expliziten Servern bietet `@` deren Agenten und Skills an und erklärt nicht verfügbare Projektdateiverweise. Ein Verbindungswechsel während einer Aktion stoppt ihre restlichen Schritte. Prüfen Sie die Unterhaltung vor erneutem Senden einer ungewissen Aktion: Sie kann OpenCode bereits erreicht haben. + +Eine unterbrochene oder ungewisse Aktion hinterlässt einen nicht modalen Hinweis in ihrer Quellunterhaltung und erhält den aktuellen Fokus. Wird die Bearbeitung einer Warteschlangennachricht unterbrochen, bleibt ihr bekannter Inhalt in der geöffneten Quellunterhaltung wiederherstellbar: Prüfen Sie die Warteschlange, leeren Sie Entwurf und Anhänge und wählen Sie **Gespeicherte Nachricht wiederherstellen**. Dadurch entsteht ein bearbeitbarer Entwurf; Senden ist eine eigene Aktion. Eine überholte `/btw`-Frage erlaubt eine ausdrücklich neue Anfrage, sobald die alte Anfrage abgeschlossen ist. + ## Unterhaltungen finden und navigieren {#navigate-conversations} 1. Wählen Sie eine Zeile unter **Sitzungen** oder verwenden Sie **Neue Sitzung**, um eine übergeordnete Unterhaltung zu beginnen. diff --git a/docs/help/de/extensions.md b/docs/help/de/extensions.md index 5a69a639e2..1af0281258 100644 --- a/docs/help/de/extensions.md +++ b/docs/help/de/extensions.md @@ -43,6 +43,8 @@ Jeder Ersatz widerruft die Aktivierung in allen Projekten, selbst bei unverände ## Kontext, Asset-Zustimmung und Sandbox-Grenzen {#permissions-sandbox} +Repository-Einträge der API 3 sind nur für Projekte verfügbar, die den gemeinsamen lokalen OpenCode-Dienst verwenden. Für jeden ausdrücklich konfigurierten OpenCode-Server, auch über Loopback oder bei getrennter Verbindung, sind sie unabhängig von dessen nativer Git-Unterstützung nicht verfügbar; die Ablehnung erfolgt vor Zugriffen auf Host-Git, Forge-Anmeldungen oder das Netzwerk. + | Vertrag | Was Aktivierung erlaubt | | --- | --- | | API 1 / `session.context` | Aktuelle Sitzungskennung (oder keine), Oberflächensprache und Darstellung. Kein Verlaufstext oder Dateisystemzugriff. | diff --git a/docs/help/de/files.md b/docs/help/de/files.md index 4b73dd9eb9..ecb075fde9 100644 --- a/docs/help/de/files.md +++ b/docs/help/de/files.md @@ -19,6 +19,10 @@ Aufgeklappte Ordner bleiben bei Moduswechseln erhalten. Listen/Status/Verlauf ve Zeilenaktionen umfassen **Pfad kopieren** und, soweit der Client Backend-Pfade öffnen kann, Dateimanager-/Editor-/Terminal-Aktionen wie **Mit Standardanwendung öffnen**, **Im Ordner anzeigen**, **Im Dateimanager öffnen** und **Terminal hier öffnen**. Bei wenig Platz können Aktionen unter **Weitere Aktionen für {name}** erscheinen; der Datei- oder Ordnername ersetzt `{name}`. Ein Remote-Browser darf einen Serverpfad nicht als lokalen Gerätepfad voraussetzen; siehe [Fernsteuerung](remote-control.md). +### Projekte auf einem OpenCode-Server {#opencode-server-files} + +Bei einem Projekt, das auf einem konfigurierten OpenCode-Server geöffnet ist, liest **Dateien** diesen Server über seine OpenCode-API, nie die Festplatte oder Git dieses Computers. **Arbeitsbereich** listet den geöffneten Ordner schreibgeschützt auf und zeigt ihn in der Vorschau (kein **Speichern**; Vorschauen enden bei 5 MiB). **Änderungen** zeigt die Änderungen der Arbeitskopie des geöffneten Ordners und seines Branches in einer einzigen Liste **Änderungen**, ohne Stagen, Commit, **Commits** oder **Git initialisieren**. Kann der Server keinen vollständigen, eindeutigen Zustand melden, zeigt das Panel **Inhalt nicht verfügbar oder unvollständig.** statt einer leeren Liste. Verwenden Sie **Aktualisieren**, nachdem der Agent Dateien geändert hat; das Panel aktualisiert sich auch, wenn der Server Datei- oder Branch-Änderungen meldet. Aktionen zum Öffnen auf diesem Computer bleiben nicht verfügbar. + ## Quelltext bearbeiten und sicher speichern {#edit-save} 1. Öffnen Sie eine Textdatei im Arbeitsbereich mit ihrer Augenaktion. diff --git a/docs/help/de/history.md b/docs/help/de/history.md index 44888353d0..e9fdedbab2 100644 --- a/docs/help/de/history.md +++ b/docs/help/de/history.md @@ -2,6 +2,8 @@ Gespeicherter Verlauf, aktuell angezeigter Gesprächsverlauf und komprimierter Modellkontext sind getrennte Dinge. Wählen Sie Navigation oder Filter, bevor Sie etwas löschen. +Diese erweiterten Verlaufsfunktionen gelten für den gemeinsam genutzten lokalen OpenCode-Dienst. Projekte auf expliziten Servern verwenden native Seiten und eine Zeitleiste geladener Nachrichten, bewahren bei unerreichbaren Passagen die gespeicherte Leseposition und bieten die ausdrückliche Rückkehr zur neuesten Seite. Volltextsuche, Vorschauen ungeladener Nachrichten und technische Bereinigung bleiben dort unverfügbar; Vorschauen bereits geladenen Textes bleiben verfügbar. + ## Gesamten Verlauf durchsuchen {#full-history-search} 1. Öffnen Sie **Chat-Verlauf durchsuchen** im Unterhaltungskopf oder verwenden Sie das zugewiesene Tastenkürzel (standardmäßig **Ctrl/Cmd+F**). diff --git a/docs/help/de/integrations.md b/docs/help/de/integrations.md index 65cb7d5f28..d51f45f510 100644 --- a/docs/help/de/integrations.md +++ b/docs/help/de/integrations.md @@ -1,5 +1,7 @@ # Native Integrationen +Die folgenden Installations-, Anwendungsanbindungs- und Konfigurationsaktionen gelten für gemeinsam genutzte lokale OpenCode-Projekte. Explizite Server behalten das schreibgeschützte Plugin-Inventar und den Integrationsstatus; Anbindung und Installation bleiben dort unverfügbar. + CodeNomad stellt OpenCodes native MCP-Verbindungen, Plugin-Aktivierung, Skills und benutzerdefinierte Befehle bereit. Sie laufen auf dem Ausführungshost. Sie sind getrennt von [Panel-Erweiterungen](extensions.md) in der Sandbox und [SideCars](browser-sidecars.md). ## Passende Steuerung wählen {#integration-scopes} diff --git a/docs/help/de/permissions.md b/docs/help/de/permissions.md index ba61aa9903..1a5fa85f57 100644 --- a/docs/help/de/permissions.md +++ b/docs/help/de/permissions.md @@ -1,5 +1,11 @@ # Fragen und Berechtigungen +Der Kontext eines expliziten Servers zeigt Namen und stabile ID, damit gleiche Namen unterscheidbar bleiben. Unsichere oder überholte Antworten erscheinen als höflicher, nicht modaler Hinweis im Anfrageeditor; gewöhnliche Fehler behalten ihre Fehleranzeige. + +**Explizite OpenCode-Server:** Fragen und Berechtigungen kommen nur live an. Entwürfe bleiben bearbeitbar. Veraltete Berechtigungen warten auf eine aktuelle Live-Anfrage; bekannte Formulare bieten die ausdrückliche Prüfung unten. Die aufklappbaren Dock-Details erklären die Grenze. Eine Unterhaltung zu öffnen stellt fehlende Anfragen nicht automatisch wieder her. Der Yolo-Modus funktioniert auf diesen Servern: Nach einer erneuten Verbindung liest CodeNomad die ausstehenden Berechtigungen nur von Yolo-Unterhaltungen erneut ein und genehmigt sie einmal. Wiederherstellung und Belege unten gelten für den gemeinsam genutzten lokalen Dienst. + +Wählen Sie bei einem bekannten Formular **Status dieses Formulars prüfen** im ursprünglichen Editor. Ein bestätigtes wartendes Formular aktiviert nur seine eigenen Antwort-/Abbruchaktionen; prüfen Sie den Entwurf und entscheiden Sie gesondert. Beantwortete oder stornierte Formulare behalten den Entwurf zum Nachlesen, ohne fremde Antworten, deren Urheber oder das Ergebnis Ihres früheren Versuchs zu erfinden. Eine unklare Prüfung lässt den Entwurf bearbeitbar und Antworten gesperrt; prüfen Sie erneut ausdrücklich. Jede Prüfung ist auf 10 Sekunden und 4 MiB pro Antwort begrenzt; geänderte Feldschemata bleiben unklar. Prüfung und Versand erfolgen nie automatisch. Die Gesamtabdeckung bleibt unbekannt; fehlende Formulare und Berechtigungen werden damit nicht gefunden. + Native Fragen, Forms und Berechtigungsanfragen werden im Unterbrechungsdock direkt über dem Eingabefeld beantwortet, nicht in wartenden Werkzeugkarten im Verlauf. ## Anfrage finden und Quelle prüfen {#request-dock} diff --git a/docs/help/de/projects.md b/docs/help/de/projects.md index 35b4223e6f..5531d9281a 100644 --- a/docs/help/de/projects.md +++ b/docs/help/de/projects.md @@ -21,6 +21,16 @@ Zuletzt verwendete Einträge sind Verknüpfungen. **Arbeitsbereich umbenennen** Ein normaler Klick öffnet weiterhin die vollständige Startseite. Der Schnellstarter ist ein Direktzugriff, keine Verwaltungsoberfläche: Benennen/entfernen Sie zuletzt verwendete Projekte und verwalten Sie Server-Lesezeichen auf der Startseite. Escape schließt den Schnellstarter und setzt den Fokus auf `+` zurück. +## Projekt auf einem OpenCode-Server öffnen {#remote-project} + +1. Klappen Sie auf der Startseite oder im Schnellstarter **REMOTE** auf und wählen Sie **+ Projekt** bei einem Server. Sein Name bleibt neben dem Ordnerpfad sichtbar. +2. Wählen Sie einen Server, durchsuchen Sie seine Ordner und wählen Sie **Öffnen**. **Rücktaste** wechselt zum übergeordneten Ordner; **Esc** kehrt zu den Servern zurück. +3. Um einen Server hinzuzufügen, fügen Sie seinen `opencode pair`-Link oder `https://opencode:@host:port` in **Kopplungslink oder Adresse** ein. Rechtsklick auf einen Server (oder **Umschalt+F10**) für **Gespeicherten Server entfernen**. + +Der Tab zeigt ein Server-Symbol, und der Ordner erscheint unter den zuletzt verwendeten Projekten. **Ordner durchsuchen**, **Git-Repo klonen** und temporäre Instanzen bleiben auf diesem Computer. + +Das Host-Backend speichert Kopplungstoken und manuelle Passwörter über Neustarts hinweg in seiner privaten `opencode-server-pairings.json` (0600) neben `config.yaml`. Ablauf, HTTP 401, ein geänderter Ursprung oder Entfernen des Servers löschen das Geheimnis. Gespeicherte Projekte werden auf ihrem eigenen Server wiederhergestellt; nur der Host fügt Server hinzu oder entfernt sie. + ## Projekt-Tab schließen {#close-stop} 1. Verwenden Sie die Schließen-Schaltfläche des Tabs oder **Tab schließen** in der Befehlspalette (`Ctrl/Cmd+W` im Renderer). diff --git a/docs/help/de/providers.md b/docs/help/de/providers.md index d0b1f03ed9..c2b10ba361 100644 --- a/docs/help/de/providers.md +++ b/docs/help/de/providers.md @@ -4,6 +4,8 @@ Anbieterauthentifizierung gehört zum verbundenen OpenCode-Dienst, nicht zum Bro ## Modell- oder Suchanbieter verbinden {#connect} +Prüfen Sie **Ausgewählter OpenCode-Server**. Die nachfolgend beschriebenen Verbindungs-, Konto-, Websuch- und Bildeinstellungen gelten für den gemeinsamen lokalen Dienst. Ein qualifizierter, explizit angegebener Server zeigt nur einen schreibgeschützten nativen Anbieter- und Modellkatalog; verwalten Sie seine Authentifizierung und Konfiguration direkt auf diesem Server, außerhalb der aktuellen Möglichkeiten von CodeNomad. Bei nicht verfügbaren Projekten bleiben die Steuerelemente inaktiv; CodeNomad-Einstellungen bleiben nutzbar. Beim lokalen Dienst lesen zugeklappte Gruppen **Modelle**, **Websuche** und **Bilder** ihre Daten erst beim Aufklappen. + 1. Öffnen Sie einen Arbeitsbereich und dann **Einstellungen → Anbieter**. **Modelle** ist anfangs aufgeklappt; klappen Sie für Suchanbieter **Websuche** auf. **Bilder** enthält die Bildeinstellungen. 2. Wählen Sie in dieser Gruppe zuerst **Anbieter auswählen**, dann **Verbinden**. 3. Durchlaufen Sie bei einem Modellanbieter die angebotene native **Authentifizierungsmethode**: API-Schlüssel, OAuth oder Befehl. Verwenden Sie bei OAuth **Autorisierungsseite öffnen** und übermitteln Sie einen Autorisierungscode nur auf Aufforderung. Suchanbieter verbinden sich mit einem API-Schlüssel. diff --git a/docs/help/de/security.md b/docs/help/de/security.md index 0e5d7a17b8..0bbda9c3db 100644 --- a/docs/help/de/security.md +++ b/docs/help/de/security.md @@ -1,5 +1,9 @@ # Authentifizierung und Sicherheit +Die Dateiauswahl liest den Anhang auf deinem Gerät; das Senden überträgt seine Bytes an den OpenCode-Server des Projekts. Der gemeinsame lokale Dienst gehört zum CodeNomad-Ausführungshost, der ein anderes Gerät sein kann. Medienabrufe begrenzen die gesamte dekomprimierte Serverantwort einschließlich Fehlern vor dem Parsen auf 16 MiB. Überschreitung, Abbruch oder ein entzogenes Projekt bzw. eine entzogene Verbindung lassen den Abruf scheitern. Bildabmessungen und der Speicher für dekodierte Bilder werden vom Browser verwaltet; Uploads vom Gerät behalten ihre eigenen Budgets. + +Der interne Chat expliziter Server prüft Medien vor Anzeige oder Download. Externe Bild-URLs, aktive SVG-/HTML-Bilder und HTML-Medieneinbettungen werden abgelehnt; Downloads erfordern Ihre Aktion und fehlgeschlagene Lesezugriffe bleiben fehlgeschlagen. Die Grenze von 8 MiB je Daten-URI begrenzt die kodierte Eingabe getrennt von dekodierten Bildmaßen und Geräte-Uploadgrenzen. + Zugriff auf CodeNomad kann über OpenCode Arbeit auf dem Backend-Host ausführen. Behandeln Sie Serverpasswörter, Browsersitzungen und gekoppelte Geräte als mächtige Zugangsdaten. CodeNomad ist keine mandantenfähige Ausführungs-Sandbox. ## Serverauthentifizierung wählen {#authentication} diff --git a/docs/help/de/settings.md b/docs/help/de/settings.md index fb0efbb914..99985ee6e6 100644 --- a/docs/help/de/settings.md +++ b/docs/help/de/settings.md @@ -2,6 +2,8 @@ ## Einstellungen öffnen und Geltungsbereich erkennen {#open-settings} +**Ausgewählter OpenCode-Server** kennzeichnet den Projektkontext (`local-shared` für den gemeinsamen lokalen Dienst); CodeNomad-Einstellungen gelten gemeinsam. Bei nicht verfügbaren Projekten bleiben OpenCode-Steuerelemente inaktiv. Konfigurationsdateien, Umgebungsvariablen und OpenCode-Wartung kennzeichnen das **lokale CodeNomad-Backend**: HOME-Dateien, Profilumgebung und gemeinsamer Dienst gehören dazu. **Lokales Backend verwalten** öffnet diese lokalen Steuerelemente ausdrücklich getrennt vom ausgewählten Projekt. + 1. Öffnen Sie **Einstellungen** über das Zahnrad **Einstellungen öffnen** in der Tab-Leiste (in der macOS-Desktop-App in der Titelleiste) oder auf der Startseite. Direktzugänge wie **Anbieter verwalten** in der Modellauswahl, das Zahnrad des Missionspanels oder das Zahnrad **Einstellungen** im Benachrichtigungsverlauf öffnen direkt den passenden Abschnitt. 2. Wählen Sie einen Abschnitt. Lokale Electron-/Tauri-Fenster öffnen oder fokussieren ein natives Einstellungsfenster; Browser-/Remote-Ansichten verwenden die eingebettete Einstellungsseite. 3. Prüfen Sie vor dem Verlassen den Geltungsbereich und mögliche **Speichern**-Aktionen. @@ -15,7 +17,9 @@ Die meisten Auswahlen wirken sofort, auch die Missionsvorgaben, die jede Änderu | Globale/projektbezogene OpenCode-Einstellungen | Native Plugin-/Konfigurationsänderungen im angezeigten Umfang. Projektsteuerung benötigt ein aktives Projekt/eine Location. | | Desktop-Datenprofil | Native Fenster, Wiederherstellungszustand und Browserspeicher, unabhängig von Konfigurationsdatei und gemeinsamem OpenCode-Dienst. Siehe [Desktop-Fenster und Daten](desktop.md). | -**Statistik** umfasst den gesamten verbundenen OpenCode-Dienst (alle Projekte, unabhängige Klone und Untersitzungen), nicht nur den geöffneten Ordner, für die letzten 7, 30, 90 oder 365 Tage. Sie benötigt ein geöffnetes Projekt und zeigt die von OpenCode erfassten Tokens und Kosten, keine Anbieterrechnungen oder Abonnementkontingente; während der Aktualisierung können zuvor gespeicherte Summen erscheinen. Plankontingente gehören in den Statusabschnitt **Nutzung**. +Qualifizierte, explizit angegebene Server bieten einen schreibgeschützten Anbieter- und Modellkatalog. Zurückgestellte Abschnitte bleiben auswählbar und erläutern ihre Einschränkung; verwalten Sie diese Servereinstellungen direkt auf dem Server. + +**Statistik** umfasst den gesamten gemeinsamen lokalen OpenCode-Dienst (alle Projekte, unabhängige Klone und Untersitzungen), nicht nur den geöffneten Ordner, für die letzten 7, 30, 90 oder 365 Tage. Sie benötigt ein geöffnetes Projekt und zeigt die von OpenCode erfassten Tokens und Kosten, keine Anbieterrechnungen oder Abonnementkontingente; während der Aktualisierung können zuvor gespeicherte Summen erscheinen. Plankontingente gehören in den Statusabschnitt **Nutzung**. **Statistik** ist für explizit angegebene Server nicht verfügbar; der Abschnitt erläutert den Grund. Anzeigeeinstellungen neu zu setzen startet OpenCode nicht neu und wiederholt keinen Prompt. Native Konfiguration, Dienstwartung und Zugangsdaten haben separate Folgen: siehe [OpenCode-Einrichtung](opencode.md), [Anbieter](providers.md) und [Integrationen](integrations.md). @@ -42,6 +46,8 @@ Erkannte [Integrationen](integrations.md#integration-sections) haben ebenfalls S Status enthält Tokeninformationen, Yolo-Modus, Anbieternutzung, Hintergrund-Shells, MCP und Plugins. Solange die Unterhaltung ein [Ziel](conversations.md#goal) hat, zeigt eine Zielzeile über diesen Abschnitten es an; diese Zeile ist kein Abschnitt und lässt sich weder ausblenden noch verschieben. Ausblenden deaktiviert keinen Dienst und widerruft keine Rechte. Schmale Layouts schließen Panels, die nicht mehr passen, statt die Unterhaltung einzuengen; ein dort geöffnetes Panel schwebt über ihr, und ein schwebendes Panel zu öffnen schließt das andere. +Bei einem Projekt auf einem konfigurierten OpenCode-Server lesen diese Abschnitte diesen Server. **Nutzung** zeigt native OpenCode-Go-Kontingente und die zugangsdatenfreie Zen-Schätzung aus [Anbieter](providers.md#usage); andere Anbieter zeigen kein Kontingent. **Plugins** listet die Plugins des Servers mit ihrem Zustand; ihre Schalter bleiben schreibgeschützt, weil OpenCode keine API bietet, um die Plugin-Konfiguration des Servers zu ändern. MCP-Server lassen sich weiterhin verbinden oder trennen. **Hintergrund-Shells** listet die Shells des Servers für den geöffneten Ordner auf und stoppt sie. + Integriertes Layout ist Fensterlayout, keine Projektänderung. Erweiterungskästchen sind anders: Sie aktivieren Code über alle Projekte dieser Konfiguration. **Zurücksetzen** ändert keine Erweiterungszustimmung. Siehe [Panel-Erweiterungen](extensions.md). ## Verlaufsdetails und Eingabegröße {#transcript-composer} diff --git a/docs/help/de/troubleshooting.md b/docs/help/de/troubleshooting.md index 3cc2a11d9a..0b742d3025 100644 --- a/docs/help/de/troubleshooting.md +++ b/docs/help/de/troubleshooting.md @@ -1,5 +1,9 @@ # Fehlerbehebung +Unterscheiden Sie gleichnamige Ausführungsserver anhand der stabilen ID neben dem Namen in Anfragedetails und Projektmeldungen. Eine unsichere Antwort bleibt im ursprünglichen Editor, ohne Fokuswechsel oder automatischen Neuversand. + +**Explizite OpenCode-Server:** Nach einer Unterbrechung oder einem Backend-Neustart ist die Abdeckung wartender Anfragen unbekannt, auch bei leerem Dock. Bewahren Sie Entwürfe auf; veraltete Berechtigungen warten auf eine aktuelle Live-Anfrage. Bei bekannten Formularen wählen Sie **Status dieses Formulars prüfen** im ursprünglichen Editor; unklare Ergebnisse sperren Antworten und erlauben eine neue ausdrückliche Prüfung. Grenze: insgesamt 10 Sekunden und 4 MiB pro Antwort; die Abdeckung bleibt unbekannt. Das Öffnen einer Unterhaltung zeigt deren Inhalt, ohne fehlende Anfragen automatisch zu finden. Eine vor der Unterbrechung gesendete Antwort kann angekommen sein; es wird nichts automatisch wiederholt. Die automatische Wiederherstellung unten betrifft den gemeinsam genutzten lokalen Dienst. Siehe [Fragen und Berechtigungen](permissions.md). + Prüfen Sie zur Wiederherstellung zuerst die zuständige Komponente des fehlgeschlagenen Vorgangs: Browser, CodeNomad-Backend, OpenCode-Dienst oder Anbieter. Eine verlorene Antwort beweist keine fehlgeschlagene Änderung; lesen Sie vor Wiederholung den aktuellen Zustand erneut. ## Desktop-Startprobleme {#desktop-launch} diff --git a/docs/help/en/browser-sidecars.md b/docs/help/en/browser-sidecars.md index 19dac63042..bf9148d524 100644 --- a/docs/help/en/browser-sidecars.md +++ b/docs/help/en/browser-sidecars.md @@ -1,5 +1,7 @@ # Browser previews and SideCars +Links in internal explicit-server chat remain external links opened by your action, including loopback URLs. They retain the address as written and use your browser's network context. This chat leaves host previews unavailable; it provides no tunnel to the execution server. + ## Open a session browser {#session-browser} 1. In a conversation's toolbar, choose **Open web preview**. diff --git a/docs/help/en/conversations.md b/docs/help/en/conversations.md index 6b34645813..20f4ff50bb 100644 --- a/docs/help/en/conversations.md +++ b/docs/help/en/conversations.md @@ -1,11 +1,17 @@ # Conversations +Explicit-server chat displays supported embedded images or qualified native media belonging to the same conversation. Other sources show an unavailable label. Local image paths resolve only to images already held in that conversation; `/btw` accepts embedded images only. Valid embedded files offer an explicit download. + CodeNomad presents native OpenCode sessions as conversations, with a hierarchy for delegated work and separate controls for what you send next. Messages render Markdown, code, diffs and supported tool-result images. Text copy, full-history search and speech use text projections, not embedded image bytes. **Message content** changes visibility without deleting stored parts; [History](history.md#operation-reference) distinguishes display controls from cleanup. Reasoning and tool headers show how long each step took, counting live while it runs; durations under one second are not shown. When **Tokens** is shown in **Message content** (the **Everything** preset shows it), each agent message ends with one token and cost line after its final text. That line adds up the message and the messages holding the tools and reasoning that its **Remove tools and reasoning from this response** action covers, within the loaded transcript; expand it for reasoning and cache counts. Steps that only ran tools have no line of their own. +In the internal explicit-server chat, `@` offers that server's agents and skills and explains unavailable project file references. A connection change during an action stops its remaining steps. Check the conversation before resending an uncertain action; it may already have reached OpenCode. + +An interrupted or uncertain action leaves a non-modal notice in its source conversation and preserves your current focus. If a queued edit is interrupted, its known content remains recoverable in the open source conversation: check the queue, clear the draft and attachments, then choose **Restore saved prompt**. This restores an editable draft; sending is a separate action. A retired `/btw` question permits an explicit new request once its old request settles. + ## Find and navigate conversations {#navigate-conversations} 1. Select a row under **Sessions**, or use **New session** to start a parent conversation. diff --git a/docs/help/en/extensions.md b/docs/help/en/extensions.md index 96d138d5b3..a773d16cc1 100644 --- a/docs/help/en/extensions.md +++ b/docs/help/en/extensions.md @@ -43,6 +43,8 @@ Every replacement revokes activation across all projects, even if the permission ## Context, asset consent and sandbox limits {#permissions-sandbox} +API 3 repository work items are available only for projects using the shared local OpenCode service. They are unavailable for every explicitly configured OpenCode server, including loopback servers and disconnected targets, regardless of native Git support; the refusal happens before host Git, forge sign-ins or network access. + | Contract | What activation permits | | --- | --- | | API 1 / `session.context` | Current session identifier (or none), interface language and appearance. No transcript text or filesystem access. | diff --git a/docs/help/en/files.md b/docs/help/en/files.md index c3e875b088..e3889aaa29 100644 --- a/docs/help/en/files.md +++ b/docs/help/en/files.md @@ -19,6 +19,10 @@ Expanded folders survive mode changes. Listings/status/history use cached snapsh Row actions include **Copy path** and, where the client supports opening backend paths, file-manager/editor/terminal actions such as **Open with default application**, **Show in folder**, **Open in file manager** and **Open terminal here**. Actions can move into **More actions for {name}** when space is limited; the file or folder name replaces `{name}`. A remote browser cannot assume a server path is a local-device path; see [Remote Control](remote-control.md). +### Projects on an OpenCode server {#opencode-server-files} + +For a project opened on a configured OpenCode server, **Files** reads that server through its OpenCode API, never this computer's disk or Git. **Workspace** lists and previews the opened folder read-only (no **Save**; previews stop at 5 MiB). **Changes** shows the working-copy changes of the opened folder and its branch, in one **Changes** list without staging, commit, **Commits** or **Initialize Git**. When the server cannot report a complete, unambiguous state, the panel shows **Content unavailable or incomplete.** instead of an empty list. Use **Refresh** after the agent changes files; the panel also refreshes when the server reports file or branch changes. Open-on-this-computer actions stay unavailable. + ## Edit source and save safely {#edit-save} 1. Open a Workspace text file with its eye action. diff --git a/docs/help/en/history.md b/docs/help/en/history.md index c3db3c7c22..98e945a67c 100644 --- a/docs/help/en/history.md +++ b/docs/help/en/history.md @@ -2,6 +2,8 @@ Stored history, what the transcript currently displays and the model's compacted context are separate. Choose navigation or filtering before deleting anything. +These enriched-history workflows apply to the shared local OpenCode service. Projects on explicit servers use native pages and a loaded-message timeline, preserving the saved reading position when a passage is unavailable and offering explicit latest-page recovery. Full-text search, previews of unloaded messages and technical cleanup remain unavailable there; previews of already loaded text remain available. + ## Search full history {#full-history-search} 1. Open **Search chat history** in the conversation header, or use its configured shortcut (default **Ctrl/Cmd+F**). diff --git a/docs/help/en/integrations.md b/docs/help/en/integrations.md index 115adaee74..c8558cc9df 100644 --- a/docs/help/en/integrations.md +++ b/docs/help/en/integrations.md @@ -1,5 +1,7 @@ # Native integrations +The installation, application attachment and configuration controls below apply to shared-local OpenCode projects. Explicit servers retain read-only Plugins inventory and integration status; attachment and installation controls stay unavailable there. + CodeNomad exposes OpenCode's native MCP connections, plugin activation, skills and custom commands. These run on the execution host. They are separate from sandboxed [panel Extensions](extensions.md) and [SideCars](browser-sidecars.md). ## Choose the right control {#integration-scopes} diff --git a/docs/help/en/permissions.md b/docs/help/en/permissions.md index ca4f10d1e6..3a3b458269 100644 --- a/docs/help/en/permissions.md +++ b/docs/help/en/permissions.md @@ -1,5 +1,11 @@ # Questions and permissions +An explicit server's context includes its name and stable ID, so identical names remain distinguishable. Uncertain or superseded replies use a polite, non-modal notice in the request editor; ordinary failures retain their error treatment. + +**Explicit OpenCode servers:** questions and permissions arrive live only. Known drafts remain editable. Stale permissions wait for a current live request; known Forms have the explicit check below. The dock's disclosure explains the limitation. Opening a conversation lets you review it, without automatically recovering missing requests. Yolo mode works on these servers: after a reconnection, CodeNomad re-reads the pending permissions of Yolo conversations only and approves them once. The recovery and receipt workflows below apply to the shared local service. + +For a known Form, choose **Check this form’s status** in its source editor. A verified waiting Form enables only its own reply/cancel controls; review the draft and make a separate explicit choice. An answered or cancelled Form keeps the draft for reference, without showing another client's answer or inventing its author or the outcome of your earlier attempt. An inconclusive check keeps editing available and responses blocked; you can explicitly check again. Each check is limited to 10 seconds and 4 MiB per response; a changed field schema also stays inconclusive. No automatic check or resend occurs. Overall coverage remains unknown; this check finds neither missing Forms nor permissions. + Native questions, Forms and permission requests are answered in the interruption dock immediately above the composer, not inside pending transcript tool cards. ## Find the request and check its source {#request-dock} diff --git a/docs/help/en/projects.md b/docs/help/en/projects.md index 696efb58be..798fcccadd 100644 --- a/docs/help/en/projects.md +++ b/docs/help/en/projects.md @@ -21,6 +21,16 @@ Recent entries are shortcuts. **Rename workspace** changes its displayed name; * A normal click still opens the full home page. The launcher is a shortcut, not the management surface: rename/remove recent projects and manage server bookmarks on the home page. Escape dismisses the launcher and returns focus to `+`. +## Open a project on an OpenCode server {#remote-project} + +1. On the home page or in the launcher, expand **REMOTES** and choose **+ Project** on a server. Its name stays visible beside the folder path. +2. Choose a server, browse its folders and choose **Open**. **Backspace** goes to the parent folder; **Escape** returns to the servers. +3. To add a server, paste its `opencode pair` link, or `https://opencode:@host:port`, into **Pairing link or address**. Right-click a server (or **Shift+F10**) for **Remove saved server**. + +The tab shows a server icon and the folder joins the recent projects. **Browse Folders**, **Clone Git Repo** and temporary instances stay on this computer. + +The host backend keeps pairing tokens and manual passwords across launches in its private `opencode-server-pairings.json` (0600), beside `config.yaml`. Expiry, HTTP 401, origin replacement or server removal erases the secret. Registered projects restore on their own server; adding and removing servers is host-only. + ## Close a project tab {#close-stop} 1. Use the tab's close button or **Close Tab** in the command palette (`Ctrl/Cmd+W` in the renderer). diff --git a/docs/help/en/providers.md b/docs/help/en/providers.md index b96d0e7188..09edb733c3 100644 --- a/docs/help/en/providers.md +++ b/docs/help/en/providers.md @@ -4,6 +4,8 @@ Provider authentication belongs to the connected OpenCode service, not to the br ## Connect a model or search provider {#connect} +Check **Selected OpenCode server**. The connection, account, web-search and image settings described below apply to the shared local service. A qualified explicit server shows only a read-only native provider/model catalogue; administer its authentication and configuration directly on that server, outside CodeNomad's current capabilities. Unavailable projects keep their controls inactive; CodeNomad preferences remain usable. On the local service, folded **Models**, **Web search** and **Images** groups defer their reads until expanded. + 1. Open a workspace, then **Settings → Providers**. **Models** starts expanded; expand **Web search** for search providers. **Images** holds the image settings. 2. In that group, choose **Select provider**, then **Connect**. 3. For a model provider, complete the native **Authentication method** offered: API key, OAuth or command. For OAuth, use **Open authorization page** and submit an authorization code only when requested. Search providers connect with an API key. diff --git a/docs/help/en/security.md b/docs/help/en/security.md index 96edc61bc7..5bbf93ebb6 100644 --- a/docs/help/en/security.md +++ b/docs/help/en/security.md @@ -1,5 +1,9 @@ # Authentication and security +Selecting an attachment reads it on your device; sending the message transfers its bytes to the project's OpenCode server. The shared local service belongs to the CodeNomad execution host, which may differ from your device. Deferred-media reads cap the entire decompressed server response at 16 MiB before parsing, including errors. Overflow, cancellation or a retired project/connection fails the read. Image dimensions and decoded-image memory are managed by the browser; device uploads retain separate budgets. + +Internal explicit-server chat authorizes media before display or download. External image URLs, active SVG/HTML images and HTML media embeds are refused; downloads require your action and a failed read stays failed. The 8 MiB data-URI limit bounds encoded input separately from decoded image dimensions and device upload limits. + Access to CodeNomad can execute work on the backend host through OpenCode. Treat server passwords, browser sessions and paired devices as powerful credentials. CodeNomad is not a multi-tenant execution sandbox. ## Choose how the server authenticates {#authentication} diff --git a/docs/help/en/settings.md b/docs/help/en/settings.md index b6399f893b..011a350199 100644 --- a/docs/help/en/settings.md +++ b/docs/help/en/settings.md @@ -2,6 +2,8 @@ ## Open settings and identify the scope {#open-settings} +**Selected OpenCode server** identifies the project context (`local-shared` for the shared local service); CodeNomad preferences remain shared. Unavailable projects keep their OpenCode controls inactive. Config Files, Environment Variables and OpenCode maintenance identify the **local CodeNomad backend**: HOME files, profile environment and the shared service belong there. When **Manage local backend** is offered, it explicitly opens those local controls separately from the selected project. + 1. Open **Settings** with the **Open settings** gear in the tab bar (the title bar in the macOS desktop app) or on the home page. Shortcuts such as **Manage Providers** in the model selector, the Missions panel gear or the **Settings** gear in the notification history open the matching section directly. 2. Select a section. Local Electron and Tauri windows open or focus one native Preferences window; browser and remote views use the embedded settings screen. 3. Check the setting's scope and any **Save** action before leaving. @@ -15,7 +17,9 @@ Most choices apply immediately, including Mission preferences, which save each c | Global/Project OpenCode settings | Native plugin/configuration changes at their displayed scope. Project controls require an active project/Location. | | Desktop data profile | Native windows, restore state and browser storage, independently of the configuration file and shared OpenCode service. See [Desktop windows and data](desktop.md). | -**Stats** covers the entire connected OpenCode service (all projects, independent clones and subsessions), not only the opened folder, for the last 7, 30, 90 or 365 days. It needs an open project and shows OpenCode's recorded tokens and cost, not provider invoices or subscription allowances; previous saved totals can appear while it refreshes. Plan quotas belong to the **Usage** Status section. +Qualified explicit servers expose a read-only provider/model catalogue. Deferred sections remain selectable and explain their limitation; administer those server settings directly on the server. + +**Stats** covers the entire shared local OpenCode service (all projects, independent clones and subsessions), not only the opened folder, for the last 7, 30, 90 or 365 days. It needs an open project and shows OpenCode's recorded tokens and cost, not provider invoices or subscription allowances; previous saved totals can appear while it refreshes. Plan quotas belong to the **Usage** Status section. **Stats** is unavailable for explicit servers; its section explains why. Changing display preferences does not restart OpenCode or replay a prompt. Native configuration, service maintenance and credentials have separate effects: see [OpenCode setup](opencode.md), [Providers](providers.md) and [Integrations](integrations.md). @@ -42,6 +46,8 @@ Recognised [integrations](integrations.md#integration-sections) also have Status Status includes token information, Yolo mode, provider Usage, background shells, MCP and Plugins. While the conversation has a [goal](conversations.md#goal), a goal line above these sections shows it; that line is not a section and cannot be hidden or moved. Hiding a section does not disable its service or revoke permissions. Narrow layouts close panels that no longer fit instead of squeezing the conversation; a panel opened there floats over it, and opening one floating panel closes the other. +For a project on a configured OpenCode server, these sections read that server. **Usage** shows native OpenCode Go quotas and the credential-free Zen estimate described in [Providers](providers.md#usage); other providers show no quota. **Plugins** lists the server's plugins with their state; their switches stay read-only because OpenCode offers no API to change the server's plugin configuration. MCP servers can still be connected or disconnected. **Background Shells** lists and stops the server's shells of the opened folder. + Built-in layout is window layout, not a project mutation. Extension checkboxes are different: they activate code across all projects using the configuration. **Reset** does not change extension consent. See [Panel extensions](extensions.md). ## Transcript detail and composer size {#transcript-composer} diff --git a/docs/help/en/troubleshooting.md b/docs/help/en/troubleshooting.md index 51ef62d5d9..2c3bcf8197 100644 --- a/docs/help/en/troubleshooting.md +++ b/docs/help/en/troubleshooting.md @@ -1,5 +1,9 @@ # Troubleshooting +For same-name execution servers, use the stable ID shown with the name in request details and project notifications. An uncertain reply stays in its original editor without stealing focus or being resent automatically. + +**Explicit OpenCode servers:** after a disconnection or backend restart, waiting request coverage is unknown, including when the dock is empty. Keep known drafts; stale permissions wait for a current live request. For a known Form, use **Check this form’s status** in its source editor; an inconclusive result leaves responses blocked and permits another deliberate check. The check is limited to 10 seconds and 4 MiB per response; coverage stays unknown. Opening a conversation reviews content without automatically finding missing requests. A response sent before the gap may have succeeded: nothing is replayed automatically. The automatic pending-recovery steps below concern the shared local service. See [Questions and permissions](permissions.md). + Recover by checking the owner of the failing operation first: browser, CodeNomad backend, OpenCode service or provider. A lost reply does not prove a mutation failed; reread current state before repeating it. ## Desktop launch problems {#desktop-launch} diff --git a/docs/help/es/browser-sidecars.md b/docs/help/es/browser-sidecars.md index 436748bf3c..c540ef3318 100644 --- a/docs/help/es/browser-sidecars.md +++ b/docs/help/es/browser-sidecars.md @@ -1,5 +1,7 @@ # Vistas previas de navegador y SideCars +Los enlaces del chat interno de servidores explícitos siguen siendo enlaces externos que abre mediante una acción, incluidas las URL loopback. Conservan la dirección escrita y usan el contexto de red de su navegador. Las vistas previas del anfitrión quedan indisponibles en este chat; no se proporciona un túnel al servidor de ejecución. + ## Abrir el navegador de una sesión {#session-browser} 1. En la barra de herramientas de una conversación, elige **Abrir vista previa web**. diff --git a/docs/help/es/conversations.md b/docs/help/es/conversations.md index 402da3cf6a..fa1646ccf9 100644 --- a/docs/help/es/conversations.md +++ b/docs/help/es/conversations.md @@ -1,11 +1,17 @@ # Conversaciones +El chat de servidores explícitos muestra imágenes integradas compatibles o medios nativos verificados de la misma conversación. Las demás fuentes indican indisponibilidad. Las rutas locales solo encuentran imágenes ya presentes en esa conversación; `/btw` solo acepta imágenes integradas. Los archivos integrados válidos ofrecen una descarga explícita. + CodeNomad presenta las sesiones nativas de OpenCode como conversaciones, con una jerarquía para el trabajo delegado y controles independientes para lo que envías a continuación. Los mensajes muestran Markdown, código, diferencias e imágenes compatibles de resultados de herramientas. La copia de texto, la búsqueda en todo el historial y la voz usan proyecciones de texto, no los bytes de las imágenes incrustadas. **Contenido de los mensajes** cambia la visibilidad sin eliminar las partes almacenadas; [Historial](history.md#operation-reference) distingue los controles de visualización de la limpieza. Los encabezados de razonamiento y de herramientas muestran cuánto duró cada paso, con un contador en vivo mientras se ejecuta; no se muestran duraciones inferiores a un segundo. Cuando **Tokens** se muestra en **Contenido de los mensajes** (el preajuste **Todo** lo muestra), cada mensaje del agente termina con una línea de tokens y coste después de su texto final. Esa línea suma el mensaje y los mensajes que contienen las herramientas y el razonamiento que cubre su acción **Eliminar herramientas y razonamientos de esta respuesta**, dentro de la transcripción cargada; despliégala para ver los recuentos de razonamiento y de caché. Los pasos que solo ejecutaron herramientas no tienen línea propia. +En el chat interno con servidores explícitos, `@` ofrece los agentes y habilidades de ese servidor y explica que las referencias a archivos del proyecto no están disponibles. Un cambio de conexión durante una acción detiene sus pasos restantes. Comprueba la conversación antes de repetir una acción incierta: puede haber llegado ya a OpenCode. + +Una acción interrumpida o incierta deja un aviso no modal en su conversación de origen y mantiene el foco actual. Si se interrumpe la edición de un mensaje en cola, su contenido conocido sigue disponible en la conversación de origen abierta: comprueba la cola, vacía el borrador y los adjuntos y elige **Restaurar mensaje guardado**. Se restaura un borrador editable; enviarlo es otra acción. Una pregunta `/btw` retirada permite una nueva solicitud explícita cuando termina la anterior. + ## Buscar y recorrer conversaciones {#navigate-conversations} 1. Selecciona una fila en **Sesiones** o usa **Nueva sesión** para iniciar una conversación padre. diff --git a/docs/help/es/extensions.md b/docs/help/es/extensions.md index b66b0a9c97..f4afb9f128 100644 --- a/docs/help/es/extensions.md +++ b/docs/help/es/extensions.md @@ -43,6 +43,8 @@ Cada reemplazo revoca la activación en todos los proyectos, incluso si la lista ## Contexto, consentimiento de recursos y límites del aislamiento {#permissions-sandbox} +Los elementos del repositorio de la API 3 solo están disponibles para proyectos que usan el servicio OpenCode local compartido. No están disponibles para ningún servidor OpenCode configurado explícitamente, incluidos los servidores de loopback y los destinos desconectados, independientemente de su compatibilidad nativa con Git; el rechazo ocurre antes de acceder a Git del anfitrión, a las sesiones de las forjas o a la red. + | Contrato | Qué permite la activación | | --- | --- | | API 1 / `session.context` | Identificador de sesión actual (o ninguno), idioma y apariencia de la interfaz. Sin texto de transcripción ni acceso al sistema de archivos. | diff --git a/docs/help/es/files.md b/docs/help/es/files.md index fc5414331c..749c99ccd6 100644 --- a/docs/help/es/files.md +++ b/docs/help/es/files.md @@ -19,6 +19,10 @@ Las carpetas expandidas sobreviven a los cambios de modo. Las listas/el estado/e Las acciones de fila incluyen **Copiar ruta** y, cuando el cliente permite abrir rutas del backend, acciones de administrador de archivos/editor/terminal como **Abrir con la aplicación predeterminada**, **Mostrar en la carpeta**, **Abrir en el explorador de archivos** y **Abrir terminal aquí**. Las acciones pueden trasladarse a **Más acciones para {name}** cuando el espacio es limitado; el nombre del archivo o carpeta reemplaza `{name}`. Un navegador remoto no puede suponer que una ruta del servidor es local al dispositivo; consulta [Control remoto](remote-control.md). +### Proyectos en un servidor OpenCode {#opencode-server-files} + +En un proyecto abierto en un servidor OpenCode configurado, **Archivos** lee ese servidor a través de su API de OpenCode, nunca el disco ni el Git de este equipo. **Espacio de trabajo** lista y previsualiza la carpeta abierta en solo lectura (sin **Guardar**; las vistas previas se detienen en 5 MiB). **Cambios** muestra los cambios de la copia de trabajo de la carpeta abierta y su rama, en una única lista **Cambios**, sin preparación, commit, **Commits** ni **Inicializar Git**. Cuando el servidor no puede informar de un estado completo e inequívoco, el panel muestra **Contenido no disponible o incompleto.** en lugar de una lista vacía. Usa **Actualizar** después de que el agente modifique archivos; el panel también se actualiza cuando el servidor informa de cambios en archivos o ramas. Las acciones para abrir en este equipo siguen sin estar disponibles. + ## Editar código fuente y guardar con seguridad {#edit-save} 1. Abre un archivo de texto de Espacio de trabajo con su acción del ojo. diff --git a/docs/help/es/history.md b/docs/help/es/history.md index f6685a26a5..4cec19a132 100644 --- a/docs/help/es/history.md +++ b/docs/help/es/history.md @@ -2,6 +2,8 @@ El historial almacenado, lo que muestra actualmente la transcripción y el contexto compactado del modelo son cosas distintas. Elige navegar o filtrar antes de eliminar nada. +Estos flujos de historial enriquecido se aplican al servicio OpenCode local compartido. Los proyectos en servidores explícitos usan páginas nativas y una cronología de mensajes cargados, conservan la posición de lectura cuando un pasaje no está disponible y ofrecen volver explícitamente a la última página. La búsqueda de texto, las vistas previas de mensajes no cargados y la limpieza técnica siguen sin estar disponibles allí; las vistas previas del texto ya cargado siguen disponibles. + ## Buscar en todo el historial {#full-history-search} 1. Abre **Buscar en el historial del chat** en la cabecera de la conversación o usa su atajo configurado (por defecto **Ctrl/Cmd+F**). diff --git a/docs/help/es/integrations.md b/docs/help/es/integrations.md index 9c2ccd0f10..4165bc209e 100644 --- a/docs/help/es/integrations.md +++ b/docs/help/es/integrations.md @@ -1,5 +1,7 @@ # Integraciones nativas +Los controles de instalación, conexión con aplicaciones y configuración siguientes se aplican a proyectos OpenCode locales compartidos. Los servidores explícitos conservan el inventario de Plugins y el estado de las integraciones en solo lectura; la conexión con aplicaciones y la instalación no están disponibles allí. + CodeNomad expone las conexiones MCP nativas, la activación de plugins, las habilidades y los comandos personalizados de OpenCode. Se ejecutan en el equipo de ejecución. Son independientes de las [Extensiones de panel](extensions.md) aisladas y los [SideCars](browser-sidecars.md). ## Elegir el control adecuado {#integration-scopes} diff --git a/docs/help/es/permissions.md b/docs/help/es/permissions.md index 807aee3c63..3ecdd645f0 100644 --- a/docs/help/es/permissions.md +++ b/docs/help/es/permissions.md @@ -1,5 +1,11 @@ # Preguntas y permisos +El contexto de un servidor explícito incluye su nombre e ID estable para distinguir nombres iguales. Las respuestas inciertas o reemplazadas usan un aviso no modal de prioridad moderada en el editor de solicitudes; los fallos ordinarios conservan su tratamiento de error. + +**Servidores OpenCode explícitos:** las preguntas y permisos llegan solo en directo. Los borradores siguen editables. Los permisos obsoletos esperan una solicitud actual en directo; los formularios conocidos ofrecen la comprobación explícita de abajo. Los detalles desplegables del panel explican el límite. Abrir una conversación permite revisarla, sin recuperar automáticamente solicitudes faltantes. El modo Yolo funciona en estos servidores: tras una reconexión, CodeNomad vuelve a leer los permisos pendientes solo de las conversaciones con Yolo y los aprueba una vez. La recuperación y los recibos descritos abajo corresponden al servicio local compartido. + +Para un formulario conocido, elige **Comprobar el estado de este formulario** en su editor de origen. Si sigue esperando, se habilitan solo sus acciones; revisa el borrador y responde o cancela con otro gesto explícito. Si ya tiene respuesta o está cancelado, se conserva el borrador sin mostrar respuestas ajenas ni inventar su autor o el resultado de tu intento anterior. Una comprobación inconclusa mantiene la edición y bloquea las respuestas; puedes repetirla explícitamente. Cada comprobación se limita a 10 segundos y 4 MiB por respuesta; un esquema de campos cambiado también queda inconcluso. No hay comprobaciones ni reenvíos automáticos. La cobertura general sigue siendo desconocida; no se recuperan formularios ni permisos faltantes. + Las preguntas nativas, los formularios y las solicitudes de permiso se responden en el panel de interrupciones justo encima del editor de mensajes, no dentro de las tarjetas de herramientas pendientes de la transcripción. ## Buscar la solicitud y comprobar su origen {#request-dock} diff --git a/docs/help/es/projects.md b/docs/help/es/projects.md index 1f97772691..36c6a01016 100644 --- a/docs/help/es/projects.md +++ b/docs/help/es/projects.md @@ -21,6 +21,16 @@ Las entradas recientes son accesos directos. **Renombrar workspace** cambia su n Un clic normal sigue abriendo la página de inicio completa. El lanzador es un acceso directo, no la superficie de gestión: renombra/elimina proyectos recientes y gestiona los marcadores de servidores en la página de inicio. Escape cierra el lanzador y devuelve el foco a `+`. +## Abrir un proyecto en un servidor OpenCode {#remote-project} + +1. En la página de inicio o en el lanzador, despliegue **REMOTOS** y elija **+ Proyecto** en un servidor. Su nombre permanece visible junto a la ruta de la carpeta. +2. Elija un servidor, explore sus carpetas y elija **Abrir**. **Retroceso** sube a la carpeta superior; **Esc** vuelve a los servidores. +3. Para añadir un servidor, pegue su enlace `opencode pair`, o `https://opencode:@host:puerto`, en **Enlace de emparejamiento o dirección**. Haga clic derecho en un servidor (o **Mayús+F10**) para **Eliminar servidor guardado**. + +La pestaña muestra un icono de servidor y la carpeta se une a los proyectos recientes. **Buscar carpetas**, **Clonar repo Git** y las instancias temporales siguen en este equipo. + +El backend anfitrión conserva tokens de emparejamiento y contraseñas manuales entre inicios en su archivo privado `opencode-server-pairings.json` (0600), junto a `config.yaml`. La caducidad, HTTP 401, un cambio de origen o eliminar el servidor borran el secreto. Los proyectos guardados se restauran en su propio servidor; solo el anfitrión añade o elimina servidores. + ## Cerrar una pestaña de proyecto {#close-stop} 1. Usa el botón de cierre de la pestaña o **Cerrar pestaña** en la paleta de comandos (`Ctrl/Cmd+W` en el renderer). diff --git a/docs/help/es/providers.md b/docs/help/es/providers.md index 1c2d2f44a7..f2ad6d2be7 100644 --- a/docs/help/es/providers.md +++ b/docs/help/es/providers.md @@ -4,6 +4,8 @@ La autenticación de proveedores pertenece al servicio OpenCode conectado, no al ## Conectar un proveedor de modelos o búsqueda {#connect} +Comprueba **Servidor OpenCode seleccionado**. Los ajustes de conexión, cuentas, búsqueda web e imágenes descritos a continuación se aplican al servicio local compartido. Un servidor indicado explícitamente y cualificado solo muestra un catálogo nativo de proveedores y modelos de solo lectura; administra su autenticación y configuración directamente en ese servidor, fuera de las capacidades actuales de CodeNomad. Los proyectos no disponibles mantienen sus controles inactivos; las preferencias de CodeNomad siguen disponibles. En el servicio local, los grupos plegados **Modelos**, **Búsqueda web** e **Imágenes** aplazan la lectura de sus datos hasta que se expanden. + 1. Abre un espacio de trabajo y después **Configuración → Proveedores**. **Modelos** empieza expandido; expande **Búsqueda web** para los proveedores de búsqueda. **Imágenes** reúne los ajustes de imágenes. 2. En ese grupo, elige **Seleccionar proveedor** y después **Conectar**. 3. Para un proveedor de modelos, completa el **Método de autenticación** nativo ofrecido: clave API, OAuth o comando. Para OAuth, usa **Abrir página de autorización** y envía un código de autorización solo cuando se solicite. Los proveedores de búsqueda se conectan con una clave API. diff --git a/docs/help/es/security.md b/docs/help/es/security.md index 21def004f8..4299592d03 100644 --- a/docs/help/es/security.md +++ b/docs/help/es/security.md @@ -1,5 +1,9 @@ # Autenticación y seguridad +Elegir un archivo adjunto lo lee en tu dispositivo; enviar el mensaje transfiere sus bytes al servidor OpenCode del proyecto. El servicio local compartido pertenece al host de ejecución de CodeNomad, que puede ser distinto de tu dispositivo. La lectura de medios diferidos limita toda la respuesta descomprimida del servidor a 16 MiB antes del análisis, incluidos los errores. Un exceso, una cancelación o la retirada del proyecto o de la conexión hace fallar la lectura. El navegador gestiona las dimensiones de imagen y la memoria de las imágenes decodificadas; los envíos desde el dispositivo mantienen sus propios presupuestos. + +El chat interno de servidores explícitos autoriza medios antes de mostrarlos o descargarlos. Se rechazan URL de imágenes externas, imágenes SVG/HTML activas y medios HTML integrados; las descargas requieren una acción y las lecturas fallidas permanecen fallidas. El límite de 8 MiB por URI de datos acota la entrada codificada por separado de las dimensiones decodificadas y los límites de carga del dispositivo. + El acceso a CodeNomad permite ejecutar trabajo en el equipo del backend mediante OpenCode. Trata las contraseñas de servidor, las sesiones de navegador y los dispositivos emparejados como credenciales potentes. CodeNomad no es un entorno aislado de ejecución multiusuario. ## Elegir cómo autentica el servidor {#authentication} diff --git a/docs/help/es/settings.md b/docs/help/es/settings.md index d4acb61e12..bd352db85d 100644 --- a/docs/help/es/settings.md +++ b/docs/help/es/settings.md @@ -2,6 +2,8 @@ ## Abrir la configuración e identificar el ámbito {#open-settings} +**Servidor OpenCode seleccionado** identifica el contexto del proyecto (`local-shared` para el servicio local compartido); las preferencias de CodeNomad siguen siendo compartidas. Los proyectos no disponibles mantienen inactivos sus controles OpenCode. Los archivos de configuración, variables de entorno y mantenimiento OpenCode identifican el **backend local de CodeNomad**: archivos HOME, entorno del perfil y servicio compartido. **Administrar backend local** abre explícitamente esos controles locales por separado del proyecto seleccionado. + 1. Abre **Configuración** con el engranaje **Abrir configuración** de la barra de pestañas (la barra de título en la aplicación de escritorio de macOS) o de la página de inicio. Accesos directos como **Gestionar proveedores** en el selector de modelos, el engranaje del panel Misiones o el engranaje **Configuración** del historial de notificaciones abren directamente la sección correspondiente. 2. Selecciona una sección. Las ventanas locales de Electron y Tauri abren o enfocan una única ventana nativa de Preferencias; las vistas de navegador y remotas usan la pantalla de configuración integrada. 3. Comprueba el ámbito del ajuste y cualquier acción de **Guardar** antes de salir. @@ -15,7 +17,9 @@ La mayoría de las elecciones se aplican inmediatamente, incluidas las preferenc | Ajustes Global/Proyecto de OpenCode | Cambios nativos de plugins/configuración en el ámbito mostrado. Los controles de Proyecto requieren un proyecto/Location activo. | | Perfil de datos de escritorio | Ventanas nativas, estado de restauración y almacenamiento del navegador, independientemente del archivo de configuración y del servicio compartido de OpenCode. Consulta [Ventanas y datos de escritorio](desktop.md). | -**Estadísticas** abarca todo el servicio OpenCode conectado (todos los proyectos, clones independientes y subsesiones), no solo la carpeta abierta, durante los últimos 7, 30, 90 o 365 días. Necesita un proyecto abierto y muestra los tokens y el coste registrados por OpenCode, no facturas del proveedor ni cuotas de suscripción; los totales guardados anteriormente pueden aparecer mientras se actualiza. Las cuotas del plan pertenecen a la sección **Uso** de Estado. +Los servidores indicados explícitamente y cualificados ofrecen un catálogo de proveedores y modelos de solo lectura. Las secciones aplazadas siguen siendo seleccionables y explican su limitación; administra esos ajustes directamente en el servidor. + +**Estadísticas** abarca todo el servicio OpenCode local compartido (todos los proyectos, clones independientes y subsesiones), no solo la carpeta abierta, durante los últimos 7, 30, 90 o 365 días. Necesita un proyecto abierto y muestra los tokens y el coste registrados por OpenCode, no facturas del proveedor ni cuotas de suscripción; los totales guardados anteriormente pueden aparecer mientras se actualiza. Las cuotas del plan pertenecen a la sección **Uso** de Estado. **Estadísticas** no está disponible para servidores indicados explícitamente; su sección explica el motivo. Cambiar preferencias de visualización no reinicia OpenCode ni repite un mensaje. La configuración nativa, el mantenimiento del servicio y las credenciales tienen efectos independientes: consulta [configuración de OpenCode](opencode.md), [Proveedores](providers.md) e [Integraciones](integrations.md). @@ -42,6 +46,8 @@ Las [integraciones](integrations.md#integration-sections) reconocidas también t Estado incluye información de tokens, modo Yolo, Uso del proveedor, shells en segundo plano, MCP y Plugins. Mientras la conversación tiene un [objetivo](conversations.md#goal), una línea de objetivo encima de estas secciones lo muestra; esa línea no es una sección y no se puede ocultar ni mover. Ocultar una sección no desactiva su servicio ni revoca permisos. Las disposiciones estrechas cierran los paneles que ya no caben en lugar de estrechar la conversación; un panel abierto en ellas flota sobre la conversación, y abrir un panel flotante cierra el otro. +En un proyecto en un servidor OpenCode configurado, estas secciones leen ese servidor. **Uso** muestra las cuotas nativas OpenCode Go y la estimación Zen sin credenciales descrita en [Proveedores](providers.md#usage); los demás proveedores no muestran cuota. **Plugins** lista los plugins del servidor con su estado; sus interruptores quedan en solo lectura porque OpenCode no ofrece ninguna API para cambiar la configuración de plugins del servidor. Los servidores MCP aún se pueden conectar o desconectar. **Shells en segundo plano** lista y detiene los shells del servidor de la carpeta abierta. + La disposición integrada es disposición de ventana, no una modificación del proyecto. Las casillas de extensiones son distintas: activan código en todos los proyectos que usan la configuración. **Restablecer** no cambia el consentimiento de extensiones. Consulta [Extensiones de panel](extensions.md). ## Detalle de la transcripción y tamaño del editor {#transcript-composer} diff --git a/docs/help/es/troubleshooting.md b/docs/help/es/troubleshooting.md index a9524f13c9..5fc0f5d026 100644 --- a/docs/help/es/troubleshooting.md +++ b/docs/help/es/troubleshooting.md @@ -1,5 +1,9 @@ # Solución de problemas +Para servidores de ejecución con el mismo nombre, usa el ID estable junto al nombre en los detalles y avisos del proyecto. Una respuesta incierta permanece en su editor de origen, sin mover el foco ni reenviarse automáticamente. + +**Servidores OpenCode explícitos:** tras una desconexión o reinicio del backend se desconoce la cobertura de solicitudes pendientes, aunque el panel esté vacío. Conserva los borradores; los permisos obsoletos esperan una solicitud actual en directo. Para un formulario conocido, usa **Comprobar el estado de este formulario** en su editor de origen; un resultado inconcluso bloquea las respuestas y permite otra comprobación explícita. Límite: 10 segundos en total y 4 MiB por respuesta; la cobertura sigue siendo desconocida. Abrir una conversación permite ver su contenido sin encontrar automáticamente solicitudes faltantes. Una respuesta enviada antes del corte puede haber llegado; no hay reenvío automático. La recuperación automática descrita abajo corresponde al servicio local compartido. Consulta [Preguntas y permisos](permissions.md). + Para recuperarte, comprueba primero quién controla la operación fallida: navegador, backend de CodeNomad, servicio OpenCode o proveedor. Una respuesta perdida no demuestra que una modificación fallara; vuelve a leer el estado actual antes de repetirla. ## Problemas al iniciar el escritorio {#desktop-launch} diff --git a/docs/help/fr/browser-sidecars.md b/docs/help/fr/browser-sidecars.md index 1363b98529..7e878ed04b 100644 --- a/docs/help/fr/browser-sidecars.md +++ b/docs/help/fr/browser-sidecars.md @@ -1,5 +1,7 @@ # Aperçus navigateur et SideCars +Les liens du chat interne des serveurs explicites restent des liens externes ouverts par votre action, y compris les URL loopback. Ils conservent l’adresse écrite et utilisent le réseau de votre navigateur. Les aperçus hôte sont indisponibles dans ce chat ; aucun tunnel vers le serveur d’exécution n’est fourni. + ## Ouvrir un navigateur de session {#session-browser} 1. Dans la barre d’outils d’une conversation, choisissez **Ouvrir l'aperçu web**. diff --git a/docs/help/fr/conversations.md b/docs/help/fr/conversations.md index 496b8cd307..c078f760b4 100644 --- a/docs/help/fr/conversations.md +++ b/docs/help/fr/conversations.md @@ -1,11 +1,17 @@ # Conversations +Le chat des serveurs explicites affiche les images intégrées prises en charge ou les médias natifs qualifiés de la même conversation. Les autres sources affichent une indication d’indisponibilité. Les chemins locaux retrouvent uniquement des images déjà détenues par cette conversation ; `/btw` accepte uniquement les images intégrées. Les fichiers intégrés valides proposent un téléchargement explicite. + CodeNomad présente les sessions natives OpenCode comme des conversations, avec une hiérarchie pour le travail délégué et des commandes distinctes pour votre prochain envoi. Les messages affichent du Markdown, du code, des diffs et les images de résultats d’outils prises en charge. La copie de texte, la recherche dans l’historique complet et la voix utilisent des projections textuelles, pas les octets des images intégrées. **Contenu des messages** change la visibilité sans supprimer les parties enregistrées ; [Historique](history.md#operation-reference) distingue les commandes d’affichage du nettoyage. Les en-têtes de raisonnement et d’outils indiquent la durée de chaque étape, comptée en direct pendant son exécution ; les durées inférieures à une seconde ne sont pas affichées. Lorsque **Tokens** est affiché dans **Contenu des messages** (le préréglage **Tout** l’affiche), chaque message d’agent se termine par une seule ligne de tokens et de coût après son texte final. Cette ligne additionne le message et les messages contenant les outils et raisonnements que couvre son action **Supprimer les outils et raisonnements de cette réponse**, dans la transcription chargée ; dépliez-la pour les comptes de raisonnement et de cache. Les étapes qui n’ont exécuté que des outils n’ont pas de ligne propre. +Dans le chat interne sur serveur explicite, `@` propose les agents et compétences de ce serveur et explique l’indisponibilité des références aux fichiers du projet. Un changement de connexion pendant une action arrête ses étapes restantes. Vérifiez la conversation avant de renvoyer une action incertaine : elle peut déjà avoir atteint OpenCode. + +Une action interrompue ou incertaine laisse un avis non modal dans sa conversation source et conserve votre focus actuel. Si la modification d’un message en attente est interrompue, son contenu connu reste récupérable dans la conversation source ouverte : vérifiez la file, videz le brouillon et les pièces jointes, puis choisissez **Restaurer le message conservé**. Cela restaure un brouillon modifiable ; l’envoi reste une action distincte. Une question `/btw` périmée permet une nouvelle demande explicite lorsque l’ancienne requête se termine. + ## Trouver des conversations et naviguer {#navigate-conversations} 1. Sélectionnez une ligne sous **Sessions**, ou utilisez **Nouvelle session** pour démarrer une conversation parente. diff --git a/docs/help/fr/extensions.md b/docs/help/fr/extensions.md index ac50507fd8..fdc9e8d6ce 100644 --- a/docs/help/fr/extensions.md +++ b/docs/help/fr/extensions.md @@ -43,6 +43,8 @@ Chaque remplacement révoque l’activation dans tous les projets, même si les ## Contexte, consentement aux ressources et limites du bac à sable {#permissions-sandbox} +Les éléments de dépôt de l’API 3 sont disponibles uniquement pour les projets utilisant le service OpenCode local partagé. Ils sont indisponibles pour tout serveur OpenCode configuré explicitement, y compris en loopback ou déconnecté, quelle que soit sa prise en charge native de Git ; le refus intervient avant tout accès au Git de l’hôte, aux connexions aux forges ou au réseau. + | Contrat | Ce que l’activation permet | | --- | --- | | API 1 / `session.context` | Identifiant de session courante (ou aucun), langue et apparence d’interface. Aucun texte de transcription ni accès aux fichiers. | diff --git a/docs/help/fr/files.md b/docs/help/fr/files.md index 614041e691..4abc83b73d 100644 --- a/docs/help/fr/files.md +++ b/docs/help/fr/files.md @@ -19,6 +19,10 @@ Les dossiers développés le restent lors des changements de mode. Les listes/st Les actions de ligne incluent **Copier le chemin** et, lorsque le client peut ouvrir les chemins du backend, des actions de gestionnaire de fichiers/éditeur/terminal comme **Ouvrir avec l'application par défaut**, **Afficher dans le dossier**, **Ouvrir dans le gestionnaire de fichiers** et **Ouvrir un terminal ici**. Les actions peuvent passer dans **Plus d'actions pour {name}** si l’espace manque ; le nom du fichier ou dossier remplace `{name}`. Un navigateur distant ne peut pas supposer qu’un chemin serveur est local à l’appareil ; voir [Contrôle à distance](remote-control.md). +### Projets sur un serveur OpenCode {#opencode-server-files} + +Pour un projet ouvert sur un serveur OpenCode configuré, **Fichiers** lit ce serveur via son API OpenCode, jamais le disque ni le Git de cet ordinateur. **Workspace** liste et prévisualise le dossier ouvert en lecture seule (sans **Enregistrer** ; les aperçus s’arrêtent à 5 MiB). **Changements** affiche les changements de la copie de travail du dossier ouvert et de sa branche, dans une seule liste **Changements**, sans indexation, commit, **Commits** ni **Initialiser Git**. Lorsque le serveur ne peut pas fournir un état complet et sans ambiguïté, le panneau affiche **Contenu indisponible ou incomplet.** au lieu d’une liste vide. Utilisez **Actualiser** après que l’agent a modifié des fichiers ; le panneau s’actualise aussi lorsque le serveur signale des changements de fichiers ou de branche. Les actions d’ouverture sur cet ordinateur restent indisponibles. + ## Modifier le source et enregistrer sans risque {#edit-save} 1. Ouvrez un fichier texte du Workspace avec son œil. diff --git a/docs/help/fr/history.md b/docs/help/fr/history.md index a77923f90d..e7577500c0 100644 --- a/docs/help/fr/history.md +++ b/docs/help/fr/history.md @@ -2,6 +2,8 @@ L’historique enregistré, ce que la transcription affiche actuellement et le contexte compacté du modèle sont distincts. Préférez la navigation ou le filtrage avant toute suppression. +Ces parcours d’historique enrichi concernent le service OpenCode local partagé. Les projets sur serveur explicite utilisent des pages natives et une chronologie des messages chargés, préservent la position de lecture lorsqu’un passage est indisponible et proposent un retour explicite à la dernière page. La recherche dans le texte, les aperçus des messages non chargés et le nettoyage technique y restent indisponibles ; les aperçus du texte déjà chargé restent disponibles. + ## Rechercher dans tout l’historique {#full-history-search} 1. Ouvrez **Rechercher dans l'historique du chat** dans l’en-tête de conversation, ou utilisez son raccourci configuré (**Ctrl/Cmd+F** par défaut). diff --git a/docs/help/fr/integrations.md b/docs/help/fr/integrations.md index c42e2b9175..cb8583060e 100644 --- a/docs/help/fr/integrations.md +++ b/docs/help/fr/integrations.md @@ -1,5 +1,7 @@ # Intégrations natives +Les commandes d’installation, d’attachement à une application et de configuration ci-dessous concernent les projets OpenCode locaux partagés. Les serveurs explicites conservent l’inventaire Plugins et le statut des intégrations en lecture seule ; attachement et installation y restent indisponibles. + CodeNomad expose les connexions MCP natives, l’activation des plugins, les compétences et commandes personnalisées d’OpenCode. Elles s’exécutent sur l’hôte d’exécution. Elles sont distinctes des [Extensions de panneau](extensions.md) en bac à sable et des [SideCars](browser-sidecars.md). ## Choisir la bonne commande {#integration-scopes} diff --git a/docs/help/fr/permissions.md b/docs/help/fr/permissions.md index f04035968c..1fc99e2159 100644 --- a/docs/help/fr/permissions.md +++ b/docs/help/fr/permissions.md @@ -1,5 +1,11 @@ # Questions et autorisations +Le contexte d’un serveur explicite comprend son nom et son ID stable pour distinguer les noms identiques. Une réponse incertaine ou dépassée utilise une annonce polie, non modale, dans l’éditeur de demande ; les échecs ordinaires gardent leur traitement d’erreur. + +**Serveurs OpenCode explicites :** questions et permissions arrivent uniquement en direct. Les brouillons restent modifiables. Les permissions obsolètes attendent une demande live courante ; les Forms connues proposent la vérification explicite ci-dessous. Le volet de détails du dock explique cette limite. Ouvrir une conversation permet de la consulter, sans récupérer automatiquement les demandes manquantes. Le mode Yolo fonctionne sur ces serveurs : après une reconnexion, CodeNomad relit les permissions en attente des seules conversations en Yolo et les approuve une fois. Les parcours de récupération et de reçus ci-dessous concernent le service local partagé. + +Pour une Form connue, choisissez **Vérifier l’état de ce formulaire** dans son éditeur source. Une Form vérifiée encore en attente active uniquement ses propres actions ; relisez le brouillon puis répondez ou annulez par un geste distinct. Une Form déjà répondue ou annulée conserve le brouillon consultable, sans afficher la réponse d'un autre client ni inventer son auteur ou le résultat de votre tentative. Une vérification indéterminée conserve l'édition et bloque les réponses ; vous pouvez la relancer explicitement. Chaque vérification est bornée à 10 secondes et 4 MiB par réponse ; un schéma de champs modifié reste aussi indéterminé. Aucun contrôle ni renvoi automatique. La couverture générale reste inconnue ; cette vérification ne retrouve ni Forms manquantes ni permissions. + Les questions, Forms et demandes d’autorisation natives se traitent dans le dock d’interruption juste au-dessus de la zone de saisie, pas dans les cartes d’outils en attente de la transcription. ## Trouver la demande et vérifier sa source {#request-dock} diff --git a/docs/help/fr/projects.md b/docs/help/fr/projects.md index e17ac9dd9a..07e83ee473 100644 --- a/docs/help/fr/projects.md +++ b/docs/help/fr/projects.md @@ -21,6 +21,16 @@ Les entrées récentes sont des raccourcis. **Renommer l'espace de travail** cha Un clic normal ouvre toujours l’accueil complet. Le lanceur est un raccourci, pas l’interface de gestion : renommez/retirez les projets récents et gérez les serveurs enregistrés depuis l’accueil. Échap ferme le lanceur et rend le focus à `+`. +## Ouvrir un projet sur un serveur OpenCode {#remote-project} + +1. Sur l'accueil ou dans le lanceur, dépliez **DISTANTS** puis choisissez **+ Projet** sur un serveur. Son nom reste visible à côté du chemin du dossier. +2. Choisissez un serveur, parcourez ses dossiers et choisissez **Ouvrir**. **Retour arrière** remonte au dossier parent ; **Échap** revient aux serveurs. +3. Pour ajouter un serveur, collez son lien `opencode pair`, ou `https://opencode:@hôte:port`, dans **Lien d'appairage ou adresse**. Clic droit sur un serveur (ou **Maj+F10**) pour **Supprimer le serveur enregistré**. + +L'onglet porte une icône de serveur et le dossier rejoint les projets récents. **Parcourir les dossiers**, **Cloner un depot Git** et les instances temporaires restent sur cet ordinateur. + +Le backend hôte conserve jetons d’appairage et mots de passe manuels entre les lancements dans son fichier privé `opencode-server-pairings.json` (0600), à côté de `config.yaml`. Expiration, HTTP 401, changement d’origine ou retrait du serveur effacent le secret. Les projets enregistrés se restaurent sur leur serveur ; ajout et retrait des serveurs sont réservés à l’hôte. + ## Fermer un onglet de projet {#close-stop} 1. Utilisez le bouton de fermeture de l’onglet ou **Fermer l'onglet** dans la palette de commandes (`Ctrl/Cmd+W` dans le moteur de rendu). diff --git a/docs/help/fr/providers.md b/docs/help/fr/providers.md index d2f39202e4..95be1f20e8 100644 --- a/docs/help/fr/providers.md +++ b/docs/help/fr/providers.md @@ -4,6 +4,8 @@ L’authentification des fournisseurs appartient au service OpenCode connecté, ## Connecter un fournisseur de modèles ou de recherche {#connect} +Vérifiez **Serveur OpenCode sélectionné**. Les paramètres de connexion, de comptes, de recherche web et d’images décrits ci-dessous s’appliquent au service local partagé. Un serveur explicitement indiqué et qualifié affiche uniquement un catalogue natif de fournisseurs et de modèles en lecture seule ; gérez son authentification et sa configuration directement sur ce serveur, hors des capacités actuelles de CodeNomad. Les contrôles des projets indisponibles restent inactifs ; les préférences CodeNomad restent accessibles. Sur le service local, les groupes **Modèles**, **Recherche web** et **Images** repliés attendent leur ouverture pour lire leurs données. + 1. Ouvrez un espace de travail, puis **Paramètres → Fournisseurs**. **Modèles** est déplié au départ ; dépliez **Recherche web** pour les fournisseurs de recherche. **Images** regroupe les réglages d'images. 2. Dans ce groupe, choisissez **Sélectionner un fournisseur**, puis **Connecter**. 3. Pour un fournisseur de modèles, effectuez la **Méthode d'authentification** native proposée : clé API, OAuth ou commande. Pour OAuth, utilisez **Ouvrir la page d'autorisation** et ne soumettez un code d’autorisation que si demandé. Les fournisseurs de recherche se connectent avec une clé API. diff --git a/docs/help/fr/security.md b/docs/help/fr/security.md index e4beed5856..1686461e64 100644 --- a/docs/help/fr/security.md +++ b/docs/help/fr/security.md @@ -1,5 +1,9 @@ # Authentification et sécurité +Choisir une pièce jointe la lit sur votre appareil ; envoyer le message transfère ses octets au serveur OpenCode du projet. Le service local partagé appartient à l’hôte d’exécution CodeNomad, qui peut différer de votre appareil. La lecture des médias différés borne la réponse serveur décompressée entière à 16 MiB avant analyse, erreurs comprises. Un dépassement, une annulation ou le retrait du projet/de la connexion fait échouer la lecture. Les dimensions d’image et la mémoire de décodage sont gérées par le navigateur ; les envois depuis l’appareil conservent leurs budgets propres. + +Le chat interne des serveurs explicites autorise les médias avant affichage ou téléchargement. Les URL d’images externes, images SVG/HTML actives et médias HTML intégrés sont refusés ; télécharger exige votre action et une lecture échouée reste en échec. La limite de 8 Mio par URI de données borne l’entrée encodée, séparément des dimensions décodées et des limites d’upload appareil. + L’accès à CodeNomad peut exécuter du travail sur l’hôte du backend via OpenCode. Traitez les mots de passe serveur, sessions navigateur et appareils appairés comme des identifiants puissants. CodeNomad n’est pas un bac à sable d’exécution multilocataire. ## Choisir l’authentification du serveur {#authentication} diff --git a/docs/help/fr/settings.md b/docs/help/fr/settings.md index 9e078b9ab3..c33fde5547 100644 --- a/docs/help/fr/settings.md +++ b/docs/help/fr/settings.md @@ -2,6 +2,8 @@ ## Ouvrir les paramètres et identifier leur portée {#open-settings} +**Serveur OpenCode sélectionné** identifie le contexte du projet (`local-shared` pour le service local partagé) ; les préférences CodeNomad restent communes. Un projet indisponible garde ses contrôles OpenCode inactifs. Les fichiers de configuration, variables d’environnement et opérations de maintenance OpenCode indiquent le **backend CodeNomad local** : fichiers HOME, environnement du profil et service partagé lui appartiennent. Lorsque **Gérer le backend local** est proposé, cette action ouvre explicitement ces contrôles locaux séparément du projet sélectionné. + 1. Ouvrez **Paramètres** avec l’engrenage **Ouvrir les paramètres** de la barre d’onglets (de la barre de titre dans l’application de bureau macOS) ou de l’accueil. Des raccourcis comme **Gérer les fournisseurs** dans le sélecteur de modèle, l’engrenage du panneau Missions ou l’engrenage **Paramètres** de l’historique des notifications ouvrent directement la section correspondante. 2. Sélectionnez une section. Les fenêtres locales Electron et Tauri ouvrent ou focalisent une unique fenêtre native Preferences ; les vues navigateur et distantes utilisent l’écran de paramètres intégré. 3. Vérifiez la portée du réglage et toute action **Enregistrer** avant de quitter. @@ -15,7 +17,9 @@ La plupart des choix s’appliquent immédiatement, y compris les préférences | Paramètres OpenCode Global/Projet | Changements de plugins/configuration natifs à la portée affichée. Les commandes Projet nécessitent un projet/une Location actif. | | Profil de données de bureau | Fenêtres natives, état de restauration et stockage navigateur, indépendamment du fichier de configuration et du service OpenCode partagé. Voir [Fenêtres de bureau et données](desktop.md). | -**Stats** couvre tout le service OpenCode connecté (tous les projets, clones indépendants et sous-sessions), pas seulement le dossier ouvert, sur les 7, 30, 90 ou 365 derniers jours. Il nécessite un projet ouvert et affiche les tokens et coûts enregistrés par OpenCode, pas les factures des fournisseurs ni les allocations d’abonnement ; les derniers totaux enregistrés peuvent s’afficher pendant l’actualisation. Les quotas de forfait relèvent de la section Statut **Utilisation**. +Les serveurs explicitement indiqués et qualifiés proposent un catalogue de fournisseurs et de modèles en lecture seule. Les sections différées restent sélectionnables et expliquent leur limitation ; gérez ces paramètres directement sur le serveur. + +**Stats** couvre tout le service OpenCode local partagé (tous les projets, clones indépendants et sous-sessions), pas seulement le dossier ouvert, sur les 7, 30, 90 ou 365 derniers jours. Il nécessite un projet ouvert et affiche les tokens et coûts enregistrés par OpenCode, pas les factures des fournisseurs ni les allocations d’abonnement ; les derniers totaux enregistrés peuvent s’afficher pendant l’actualisation. Les quotas de forfait relèvent de la section Statut **Utilisation**. **Stats** est indisponible pour les serveurs explicitement indiqués ; sa section en explique la raison. Changer les préférences d’affichage ne redémarre pas OpenCode et ne rejoue pas de prompt. Configuration native, maintenance du service et identifiants ont des effets distincts : voir [Configuration d’OpenCode](opencode.md), [Fournisseurs](providers.md) et [Intégrations](integrations.md). @@ -42,6 +46,8 @@ Les [intégrations](integrations.md#integration-sections) reconnues ont aussi le Statut inclut les informations de tokens, le mode Yolo, l’utilisation fournisseur, les shells en arrière-plan, MCP et Plugins. Tant que la conversation a un [objectif](conversations.md#goal), une ligne d’objectif au-dessus de ces sections l’affiche ; cette ligne n’est pas une section et ne peut être ni masquée ni déplacée. Masquer une section ne désactive pas son service et ne révoque pas de permissions. Les dispositions étroites ferment les panneaux qui ne tiennent plus au lieu de comprimer la conversation ; un panneau ouvert alors flotte au-dessus d’elle, et ouvrir un panneau flottant ferme l’autre. +Pour un projet sur un serveur OpenCode configuré, ces sections lisent ce serveur. **Utilisation** affiche les quotas natifs OpenCode Go et l’estimation Zen sans identifiants décrite dans [Fournisseurs](providers.md#usage) ; les autres fournisseurs n’affichent aucun quota. **Plugins** liste les plugins du serveur avec leur état ; leurs interrupteurs restent en lecture seule, car OpenCode n’offre aucune API pour modifier la configuration des plugins du serveur. Les serveurs MCP peuvent toujours être connectés ou déconnectés. **Shells en arrière-plan** liste et arrête les shells du serveur pour le dossier ouvert. + La disposition intégrée est propre à la fenêtre, pas une modification du projet. Les cases d’extension sont différentes : elles activent du code dans tous les projets utilisant la configuration. **Réinitialiser** ne change pas le consentement aux extensions. Voir [Extensions de panneau](extensions.md). ## Détail de transcription et taille de saisie {#transcript-composer} diff --git a/docs/help/fr/troubleshooting.md b/docs/help/fr/troubleshooting.md index 524e816e4a..0aff64a3d6 100644 --- a/docs/help/fr/troubleshooting.md +++ b/docs/help/fr/troubleshooting.md @@ -1,5 +1,9 @@ # Dépannage +Pour des serveurs d’exécution homonymes, utilisez l’ID stable affiché avec le nom dans les détails de demande et les notifications de projet. Une réponse incertaine reste dans son éditeur d’origine, sans déplacement du focus ni renvoi automatique. + +**Serveurs OpenCode explicites :** après une coupure ou un redémarrage du backend, la couverture des demandes en attente est inconnue, même si le dock est vide. Conservez les brouillons connus ; les permissions obsolètes attendent une demande live courante. Pour une Form connue, utilisez **Vérifier l’état de ce formulaire** dans son éditeur source ; un résultat indéterminé garde les réponses bloquées et permet une nouvelle vérification explicite. La vérification est bornée à 10 secondes et 4 MiB par réponse ; la couverture reste inconnue. Ouvrir la conversation permet de consulter son contenu sans retrouver automatiquement les demandes manquantes. Une réponse envoyée avant la coupure peut avoir abouti : aucun rejeu automatique. Les étapes de récupération automatique ci-dessous concernent le service local partagé. Voir [Questions et autorisations](permissions.md). + Pour récupérer, vérifiez d’abord le propriétaire de l’opération défaillante : navigateur, backend CodeNomad, service OpenCode ou fournisseur. Une réponse perdue ne prouve pas l’échec d’une modification ; relisez l’état actuel avant de la répéter. ## Problèmes de lancement sur ordinateur {#desktop-launch} diff --git a/docs/help/he/browser-sidecars.md b/docs/help/he/browser-sidecars.md index ae19019e59..2c09200baf 100644 --- a/docs/help/he/browser-sidecars.md +++ b/docs/help/he/browser-sidecars.md @@ -1,5 +1,7 @@ # תצוגות דפדפן ו־SideCars +קישורים בצ׳אט הפנימי של שרתים מפורשים נשארים קישורים חיצוניים שנפתחים בפעולה שלך, כולל כתובות loopback. הם שומרים את הכתובת כפי שנכתבה ומשתמשים בהקשר הרשת של הדפדפן שלך. תצוגות מקדימות של המארח אינן זמינות בצ׳אט הזה; לא מסופקת מנהרה לשרת הביצוע. + ## פתיחת דפדפן לסשן {#session-browser} 1. בסרגל הכלים של שיחה, בחרו **פתח תצוגה מקדימה של אתר**. diff --git a/docs/help/he/conversations.md b/docs/help/he/conversations.md index 9b16ab9220..de3f445417 100644 --- a/docs/help/he/conversations.md +++ b/docs/help/he/conversations.md @@ -1,11 +1,17 @@ # שיחות +הצ׳אט של שרתים מפורשים מציג תמונות מוטמעות נתמכות או מדיה מקורית מאומתת של אותה שיחה. מקורות אחרים מציגים הודעת אי־זמינות. נתיבים מקומיים מוצאים רק תמונות שכבר מוחזקות בשיחה הזאת; `/btw` מקבל רק תמונות מוטמעות. קבצים מוטמעים תקינים מציעים הורדה מפורשת. + CodeNomad מציג סשנים מקוריים של OpenCode כשיחות, עם היררכיה לעבודה מואצלת ופקדים נפרדים למה שתשלחו בהמשך. הודעות מציגות Markdown, קוד, הבדלים ותמונות נתמכות מתוצאות כלים. העתקת טקסט, חיפוש בהיסטוריה המלאה ודיבור משתמשים בהיטלי טקסט, לא בבתי תמונה מוטמעים. **תוכן ההודעות** משנה נראות בלי למחוק חלקים שמורים; [היסטוריה](history.md#operation-reference) מבחין בין פקדי תצוגה לניקוי. כותרות החשיבה והכלים מציגות כמה זמן נמשך כל שלב, בספירה חיה בזמן שהוא רץ; משכים של פחות משנייה אינם מוצגים. כאשר **טוקנים** מוצג ב־**תוכן ההודעות** (התבנית **הכול** מציגה אותו), כל הודעת סוכן מסתיימת בשורת טוקנים ועלות אחת אחרי הטקסט הסופי שלה. שורה זו מסכמת את ההודעה ואת ההודעות המכילות את הכלים והחשיבה שהפעולה **הסר כלים וחשיבה מהתשובה הזו** שלה מכסה, בתוך התמליל הטעון; הרחיבו אותה לספירות החשיבה והמטמון. לשלבים שרק הריצו כלים אין שורה משלהם. +בצ׳אט הפנימי עם שרת מפורש, `@` מציע את הסוכנים והמיומנויות של השרת ומסביר שהפניות לקובצי הפרויקט אינן זמינות. שינוי חיבור במהלך פעולה עוצר את שלביה הנותרים. בדקו את השיחה לפני שליחה חוזרת של פעולה שתוצאתה אינה ודאית: ייתכן שהיא כבר הגיעה ל־OpenCode. + +פעולה שנקטעה או שתוצאתה אינה ודאית משאירה הודעה לא מודאלית בשיחת המקור ושומרת על המיקוד הנוכחי. אם עריכת הודעה בתור נקטעת, התוכן הידוע נשאר זמין לשחזור בשיחת המקור הפתוחה: בדקו את התור, רוקנו את הטיוטה והקבצים המצורפים ובחרו **שחזור הודעה שמורה**. כך משוחזרת טיוטה לעריכה; השליחה היא פעולה נפרדת. שאלת `/btw` שהתיישנה מאפשרת בקשה חדשה ומפורשת לאחר סיום הבקשה הישנה. + ## איתור שיחות וניווט ביניהן {#navigate-conversations} 1. בחרו שורה תחת **סשנים**, או השתמשו ב־**סשן חדש** להתחלת שיחת הורה. diff --git a/docs/help/he/extensions.md b/docs/help/he/extensions.md index dbf06a7f03..805c1624cd 100644 --- a/docs/help/he/extensions.md +++ b/docs/help/he/extensions.md @@ -43,6 +43,8 @@ ## הקשר, הסכמה לנכסים ומגבלות ארגז החול {#permissions-sandbox} +פריטי המאגר של API 3 זמינים רק לפרויקטים המשתמשים בשירות OpenCode המקומי המשותף. הם אינם זמינים בכל שרת OpenCode שהוגדר במפורש, כולל שרתי loopback ויעדים מנותקים, ללא תלות בתמיכת Git המובנית שלו; הבקשה נדחית לפני גישה ל-Git במארח, להתחברויות לפלטפורמות אירוח קוד או לרשת. + | חוזה | מה ההפעלה מתירה | | --- | --- | | API 1 / `session.context` | מזהה הסשן הנוכחי (או ללא מזהה), שפת הממשק והמראה. ללא טקסט תמליל או גישה למערכת הקבצים. | diff --git a/docs/help/he/files.md b/docs/help/he/files.md index b453087048..1f82a8ddc6 100644 --- a/docs/help/he/files.md +++ b/docs/help/he/files.md @@ -19,6 +19,10 @@ פעולות שורה כוללות **העתק נתיב**, וכשהלקוח תומך בפתיחת נתיבי שרת קצה, פעולות מנהל קבצים/עורך/מסוף כגון **פתיחה באמצעות יישום ברירת המחדל**, **הצגה בתיקייה**, **פתיחה במנהל הקבצים** ו־**פתיחת מסוף כאן**. פעולות עשויות לעבור ל־**פעולות נוספות עבור {name}** כשהמקום מוגבל; שם הקובץ או התיקייה מחליף את `{name}`. דפדפן מרוחק אינו יכול להניח שנתיב שרת הוא נתיב מקומי למכשיר; ראו [שליטה מרחוק](remote-control.md). +### פרויקטים בשרת OpenCode {#opencode-server-files} + +בפרויקט שנפתח בשרת OpenCode מוגדר, **קבצים** קורא מהשרת הזה דרך ה־API של OpenCode שלו, ולעולם לא מהדיסק או מ־Git של המחשב הזה. **סביבת עבודה** מציגה את התיקייה הפתוחה ותצוגה מקדימה שלה לקריאה בלבד (ללא **שמור**; תצוגות מקדימות נעצרות ב־5 MiB). **שינויים** מציג את שינויי עותק העבודה של התיקייה הפתוחה והענף שלה ברשימת **שינויים** אחת, ללא staging, ‏commit, **קומיטים** או **אתחול Git**. כשהשרת אינו יכול לדווח על מצב שלם וחד־משמעי, הלוח מציג **התוכן אינו זמין או חלקי.** במקום רשימה ריקה. השתמשו ב־**רענן** אחרי שהסוכן משנה קבצים; הלוח מתרענן גם כשהשרת מדווח על שינויים בקבצים או בענף. פעולות פתיחה במחשב הזה נשארות לא זמינות. + ## עריכת מקור ושמירה בטוחה {#edit-save} 1. פתחו קובץ טקסט מסביבת העבודה בפעולת העין שלו. diff --git a/docs/help/he/history.md b/docs/help/he/history.md index 0c391f06dc..b737811c43 100644 --- a/docs/help/he/history.md +++ b/docs/help/he/history.md @@ -2,6 +2,8 @@ ההיסטוריה השמורה, מה שהתמליל מציג כרגע וההקשר המסוכם של המודל הם דברים נפרדים. בחרו בניווט או בסינון לפני מחיקת דבר כלשהו. +תהליכי ההיסטוריה המורחבת האלה חלים על שירות OpenCode המקומי המשותף. פרויקטים בשרתים מפורשים משתמשים בדפים מקוריים ובציר זמן של הודעות שנטענו, שומרים את מיקום הקריאה כשקטע אינו זמין ומציעים מעבר מפורש לדף האחרון. חיפוש בטקסט, תצוגות מקדימות של הודעות שלא נטענו וניקוי טכני נשארים בלתי זמינים שם; תצוגות מקדימות של טקסט שכבר נטען נשארות זמינות. + ## חיפוש בהיסטוריה המלאה {#full-history-search} 1. פתחו **חפש בהיסטוריית הצ'אט** בכותרת השיחה, או השתמשו בקיצור המוגדר שלו (ברירת מחדל **Ctrl/Cmd+F**). diff --git a/docs/help/he/integrations.md b/docs/help/he/integrations.md index 794dab84f9..cef44561cb 100644 --- a/docs/help/he/integrations.md +++ b/docs/help/he/integrations.md @@ -1,5 +1,7 @@ # שילובים מקוריים +פקדי ההתקנה, החיבור ליישום והתצורה להלן חלים על פרויקטי OpenCode מקומיים משותפים. בשרתים מפורשים נשארים מלאי התוספים ומצב השילובים לקריאה בלבד; חיבור ליישום והתקנה אינם זמינים שם. + CodeNomad מציג את חיבורי MCP, הפעלת התוספים, המיומנויות והפקודות המותאמות המקוריים של OpenCode. אלה רצים במארח ההרצה. הם נפרדים מ־[הרחבות לוח](extensions.md) מוגבלות בארגז חול ומ־[SideCars](browser-sidecars.md). ## בחירת הפקד המתאים {#integration-scopes} diff --git a/docs/help/he/permissions.md b/docs/help/he/permissions.md index 7ea9b09d18..74485983c6 100644 --- a/docs/help/he/permissions.md +++ b/docs/help/he/permissions.md @@ -1,5 +1,11 @@ # שאלות ואישורים +ההקשר של שרת שהוגדר במפורש כולל שם ומזהה יציב, כדי להבחין בין שמות זהים. תשובה שתוצאתה לא ודאית או שהוחלפה מוצגת בהודעה מנומסת ולא מודאלית בעורך הבקשה; כשלים רגילים שומרים על תצוגת השגיאה שלהם. + +**שרתי OpenCode שהוגדרו במפורש:** שאלות ובקשות הרשאה מגיעות בשידור חי בלבד. הטיוטות נשארות ניתנות לעריכה. הרשאות מיושנות ממתינות לבקשה חיה עדכנית; לטפסים מוכרים יש בדיקה מפורשת כמפורט להלן. הפרטים הנפתחים באזור הבקשות מסבירים את המגבלה. פתיחת שיחה מאפשרת לעיין בה בלי לשחזר אוטומטית בקשות חסרות. מצב Yolo פועל בשרתים האלה: אחרי חיבור מחדש, CodeNomad קורא שוב את ההרשאות הממתינות של שיחות Yolo בלבד ומאשר אותן פעם אחת. תהליכי השחזור והקבלות שלהלן חלים על השירות המקומי המשותף. + +בטופס מוכר בחרו **בדיקת מצב הטופס הזה** בעורך המקורי. טופס מאומת שעדיין ממתין מפעיל רק את פעולות המענה והביטול שלו; בדקו את הטיוטה ואז פעלו במחווה נפרדת. טופס שנענה או בוטל שומר את הטיוטה לעיון, בלי להציג תשובה של לקוח אחר או להמציא משיב או תוצאה לניסיון הקודם. בדיקה שלא הוכרעה משאירה עריכה זמינה ומענה חסום; אפשר לבדוק שוב במפורש. כל בדיקה מוגבלת ל־10 שניות ול־4 MiB לכל תגובה; שינוי במבנה השדות נשאר לא מוכרע. אין בדיקה או שליחה חוזרת אוטומטית. הכיסוי הכולל נשאר לא ידוע; הבדיקה אינה מוצאת טפסים או הרשאות חסרים. + לשאלות, לטפסים ולבקשות אישור מקוריים עונים באזור הבקשות מיד מעל שדה הקלט, לא בתוך כרטיסי כלים ממתינים בתמליל. ## איתור הבקשה ובדיקת מקורה {#request-dock} diff --git a/docs/help/he/projects.md b/docs/help/he/projects.md index 3c52a50657..362b794d10 100644 --- a/docs/help/he/projects.md +++ b/docs/help/he/projects.md @@ -21,6 +21,16 @@ לחיצה רגילה עדיין פותחת את דף הבית המלא. המשגר הוא קיצור דרך, לא ממשק הניהול: שנו שמות/הסירו פרויקטים אחרונים ונהלו סימניות שרתים בדף הבית. Escape סוגר את המשגר ומחזיר מיקוד ל־`+`. +## פתיחת פרויקט בשרת OpenCode {#remote-project} + +1. בדף הבית או במפעיל, הרחיבו את **מרוחקים** ובחרו **+ פרויקט** בשרת. שמו נשאר גלוי לצד נתיב התיקייה. +2. בחרו שרת, עיינו בתיקיות שלו ובחרו **פתח**. **Backspace** עובר לתיקיית האב; **Esc** חוזר לרשימת השרתים. +3. כדי להוסיף שרת, הדביקו את קישור `opencode pair` שלו, או `https://opencode:@host:port`, בשדה **קישור צימוד או כתובת**. לחיצה ימנית על שרת (או **Shift+F10**) מציגה את **הסר שרת שמור**. + +הלשונית מסומנת בסמל שרת והתיקייה מצטרפת לפרויקטים האחרונים. **עיון בתיקיות**, **שכפל מאגר Git** ומופעים זמניים נשארים במחשב זה. + +מארח ה־backend שומר אסימוני צימוד וסיסמאות ידניות בין הפעלות בקובץ הפרטי `opencode-server-pairings.json` (0600), ליד `config.yaml`. תפוגה, HTTP 401, שינוי מקור או הסרת שרת מוחקים את הסוד. פרויקטים שמורים משוחזרים בשרת שלהם; רק המארח מוסיף ומסיר שרתים. + ## סגירת לשונית פרויקט {#close-stop} 1. השתמשו בכפתור הסגירה של הלשונית או ב־**סגור לשונית** בלוח הפקודות (`Ctrl/Cmd+W` בתהליך התצוגה). diff --git a/docs/help/he/providers.md b/docs/help/he/providers.md index 66a8a3f26d..d4bd77a77a 100644 --- a/docs/help/he/providers.md +++ b/docs/help/he/providers.md @@ -4,6 +4,8 @@ ## חיבור ספק מודלים או חיפוש {#connect} +בדקו את **שרת OpenCode שנבחר**. הגדרות החיבור, החשבונות, החיפוש ברשת והתמונות המתוארות להלן חלות על השירות המקומי המשותף. שרת שהוגדר במפורש ונמצא מתאים מציג רק קטלוג מובנה של ספקים ומודלים לקריאה בלבד; נהלו את האימות והתצורה שלו ישירות בשרת, מחוץ ליכולות הנוכחיות של CodeNomad. בפרויקטים שאינם זמינים הפקדים נשארים לא פעילים; העדפות CodeNomad נשארות זמינות. בשירות המקומי, הקבוצות המקופלות **מודלים**, **חיפוש ברשת** ו**תמונות** דוחות את קריאת הנתונים עד להרחבתן. + 1. פתחו סביבת עבודה, ואז **הגדרות → ספקים**. **מודלים** מתחיל מורחב; הרחיבו את **חיפוש ברשת** עבור ספקי חיפוש. **תמונות** מרכז את הגדרות התמונות. 2. באותה קבוצה, בחרו **בחר ספק**, ואז **התחבר**. 3. לספק מודלים, השלימו את **שיטת אימות** המקורית המוצעת: מפתח API, OAuth או פקודה. ל־OAuth, השתמשו ב־**פתח דף הרשאה** ושלחו קוד הרשאה רק כשמתבקשים. ספקי חיפוש מתחברים באמצעות מפתח API. diff --git a/docs/help/he/security.md b/docs/help/he/security.md index 5aa882d7bf..e4a7861ab9 100644 --- a/docs/help/he/security.md +++ b/docs/help/he/security.md @@ -1,5 +1,9 @@ # אימות ואבטחה +בחירת קובץ מצורף קוראת אותו במכשיר שלך; שליחת ההודעה מעבירה את הבתים שלו לשרת OpenCode של הפרויקט. השירות המקומי המשותף שייך למארח ההרצה של CodeNomad, שעשוי להיות שונה מהמכשיר שלך. קריאת מדיה מגבילה את כל תשובת השרת לאחר פריסה ל־16 MiB לפני הפענוח, כולל שגיאות. חריגה, ביטול או ביטול סמכות הפרויקט או החיבור מכשילים את הקריאה. ממדי התמונות וזיכרון פענוח התמונות מנוהלים על ידי הדפדפן; להעלאות מהמכשיר נשארים תקציבים נפרדים. + +הצ׳אט הפנימי של שרתים מפורשים מאשר מדיה לפני הצגה או הורדה. כתובות תמונה חיצוניות, תמונות SVG/HTML פעילות ומדיה מוטמעת ב־HTML נדחות; הורדות דורשות פעולה שלך וקריאה שנכשלה נשארת כושלת. מגבלת 8 MiB לכל URI נתונים מגבילה את הקלט המקודד בנפרד מממדי התמונה המפוענחת וממגבלות העלאה מהמכשיר. + גישה ל־CodeNomad יכולה להריץ עבודה במארח שרת הקצה באמצעות OpenCode. התייחסו לסיסמאות שרת, לסשנים בדפדפן ולמכשירים מצומדים כאל אישורי גישה רבי עוצמה. CodeNomad אינו ארגז חול להרצה מרובת דיירים. ## בחירת אופן אימות השרת {#authentication} diff --git a/docs/help/he/settings.md b/docs/help/he/settings.md index 660fad9e1a..2f0049e9f7 100644 --- a/docs/help/he/settings.md +++ b/docs/help/he/settings.md @@ -2,6 +2,8 @@ ## פתיחת הגדרות וזיהוי ההיקף {#open-settings} +**שרת OpenCode שנבחר** מזהה את הקשר הפרויקט (`local-shared` לשירות המקומי המשותף); העדפות CodeNomad נשארות משותפות. בפרויקט לא זמין פקדי OpenCode נשארים לא פעילים. קובצי תצורה, משתני סביבה ותחזוקת OpenCode מציינים את **שרת CodeNomad המקומי**: קובצי HOME, סביבת הפרופיל והשירות המשותף שייכים אליו. **ניהול השרת המקומי** פותח במפורש את הפקדים המקומיים בנפרד מהפרויקט שנבחר. + 1. פתחו **הגדרות** באמצעות גלגל השיניים **פתח הגדרות** בסרגל הלשוניות (בסרגל הכותרת באפליקציית שולחן העבודה ב־macOS) או בדף הבית. קיצורי דרך כגון **נהל ספקים** בבורר המודלים, גלגל השיניים של לוח המשימות או גלגל השיניים **הגדרות** בהיסטוריית ההתראות פותחים ישירות את הסעיף המתאים. 2. בחרו סעיף. חלונות Electron ו־Tauri מקומיים פותחים או ממקדים חלון העדפות מקורי אחד; דפדפן ותצוגות מרוחקות משתמשים במסך ההגדרות המוטמע. 3. בדקו את היקף ההגדרה וכל פעולת **שמור** לפני עזיבה. @@ -15,7 +17,9 @@ | הגדרות OpenCode כלליות/של פרויקט | שינויים בתוספים/בתצורה המקורית בהיקף המוצג. פקדי פרויקט דורשים פרויקט/Location פעיל. | | פרופיל נתונים לשולחן העבודה | חלונות מקוריים, מצב שחזור ואחסון דפדפן, בנפרד מקובץ התצורה ומשירות OpenCode המשותף. ראו [חלונות ונתונים בשולחן העבודה](desktop.md). | -**סטטיסטיקות** מכסה את כל שירות OpenCode המחובר (כל הפרויקטים, שכפולים עצמאיים ותתי־סשנים), לא רק את התיקייה הפתוחה, עבור 7, 30, 90 או 365 הימים האחרונים. הסעיף דורש פרויקט פתוח ומציג את הטוקנים והעלות ש־OpenCode תיעד, לא חשבוניות של ספקים או הקצאות מנוי; סכומים שמורים קודמים עשויים להופיע בזמן הרענון. מכסות תוכניות שייכות לסעיף הסטטוס **שימוש**. +שרתים שהוגדרו במפורש ונמצאו מתאימים מציגים קטלוג ספקים ומודלים לקריאה בלבד. הסעיפים שנדחו נשארים ניתנים לבחירה ומסבירים את המגבלה שלהם; נהלו את הגדרות השרת האלה ישירות בשרת. + +**סטטיסטיקות** מכסה את כל שירות OpenCode המקומי המשותף (כל הפרויקטים, שכפולים עצמאיים ותתי־סשנים), לא רק את התיקייה הפתוחה, עבור 7, 30, 90 או 365 הימים האחרונים. הסעיף דורש פרויקט פתוח ומציג את הטוקנים והעלות ש־OpenCode תיעד, לא חשבוניות של ספקים או הקצאות מנוי; סכומים שמורים קודמים עשויים להופיע בזמן הרענון. מכסות תוכניות שייכות לסעיף הסטטוס **שימוש**. **סטטיסטיקות** אינה זמינה לשרתים שהוגדרו במפורש; הסעיף מסביר מדוע. שינוי העדפות תצוגה אינו מפעיל מחדש את OpenCode או שולח קלט שוב. לתצורה מקורית, לתחזוקת שירות ולפרטי התחברות השפעות נפרדות: ראו [הגדרת OpenCode](opencode.md), [ספקים](providers.md) ו־[שילובים](integrations.md). @@ -42,6 +46,8 @@ הסטטוס כולל פרטי טוקנים, מצב Yolo, שימוש אצל ספקים, מעטפות רקע, MCP ותוספים. כל עוד לשיחה יש [יעד](conversations.md#goal), שורת יעד מעל הסעיפים האלה מציגה אותו; שורה זו אינה סעיף ואי אפשר להסתיר או להזיז אותה. הסתרת סעיף אינה משביתה את השירות שלו או מבטלת הרשאות. פריסות צרות סוגרות לוחות שכבר אינם נכנסים במקום לדחוק את השיחה; לוח שנפתח בהן צף מעליה, ופתיחת לוח צף אחד סוגרת את האחר. +בפרויקט בשרת OpenCode מוגדר, הסעיפים האלה קוראים מהשרת הזה. **שימוש** מציג מכסות מקוריות של OpenCode Go ואת אומדן Zen ללא פרטי התחברות המתואר ב[ספקים](providers.md#usage); ספקים אחרים אינם מציגים מכסה. **תוספים** מציג את התוספים של השרת ואת מצבם; המתגים שלהם נשארים לקריאה בלבד כי OpenCode אינו מציע API לשינוי תצורת התוספים של השרת. עדיין אפשר לחבר או לנתק שרתי MCP. **מעטפות רקע** מציג ועוצר את המעטפות של השרת עבור התיקייה הפתוחה. + פריסה מובנית היא פריסת חלון, לא שינוי בפרויקט. תיבות הסימון של הרחבות שונות: הן מפעילות קוד בכל הפרויקטים המשתמשים בתצורה. **איפוס** אינו משנה הסכמה להרחבות. ראו [הרחבות לוח](extensions.md). ## פירוט התמליל וגודל שדה הקלט {#transcript-composer} diff --git a/docs/help/he/troubleshooting.md b/docs/help/he/troubleshooting.md index 25efb86f0a..eed28066c3 100644 --- a/docs/help/he/troubleshooting.md +++ b/docs/help/he/troubleshooting.md @@ -1,5 +1,9 @@ # פתרון בעיות +כדי להבחין בין שרתי ביצוע בעלי שם זהה, השתמשו במזהה היציב שמופיע לצד השם בפרטי הבקשה ובהתראות הפרויקט. תשובה לא ודאית נשארת בעורך המקורי בלי להעביר את המיקוד או להישלח שוב אוטומטית. + +**שרתי OpenCode שהוגדרו במפורש:** אחרי ניתוק או הפעלה מחדש של שרת התיווך, כיסוי הבקשות הממתינות אינו ידוע, גם כשאזור הבקשות ריק. שמרו על הטיוטות; הרשאות מיושנות ממתינות לבקשה חיה עדכנית. בטופס מוכר בחרו **בדיקת מצב הטופס הזה** בעורך המקורי; תוצאה שלא הוכרעה משאירה מענה חסום ומאפשרת בדיקה מפורשת נוספת. הגבול הוא 10 שניות בסך הכול ו־4 MiB לכל תגובה; הכיסוי נשאר לא ידוע. פתיחת שיחה מציגה את תוכנה בלי למצוא בקשות חסרות אוטומטית. תשובה שנשלחה לפני הניתוק עשויה להתקבל; אין שליחה חוזרת אוטומטית. השחזור האוטומטי שלהלן חל על השירות המקומי המשותף. ראו [שאלות ואישורים](permissions.md). + התאוששו באמצעות בדיקה תחילה של הגורם האחראי לפעולה שנכשלה: הדפדפן, שרת הקצה של CodeNomad, שירות OpenCode או הספק. תשובה שאבדה אינה מוכיחה שפעולת שינוי נכשלה; קראו מחדש את המצב הנוכחי לפני חזרה עליה. ## בעיות הפעלה בשולחן העבודה {#desktop-launch} diff --git a/docs/help/ja/browser-sidecars.md b/docs/help/ja/browser-sidecars.md index 97ba7e449c..f2665e8bde 100644 --- a/docs/help/ja/browser-sidecars.md +++ b/docs/help/ja/browser-sidecars.md @@ -1,5 +1,7 @@ # ブラウザープレビューと SideCar +明示的サーバーの内部チャットのリンクは、ループバック URL を含め、利用者の操作で開く外部リンクのままです。記載されたアドレスを保持し、ブラウザーのネットワーク環境を使います。このチャットではホストプレビューは利用できず、実行サーバーへのトンネルも提供されません。 + ## セッションのブラウザーを開く {#session-browser} 1. 会話のツールバーで **Web プレビューを開く** を選びます。 diff --git a/docs/help/ja/conversations.md b/docs/help/ja/conversations.md index c633aa495c..b664c54789 100644 --- a/docs/help/ja/conversations.md +++ b/docs/help/ja/conversations.md @@ -1,11 +1,17 @@ # 会話 +明示的サーバーのチャットでは、対応する埋め込み画像と同じ会話の検証済みネイティブメディアを表示します。他のソースには利用不可の表示が出ます。ローカルパスは、その会話ですでに保持している画像だけに解決できます。`/btw` は埋め込み画像のみ受け付けます。有効な埋め込みファイルは明示的な操作でダウンロードできます。 + CodeNomad は、OpenCode ネイティブのセッションを会話として表示し、委任した作業の階層と、次に送信する内容のための個別のコントロールを提供します。 メッセージは Markdown、コード、差分、対応するツール結果の画像を表示します。テキストのコピー、全履歴検索、音声は、埋め込まれた画像のバイト列ではなく、テキストとしての表現を使用します。**メッセージの内容** は、保存されたパーツを削除せずに表示を変えます。[履歴](history.md#operation-reference)では、表示の操作とクリーンアップの違いを説明しています。 推論とツールのヘッダーには各ステップの所要時間が表示され、実行中はリアルタイムで増えていきます。1 秒未満の所要時間は表示されません。**メッセージの内容** で **トークン** を表示している場合(プリセット **すべて** では表示されます)、各エージェントメッセージの最後のテキストの後に、トークンとコストの行が 1 つ付きます。この行は、そのメッセージと、その **この回答からツールと推論を削除** 操作の対象となるツールと推論を含むメッセージを、読み込まれた会話記録の範囲で合計したものです。展開すると推論とキャッシュの数を確認できます。ツールを実行しただけのステップには、独自の行はありません。 +明示サーバー向けの内部チャットでは、`@` でそのサーバーのエージェントとスキルを選べ、プロジェクトファイルの参照が利用できない旨が表示されます。操作中に接続が変わると、残りの手順は停止します。結果が不明な操作は、OpenCode に届いている可能性があるため、再送前に会話を確認してください。 + +中断された操作や結果が不明な操作は、元の会話に非モーダルの通知を残し、現在のフォーカスを維持します。待機中メッセージの編集が中断された場合、既知の内容は開いている元の会話で復元できます。キューを確認し、下書きと添付を空にして、**保存したメッセージを復元**を選択してください。編集可能な下書きが復元され、送信は別の操作です。無効になった `/btw` の質問は、古いリクエストが完了すると、明示的に新しい質問を送れます。 + ## 会話を探して移動する {#navigate-conversations} 1. **セッション** の行を選ぶか、**新しいセッション** で親会話を開始します。 diff --git a/docs/help/ja/extensions.md b/docs/help/ja/extensions.md index befc94732c..e3bc2d7f2e 100644 --- a/docs/help/ja/extensions.md +++ b/docs/help/ja/extensions.md @@ -43,6 +43,8 @@ ## コンテキスト、資産への同意、サンドボックスの制限 {#permissions-sandbox} +API 3 のリポジトリ項目は、共有ローカル OpenCode サービスを使うプロジェクトでのみ利用できます。明示的に設定されたすべての OpenCode サーバーでは、ループバックや切断中の接続先を含め、ネイティブの Git 対応状況にかかわらず利用できません。ホストの Git、フォージへのサインイン、ネットワークにアクセスする前に拒否されます。 + | 契約 | 有効化で許可するもの | | --- | --- | | API 1 / `session.context` | 現在のセッション識別子(またはなし)、UI 言語、外観。会話テキストやファイルシステムアクセスはありません。 | diff --git a/docs/help/ja/files.md b/docs/help/ja/files.md index 405b43f255..6a91270ac9 100644 --- a/docs/help/ja/files.md +++ b/docs/help/ja/files.md @@ -19,6 +19,10 @@ 行の操作には **パスをコピー** があり、バックエンドのパスを開くことにクライアントが対応している場合は、**既定のアプリケーションで開く**、**フォルダーに表示**、**ファイルマネージャーで開く**、**ここでターミナルを開く** などもあります。領域が限られると、操作は **{name}のその他の操作** に移る場合があります。`{name}` にはファイル名またはフォルダー名が入ります。リモートブラウザーは、サーバーパスを端末ローカルのパスとみなせません。[リモートコントロール](remote-control.md)を参照してください。 +### OpenCode サーバー上のプロジェクト {#opencode-server-files} + +設定済みの OpenCode サーバーで開いたプロジェクトでは、**ファイル** はそのサーバーを OpenCode API 経由で読み取り、このコンピューターのディスクや Git は読み取りません。**ワークスペース** は開いたフォルダーを読み取り専用で一覧表示・プレビューします(**保存** はなく、プレビューは 5 MiB までです)。**変更** は開いたフォルダーとそのブランチの作業コピーの変更を 1 つの **変更** リストに表示し、ステージ、コミット操作、**コミット**、**Git を初期化** はありません。サーバーが完全で曖昧さのない状態を報告できない場合、パネルは空のリストではなく **内容を取得できないか、不完全です。** を表示します。エージェントがファイルを変更した後は **更新** を使ってください。サーバーがファイルやブランチの変更を報告したときもパネルは更新されます。このコンピューターで開く操作は引き続き利用できません。 + ## ソースを編集して安全に保存する {#edit-save} 1. ワークスペースのテキストファイルを目の操作で開きます。 diff --git a/docs/help/ja/history.md b/docs/help/ja/history.md index 1a706f9923..c746876416 100644 --- a/docs/help/ja/history.md +++ b/docs/help/ja/history.md @@ -2,6 +2,8 @@ 保存された履歴、会話欄に現在表示されている内容、モデルのコンパクト化されたコンテキストは別物です。何かを削除する前に、移動やフィルターを選んでください。 +以下の拡張履歴機能は共有ローカル OpenCode サービスが対象です。明示的サーバーのプロジェクトでは、ネイティブページと読み込み済みメッセージのタイムラインを使用し、箇所を開けない場合も保存した読書位置を保持して最新ページへの明示的な移動を提供します。全文検索、未読み込みメッセージのプレビュー、技術的内容の削除は利用できませんが、読み込み済みテキストのプレビューは利用できます。 + ## 全履歴を検索する {#full-history-search} 1. 会話ヘッダーの **チャット履歴を検索** を開くか、設定したショートカット(既定は **Ctrl/Cmd+F**)を使用します。 diff --git a/docs/help/ja/integrations.md b/docs/help/ja/integrations.md index dd1d43b277..d8f2e72407 100644 --- a/docs/help/ja/integrations.md +++ b/docs/help/ja/integrations.md @@ -1,5 +1,7 @@ # ネイティブ連携 +以下のインストール、アプリケーション接続、設定の操作は、共有ローカル OpenCode プロジェクトが対象です。明示的サーバーではプラグイン一覧と連携状態を読み取り専用で表示し、接続とインストールの操作は利用できません。 + CodeNomad は、OpenCode ネイティブの MCP 接続、プラグイン有効化、スキル、カスタムコマンドを提供します。これらは実行ホスト上で動きます。サンドボックス化された[パネル拡張機能](extensions.md)や [SideCar](browser-sidecars.md)とは別です。 ## 適切なコントロールを選ぶ {#integration-scopes} diff --git a/docs/help/ja/permissions.md b/docs/help/ja/permissions.md index a920626ea5..e3fa2fe2dd 100644 --- a/docs/help/ja/permissions.md +++ b/docs/help/ja/permissions.md @@ -1,5 +1,11 @@ # 質問と権限 +明示的なサーバーのコンテキストには名前と固定IDが表示され、同名のサーバーを区別できます。不確実または古くなった回答は、リクエスト編集欄で非モーダルの穏やかな通知として表示されます。通常の失敗にはエラー表示が使われます。 + +**明示的に設定したOpenCodeサーバー:** 質問と権限リクエストはライブでのみ届きます。下書きは編集できます。古い権限リクエストは現在のライブリクエストを待ちます。既知のFormには以下の明示的な確認があります。ドックの開閉可能な詳細で制限を確認できます。会話を開いて内容を確認しても、欠けたリクエストは自動復元されません。これらのサーバーでもYoloモードは機能します。再接続後、CodeNomadはYoloの会話の保留中の権限リクエストのみを読み直し、一度だけ承認します。以下の復元と決定記録の手順は共有ローカルサービスに適用されます。 + +既知のFormでは、元の編集欄で **このフォームの状態を確認** を選びます。待機中と確認できたFormだけが回答・キャンセル可能になります。下書きを確認してから別の操作で送信してください。回答済み・キャンセル済みの場合は下書きだけ保持し、他のクライアントの回答や回答者、以前の試行の成否は推測しません。確認できなければ編集は可能なまま回答を無効にし、明示的に再確認できます。各確認は全体で10秒、応答ごとに4 MiBまでです。項目の構造が変わっていても未確認のままです。自動確認・再送は行いません。網羅状況は不明のままで、欠けたFormや権限リクエストは見つかりません。 + ネイティブの質問、Form、権限リクエストには、入力欄のすぐ上の割り込みドックで回答します。会話欄の待機中のツールカード内ではありません。 ## リクエストを見つけて発生元を確認する {#request-dock} diff --git a/docs/help/ja/projects.md b/docs/help/ja/projects.md index f59bc8e5ff..47a9ced1e2 100644 --- a/docs/help/ja/projects.md +++ b/docs/help/ja/projects.md @@ -21,6 +21,16 @@ 通常のクリックでは、引き続きホームページ全体が開きます。ランチャーはショートカットであり、管理画面ではありません。最近のプロジェクトの名前変更/削除やサーバーブックマークの管理は、ホームページで行います。Escape でランチャーを閉じ、フォーカスを `+` に戻せます。 +## OpenCode サーバー上のプロジェクトを開く {#remote-project} + +1. ホームページまたはランチャーで **リモート** を展開し、サーバーの **+ プロジェクト** を選びます。サーバー名はフォルダーのパスの横に表示されます。 +2. サーバーを選び、フォルダーを参照して **開く** を選びます。**Backspace** で親フォルダーへ、**Esc** でサーバー一覧へ戻ります。 +3. サーバーを追加するには、`opencode pair` のリンク、または `https://opencode:<パスワード>@host:port` を **ペアリングリンクまたはアドレス** に貼り付けます。サーバーを右クリック(または **Shift+F10**)すると **保存したサーバーを削除** を選べます。 + +タブにはサーバーアイコンが表示され、フォルダーは最近のプロジェクトに加わります。**フォルダを参照**、**Git リポジトリをクローン**、一時インスタンスはこのコンピューター上に残ります。 + +ホストのバックエンドは、ペアリングトークンと手入力のパスワードを `config.yaml` の隣の非公開ファイル `opencode-server-pairings.json` (0600) に保存し、再起動後も使用します。有効期限切れ、HTTP 401、接続元の変更、サーバーの削除で秘密情報を消去します。保存したプロジェクトは元のサーバーで復元され、サーバーの追加・削除はホストのみが行えます。 + ## タブを閉じてプロジェクトを閉じる {#close-stop} 1. タブの閉じるボタン、またはコマンドパレットの **タブを閉じる**(レンダラーでは `Ctrl/Cmd+W`)を使用します。 diff --git a/docs/help/ja/providers.md b/docs/help/ja/providers.md index 58bc116dc1..1af05c186e 100644 --- a/docs/help/ja/providers.md +++ b/docs/help/ja/providers.md @@ -4,6 +4,8 @@ ## モデルまたは検索プロバイダーを接続する {#connect} +**選択した OpenCode サーバー**を確認してください。以下の接続、アカウント、ウェブ検索、画像の設定は、共有ローカルサービスに適用されます。明示的に指定され、適合性が確認されたサーバーでは、ネイティブのプロバイダーとモデルのカタログを読み取り専用で表示します。そのサーバーの認証と設定は、CodeNomad の現在の機能範囲外となるため、サーバー上で直接管理してください。利用できないプロジェクトの操作は無効のままですが、CodeNomad の設定は引き続き利用できます。ローカルサービスでは、折りたたまれた **モデル**、**ウェブ検索**、**画像** グループは、展開するまでデータを読み取りません。 + 1. ワークスペースを開き、**設定 → プロバイダー** を開きます。**モデル** は展開された状態で始まります。検索プロバイダーには **ウェブ検索** を展開します。**画像** には画像の設定があります。 2. そのグループで **プロバイダーを選択**、続けて **接続** を選びます。 3. モデルプロバイダーでは、提供されたネイティブの **認証方法**(API キー、OAuth、コマンド)を完了します。OAuth では **認可ページを開く** を使用し、求められた場合にのみ認可コードを送信します。検索プロバイダーは API キーで接続します。 diff --git a/docs/help/ja/security.md b/docs/help/ja/security.md index af7dd1f1f5..d42baea45a 100644 --- a/docs/help/ja/security.md +++ b/docs/help/ja/security.md @@ -1,5 +1,9 @@ # 認証とセキュリティ +添付ファイルの選択時は端末で読み取り、メッセージ送信時にプロジェクトの OpenCode サーバーへバイト列を転送します。共有ローカルサービスは CodeNomad の実行ホスト側にあり、操作中の端末とは異なる場合があります。遅延メディアの読み取りは、エラーを含むサーバー応答全体を展開後 16 MiB に制限してから解析します。超過、キャンセル、プロジェクトや接続の権限失効時は読み取りが失敗します。画像の寸法と画像デコード時のメモリはブラウザーが管理し、端末からのアップロードには独立した容量制限があります。 + +明示的サーバーの内部チャットでは表示やダウンロード前にメディアを検証します。外部画像 URL、アクティブな SVG/HTML 画像、HTML メディア埋め込みは拒否します。ダウンロードには利用者の操作が必要で、読み込み失敗は失敗のまま扱います。データ URI ごとの 8 MiB 制限は符号化された入力の上限で、復号後の画像寸法や端末アップロードの上限とは別です。 + CodeNomad へのアクセスにより、OpenCode を通じてバックエンドホスト上で作業を実行できます。サーバーパスワード、ブラウザーセッション、ペアリング済み端末は、強力な認証情報として扱ってください。CodeNomad はマルチテナントの実行サンドボックスではありません。 ## サーバーの認証方法を選ぶ {#authentication} diff --git a/docs/help/ja/settings.md b/docs/help/ja/settings.md index 417e8bcf3d..9a1e2705cc 100644 --- a/docs/help/ja/settings.md +++ b/docs/help/ja/settings.md @@ -2,6 +2,8 @@ ## 設定を開き、範囲を確認する {#open-settings} +**選択した OpenCode サーバー**はプロジェクトの対象を示します(共有ローカルサービスは `local-shared`)。CodeNomad の設定は共通です。利用できないプロジェクトの OpenCode 操作は無効のままです。設定ファイル、環境変数、OpenCode の保守は **ローカル CodeNomad バックエンド**を対象とし、HOME ファイル、プロファイル環境、共有サービスを扱います。**ローカルバックエンドを管理**を選ぶと、選択したプロジェクトとは別にこれらのローカル操作を明示的に開きます。 + 1. タブバー(macOS のデスクトップアプリではタイトルバー)またはホームページの **設定を開く** の歯車で **設定** を開きます。モデルセレクターの **プロバイダーを管理**、ミッションパネルの歯車、通知履歴の **設定** の歯車などのショートカットは、該当するセクションを直接開きます。 2. セクションを選びます。ローカルの Electron/Tauri ウィンドウは、単一のネイティブ設定ウィンドウを開くかフォーカスします。ブラウザー/リモート表示は埋め込み設定画面を使います。 3. 離れる前に、設定の範囲と **保存** 操作の有無を確認します。 @@ -15,7 +17,9 @@ | グローバル/プロジェクトの OpenCode 設定 | 表示範囲のネイティブなプラグイン/設定変更。プロジェクト操作にはアクティブなプロジェクト/Location が必要です。 | | デスクトップデータプロファイル | 設定ファイルや共有 OpenCode サービスとは独立した、ネイティブウィンドウ、復元状態、ブラウザーストレージ。[デスクトップのウィンドウとデータ](desktop.md)を参照してください。 | -**統計** は、開いたフォルダーだけでなく、接続先の OpenCode サービス全体(すべてのプロジェクト、独立したクローン、サブセッション)を対象とし、過去 7、30、90、365 日を集計します。開いているプロジェクトが必要で、表示するのは OpenCode が記録したトークンとコストであり、プロバイダーの請求書やサブスクリプションの利用枠ではありません。更新中は、以前に保存した合計が表示される場合があります。プランの割り当て量は、ステータスの **使用量** セクションで確認します。 +明示的に指定され、適合性が確認されたサーバーでは、プロバイダーとモデルのカタログを読み取り専用で表示します。対応が保留されているセクションも選択でき、制限の説明が表示されます。これらのサーバー設定は、サーバー上で直接管理してください。 + +**統計** は、開いたフォルダーだけでなく、共有ローカル OpenCode サービス全体(すべてのプロジェクト、独立したクローン、サブセッション)を対象とし、過去 7、30、90、365 日を集計します。開いているプロジェクトが必要で、表示するのは OpenCode が記録したトークンとコストであり、プロバイダーの請求書やサブスクリプションの利用枠ではありません。更新中は、以前に保存した合計が表示される場合があります。プランの割り当て量は、ステータスの **使用量** セクションで確認します。明示的に指定されたサーバーでは **統計** を利用できません。その理由はセクション内に表示されます。 表示設定を変更しても、OpenCode の再起動やプロンプトの再実行は行いません。ネイティブ設定、サービス保守、認証情報の影響は別です。[OpenCode のセットアップ](opencode.md)、[プロバイダー](providers.md)、[連携](integrations.md)を参照してください。 @@ -42,6 +46,8 @@ UI は会話を再起動せずに更新されます。ヘブライ語では右 ステータスには、トークン情報、Yolo モード、プロバイダーの使用量、バックグラウンドシェル、MCP、プラグインがあります。会話に[目標](conversations.md#goal)がある間は、これらのセクションの上に目標の行が表示されます。この行はセクションではないため、非表示にも移動もできません。セクションを隠しても、サービスの無効化や権限の取り消しはしません。狭いレイアウトでは、会話を圧迫せず、収まらなくなったパネルを閉じます。そこで開いたパネルは会話の上に浮かび、一方のフローティングパネルを開くと他方は閉じます。 +設定済みの OpenCode サーバー上のプロジェクトでは、これらのセクションはそのサーバーを読み取ります。**使用量** には、ネイティブの OpenCode Go クォータと、[プロバイダー](providers.md#usage)で説明する認証情報不要の Zen 推定値が表示されます。他のプロバイダーにはクォータが表示されません。**プラグイン** にはサーバーのプラグインとその状態が一覧表示されます。OpenCode にはサーバーのプラグイン設定を変更する API がないため、スイッチは読み取り専用のままです。MCP サーバーは引き続き接続・切断できます。**バックグラウンドシェル** では、開いたフォルダーのサーバー上のシェルを一覧表示・停止できます。 + 組み込みレイアウトはウィンドウのレイアウトであり、プロジェクトの変更操作ではありません。拡張機能のチェックボックスは異なり、その設定を使う全プロジェクトでコードを有効化します。**リセット** は拡張機能の同意を変更しません。[パネル拡張機能](extensions.md)を参照してください。 ## 会話表示の詳細と入力欄のサイズ {#transcript-composer} diff --git a/docs/help/ja/troubleshooting.md b/docs/help/ja/troubleshooting.md index 21948f10f7..6aba70765e 100644 --- a/docs/help/ja/troubleshooting.md +++ b/docs/help/ja/troubleshooting.md @@ -1,5 +1,9 @@ # トラブルシューティング +同名の実行サーバーは、リクエストの詳細とプロジェクト通知に名前と併記される固定IDで区別してください。不確実な回答は元の編集欄に残り、フォーカスの移動や自動再送は行われません。 + +**明示的に設定したOpenCodeサーバー:** 切断やバックエンド再起動後は、ドックが空でも待機中リクエストの網羅状況は不明です。下書きを保持し、古い権限リクエストは現在のライブリクエストを待ってください。既知のFormは元の編集欄の **このフォームの状態を確認** で確認できます。確認できなければ回答は無効のままで、明示的に再確認できます。全体10秒、応答ごとに4 MiBまでで、網羅状況は不明のままです。会話を開いても欠けたリクエストは自動検出されません。切断前の回答は届いている可能性があり、自動再送は行われません。以下の自動復元手順は共有ローカルサービスに適用されます。[質問と権限](permissions.md)も参照してください。 + まず、失敗した操作の管理元がブラウザー、CodeNomad バックエンド、OpenCode サービス、プロバイダーのどれかを確認して復旧します。応答が失われても、変更操作の失敗は証明できません。繰り返す前に現在の状態を読み直してください。 ## デスクトップの起動問題 {#desktop-launch} diff --git a/docs/help/ne/browser-sidecars.md b/docs/help/ne/browser-sidecars.md index de2df373b9..dfbe742430 100644 --- a/docs/help/ne/browser-sidecars.md +++ b/docs/help/ne/browser-sidecars.md @@ -1,5 +1,7 @@ # ब्राउजर पूर्वावलोकन र SideCars +स्पष्ट सर्भरको आन्तरिक च्याटका लिङ्कहरू loopback URL सहित तपाईंको कार्यबाट खुल्ने बाह्य लिङ्क नै रहन्छन्। तिनले लेखिएको ठेगाना राख्छन् र तपाईंको ब्राउजरको नेटवर्क सन्दर्भ प्रयोग गर्छन्। यो च्याटमा होस्ट पूर्वावलोकन उपलब्ध हुँदैन; कार्यान्वयन सर्भरमा सुरुङ प्रदान गरिँदैन। + ## सत्र ब्राउजर खोल्नुहोस् {#session-browser} 1. कुराकानी toolbar मा **वेब पूर्वावलोकन खोल्नुहोस्** रोज्नुहोस्। diff --git a/docs/help/ne/conversations.md b/docs/help/ne/conversations.md index eb5983a634..0c15457ba6 100644 --- a/docs/help/ne/conversations.md +++ b/docs/help/ne/conversations.md @@ -1,11 +1,17 @@ # कुराकानी +स्पष्ट सर्भरको च्याटले समर्थित इम्बेड गरिएका तस्बिर वा उही कुराकानीका प्रमाणित नेटिभ मिडिया देखाउँछ। अन्य स्रोतमा अनुपलब्धताको सूचना देखिन्छ। स्थानीय पथले त्यही कुराकानीमा पहिले नै रहेका तस्बिर मात्र फेला पार्छन्; `/btw` ले इम्बेड गरिएका तस्बिर मात्र स्वीकार गर्छ। मान्य इम्बेड गरिएका फाइलमा स्पष्ट डाउनलोड कार्य हुन्छ। + CodeNomad ले नेटिभ OpenCode सत्रलाई कुराकानीका रूपमा देखाउँछ, प्रत्यायोजित कामको पदानुक्रम र अर्को पटक पठाउने कुराका छुट्टै नियन्त्रणसहित। सन्देशले Markdown, code, diff र समर्थित उपकरण-नतिजा छवि देखाउँछन्। पाठ प्रतिलिपि, पूर्ण-इतिहास खोज र वाचनले embedded छविका byte होइन पाठ projection प्रयोग गर्छन्। **सन्देशको सामग्री** ले सुरक्षित अंश नमेटी दृश्यता बदल्छ; [इतिहास](history.md#operation-reference) ले प्रदर्शन नियन्त्रण र सफाइ छुट्याउँछ। तर्क र उपकरणका header ले हरेक चरणमा लागेको समय देखाउँछन्, चलिरहँदा प्रत्यक्ष गन्दै; एक सेकेन्डभन्दा कम अवधि देखाइँदैन। **सन्देशको सामग्री** मा **टोकन** देखाइएको बेला (**सबै** प्रिसेटले देखाउँछ), हरेक agent सन्देश आफ्नो अन्तिम पाठपछि एउटा token र लागत पङ्क्तिमा टुङ्गिन्छ। त्यो पङ्क्तिले लोड भएको transcript भित्र, त्यो सन्देश र यसको **यस जवाफबाट उपकरण र तर्क हटाउनुहोस्** कार्यले समेट्ने उपकरण र तर्क भएका सन्देशहरू जोड्छ; तर्क र cache गणनाका लागि यसलाई विस्तार गर्नुहोस्। उपकरण मात्र चलाएका चरणको आफ्नै पङ्क्ति हुँदैन। +स्पष्ट सर्भरको आन्तरिक च्याटमा `@` ले त्यस सर्भरका एजेन्ट र सीप देखाउँछ र परियोजना फाइलका सन्दर्भ उपलब्ध नभएको बताउँछ। कार्य चल्दा जडान परिवर्तन भए बाँकी चरण रोकिन्छन्। अनिश्चित कार्य फेरि पठाउनुअघि कुराकानी जाँच्नुहोस्: त्यो OpenCode मा पुगिसकेको हुन सक्छ। + +रोकिएको वा अनिश्चित कार्यले मूल कुराकानीमा गैर-मोडल सूचना छोड्छ र हालको फोकस कायम राख्छ। लामको सन्देश सम्पादनमा अवरोध आएमा त्यसको ज्ञात सामग्री खुला मूल कुराकानीमा पुनःस्थापना गर्न सकिन्छ: लाम जाँचेर मस्यौदा र संलग्नक खाली गर्नुहोस्, अनि **सुरक्षित सन्देश पुनःस्थापना गर्नुहोस्** छान्नुहोस्। यसले सम्पादनयोग्य मस्यौदा फर्काउँछ; पठाउनु छुट्टै कार्य हो। पुरानो `/btw` अनुरोध सकिएपछि नयाँ प्रश्न स्पष्ट रूपमा पठाउन सकिन्छ। + ## कुराकानी खोज्नुहोस् र आवागमन गर्नुहोस् {#navigate-conversations} 1. **सत्रहरू** अन्तर्गतको row चयन गर्नुहोस्, वा parent कुराकानी सुरु गर्न **नयाँ सत्र** प्रयोग गर्नुहोस्। diff --git a/docs/help/ne/extensions.md b/docs/help/ne/extensions.md index 77145a397e..27d2b41117 100644 --- a/docs/help/ne/extensions.md +++ b/docs/help/ne/extensions.md @@ -43,6 +43,8 @@ extension store चयनित CodeNomad कन्फिगरेसनछे ## सन्दर्भ, asset सहमति र sandbox सीमा {#permissions-sandbox} +API 3 का repository वस्तुहरू साझा स्थानीय OpenCode सेवा प्रयोग गर्ने परियोजनाका लागि मात्र उपलब्ध छन्। स्पष्ट रूपमा कन्फिगर गरिएका सबै OpenCode सर्भरमा, loopback सर्भर र विच्छेदित लक्ष्यसहित, तिनको native Git समर्थन जस्तो भए पनि यी उपलब्ध हुँदैनन्; होस्टको Git, forge साइन-इन वा नेटवर्कमा पहुँच हुनुअघि अनुरोध अस्वीकार हुन्छ। + | Contract | सक्रियताले दिने अनुमति | | --- | --- | | API 1 / `session.context` | हालको session identifier (वा कुनै होइन), interface भाषा र रूप। transcript पाठ वा filesystem पहुँच छैन। | diff --git a/docs/help/ne/files.md b/docs/help/ne/files.md index 9d2c49f2ba..4d57cafae5 100644 --- a/docs/help/ne/files.md +++ b/docs/help/ne/files.md @@ -19,6 +19,10 @@ row कार्यमा **मार्ग (Path) प्रतिलिपि गर्नुहोस्** र क्लाइन्टले ब्याकएन्ड मार्ग खोल्न समर्थन गर्दा **पूर्वनिर्धारित अनुप्रयोगमा खोल्नुहोस्**, **फोल्डरमा देखाउनुहोस्**, **फाइल व्यवस्थापकमा खोल्नुहोस्** र **यहाँ टर्मिनल खोल्नुहोस्** जस्ता file-manager/editor/terminal कार्य छन्। ठाउँ सीमित भए कार्य **{name} का लागि थप कार्यहरू** मा जान सक्छन्; `{name}` को ठाउँमा फाइल वा फोल्डर नाम आउँछ। रिमोट ब्राउजरले सर्भर मार्गलाई स्थानीय उपकरण मार्ग मान्न सक्दैन; [Remote Control](remote-control.md) हेर्नुहोस्। +### OpenCode सर्भरमा रहेका परियोजनाहरू {#opencode-server-files} + +कन्फिगर गरिएको OpenCode सर्भरमा खोलिएको परियोजनाका लागि **फाइलहरू** ले त्यो सर्भरलाई यसको OpenCode API मार्फत पढ्छ, यो कम्प्युटरको डिस्क वा Git कहिल्यै पढ्दैन। **कार्यक्षेत्र** ले खोलिएको फोल्डर पढ्न-मात्र रूपमा सूचीबद्ध र पूर्वावलोकन गर्छ (**बचत** छैन; पूर्वावलोकन 5 MiB मा रोकिन्छ)। **परिवर्तनहरू** ले खोलिएको फोल्डर र यसको branch का working-copy परिवर्तनहरू एउटै **परिवर्तनहरू** सूचीमा देखाउँछ, staging, commit, **कमिटहरू** वा **Git सुरु गर्नुहोस्** बिना। सर्भरले पूर्ण र स्पष्ट अवस्था रिपोर्ट गर्न नसक्दा प्यानलले खाली सूचीको सट्टा **सामग्री उपलब्ध छैन वा अपूर्ण छ।** देखाउँछ। एजेन्टले फाइल परिवर्तन गरेपछि **रिफ्रेस** प्रयोग गर्नुहोस्; सर्भरले फाइल वा branch परिवर्तन रिपोर्ट गर्दा पनि प्यानल रिफ्रेस हुन्छ। यो कम्प्युटरमा खोल्ने कार्यहरू अनुपलब्ध रहन्छन्। + ## स्रोत सम्पादन र सुरक्षित बचत {#edit-save} 1. eye कार्यबाट Workspace पाठ फाइल खोल्नुहोस्। diff --git a/docs/help/ne/history.md b/docs/help/ne/history.md index 0c74566514..2d4bd508ad 100644 --- a/docs/help/ne/history.md +++ b/docs/help/ne/history.md @@ -2,6 +2,8 @@ सुरक्षित इतिहास, transcript ले अहिले देखाउने कुरा र मोडेलको संक्षिप्त सन्दर्भ फरक हुन्। केही मेट्नुअघि नेभिगेसन वा filtering रोज्नुहोस्। +यी विस्तारित इतिहास कार्यहरू साझा स्थानीय OpenCode सेवाका लागि हुन्। स्पष्ट सर्भरका परियोजनाले नेटिभ पृष्ठ र लोड भएका सन्देशको समयरेखा प्रयोग गर्छन्, अंश उपलब्ध नभए सुरक्षित पढ्ने स्थान कायम राख्छन् र पछिल्लो पृष्ठमा स्पष्ट रूपमा फर्कने विकल्प दिन्छन्। पूर्ण-पाठ खोज, लोड नभएका सन्देशका पूर्वावलोकन र प्राविधिक सफाइ त्यहाँ उपलब्ध छैनन्; पहिल्यै लोड भएको पाठका पूर्वावलोकन उपलब्ध छन्। + ## पूर्ण इतिहास खोज्नुहोस् {#full-history-search} 1. कुराकानी header मा **च्याट इतिहास खोज्नुहोस्** खोल्नुहोस्, वा कन्फिगर shortcut (default **Ctrl/Cmd+F**) प्रयोग गर्नुहोस्। diff --git a/docs/help/ne/integrations.md b/docs/help/ne/integrations.md index 2f1bb63dd1..0f78908e4e 100644 --- a/docs/help/ne/integrations.md +++ b/docs/help/ne/integrations.md @@ -1,5 +1,7 @@ # नेटिभ एकीकरण +तलका स्थापना, एप्लिकेसन जडान र कन्फिगरेसन नियन्त्रण साझा स्थानीय OpenCode परियोजनाका लागि हुन्। स्पष्ट सर्भरमा प्लगइन सूची र एकीकरण स्थिति पढ्न-मात्र रहन्छ; एप्लिकेसन जडान र स्थापना त्यहाँ उपलब्ध हुँदैनन्। + CodeNomad ले OpenCode का नेटिभ MCP जडान, plugin सक्रियता, skill र custom command उपलब्ध गराउँछ। यी execution host मा चल्छन्। यी sandbox भएका [प्यानल विस्तार](extensions.md) र [SideCars](browser-sidecars.md) भन्दा फरक हुन्। ## सही नियन्त्रण रोज्नुहोस् {#integration-scopes} diff --git a/docs/help/ne/permissions.md b/docs/help/ne/permissions.md index ab93801dc0..fcc9760b4e 100644 --- a/docs/help/ne/permissions.md +++ b/docs/help/ne/permissions.md @@ -1,5 +1,11 @@ # प्रश्न र अनुमति +स्पष्ट सर्भरको सन्दर्भमा नाम र स्थिर ID हुन्छ, त्यसैले उस्तै नाम छुट्याउन सकिन्छ। अनिश्चित वा पुरानो भइसकेको जवाफको सूचना अनुरोध सम्पादकमा विनम्र र गैर-मोडल रूपमा देखिन्छ; सामान्य असफलताले त्रुटि प्रदर्शन कायम राख्छ। + +**स्पष्ट रूपमा कन्फिगर गरिएका OpenCode सर्भरहरू:** प्रश्न र अनुमति अनुरोधहरू प्रत्यक्ष रूपमा मात्र आउँछन्। मस्यौदा सम्पादन गर्न सकिन्छ। पुराना अनुमति अनुरोधले हालको प्रत्यक्ष अनुरोध पर्खन्छन्; ज्ञात Form का लागि तल स्पष्ट जाँच उपलब्ध छ। डकको खोल्न मिल्ने विवरणले सीमा बताउँछ। संवाद खोल्दा छुटेका अनुरोध स्वतः पुनःप्राप्त हुँदैनन्। यी सर्भरहरूमा Yolo मोड काम गर्छ: पुनः जडानपछि CodeNomad ले Yolo कुराकानीहरूका मात्र बाँकी अनुमति अनुरोध फेरि पढ्छ र तिनलाई एक पटक स्वीकृत गर्छ। तलका पुनःप्राप्ति र निर्णय अभिलेख प्रक्रिया साझा स्थानीय सेवाका लागि हुन्। + +ज्ञात Form का लागि मूल सम्पादकमा **यो फारमको स्थिति जाँच्नुहोस्** छान्नुहोस्। पर्खिरहेको प्रमाणित Form का आफ्नै जवाफ र रद्द कार्य मात्र खुल्छन्; मस्यौदा हेरेर छुट्टै स्पष्ट कार्य गर्नुहोस्। जवाफ दिइसकेको वा रद्द भएको Form ले मस्यौदा सन्दर्भका लागि राख्छ; अर्को क्लाइन्टको जवाफ, लेखक वा पुरानो प्रयासको नतिजा अनुमान गर्दैन। अनिर्णीत जाँचले सम्पादन खुला र जवाफ बन्द राख्छ; फेरि स्पष्ट रूपमा जाँच्न सक्नुहुन्छ। प्रत्येक जाँच 10 सेकेन्ड र प्रति प्रतिक्रिया 4 MiB मा सीमित छ; बदलिएको फिल्ड संरचना पनि अनिर्णीत रहन्छ। स्वतः जाँच वा पुनःपठाउने हुँदैन। समग्र पूर्णता अज्ञात रहन्छ; छुटेका Form वा अनुमति भेटिँदैनन्। + नेटिभ प्रश्न, Form र अनुमति अनुरोधको उत्तर कम्पोजरको ठीक माथिको interruption dock मा दिइन्छ, pending transcript tool card भित्र होइन। ## अनुरोध खोज्नुहोस् र स्रोत जाँच्नुहोस् {#request-dock} diff --git a/docs/help/ne/projects.md b/docs/help/ne/projects.md index bb723aca9f..1633cfdac6 100644 --- a/docs/help/ne/projects.md +++ b/docs/help/ne/projects.md @@ -21,6 +21,16 @@ सामान्य क्लिकले अझै पूर्ण गृह पृष्ठ खोल्छ। launcher shortcut हो, व्यवस्थापन सतह होइन: recent परियोजनाको नाम बदल्न/हटाउन र सर्भर bookmark व्यवस्थापन गर्न गृह पृष्ठ प्रयोग गर्नुहोस्। Escape ले launcher बन्द गरी `+` मा focus फर्काउँछ। +## OpenCode सर्भरमा परियोजना खोल्नुहोस् {#remote-project} + +1. गृह पृष्ठ वा launcher मा **रिमोटहरू** विस्तार गर्नुहोस् र सर्भरमा **+ परियोजना** छान्नुहोस्। यसको नाम फोल्डरको पथसँगै देखिइरहन्छ। +2. सर्भर छान्नुहोस्, यसका फोल्डरहरू हेर्नुहोस् र **खोल्नुहोस्** छान्नुहोस्। **Backspace** ले माथिल्लो फोल्डरमा लैजान्छ; **Esc** ले सर्भर सूचीमा फर्काउँछ। +3. सर्भर थप्न, यसको `opencode pair` लिङ्क वा `https://opencode:@host:port` लाई **पेयरिङ लिङ्क वा ठेगाना** मा टाँस्नुहोस्। **बचत गरिएको सर्भर हटाउनुहोस्** का लागि सर्भरमा दायाँ-क्लिक (वा **Shift+F10**) गर्नुहोस्। + +ट्याबमा सर्भर आइकन देखिन्छ र फोल्डर हालका परियोजनाहरूमा थपिन्छ। **फोल्डरहरू ब्राउज गर्नुहोस्**, **Git Repo क्लोन गर्नुहोस्** र अस्थायी instance हरू यही कम्प्युटरमा रहन्छन्। + +होस्ट backend ले pairing token र हातैले लेखिएका password पुनःसुरु भएपछि पनि `config.yaml` छेउको निजी `opencode-server-pairings.json` (0600) मा राख्छ। म्याद सकिँदा, HTTP 401 आउँदा, origin फेरिँदा वा सर्भर हटाउँदा गोप्य मान मेटिन्छ। सुरक्षित परियोजनाहरू आफ्नै सर्भरमा पुनर्स्थापित हुन्छन्; सर्भर थप्ने र हटाउने काम होस्टले मात्र गर्छ। + ## ट्याब बन्द गरेर परियोजना बन्द गर्नुहोस् {#close-stop} 1. ट्याबको close बटन वा कमाण्ड प्यालेटको **ट्याब बन्द गर्नुहोस्** (renderer मा `Ctrl/Cmd+W`) प्रयोग गर्नुहोस्। diff --git a/docs/help/ne/providers.md b/docs/help/ne/providers.md index 156783d81d..f8b7362f51 100644 --- a/docs/help/ne/providers.md +++ b/docs/help/ne/providers.md @@ -4,6 +4,8 @@ ## मोडेल वा खोज प्रदायक जोड्नुहोस् {#connect} +**चयन गरिएको OpenCode सर्भर** जाँच्नुहोस्। तल वर्णन गरिएका जडान, खाता, वेब खोज र छवि सेटिङहरू साझा स्थानीय सेवामा लागू हुन्छन्। स्पष्ट रूपमा तोकिएको र योग्य ठहरिएको सर्भरले प्रदायक र मोडेलहरूको नेटिभ सूची पढ्न मात्र मिल्ने गरी देखाउँछ; त्यसको प्रमाणीकरण र कन्फिगरेसन CodeNomad का हालका क्षमताबाहिर पर्ने भएकाले सर्भरमै सीधै व्यवस्थापन गर्नुहोस्। अनुपलब्ध परियोजनाका नियन्त्रणहरू निष्क्रिय रहन्छन्; CodeNomad प्राथमिकताहरू भने प्रयोग गर्न सकिन्छ। स्थानीय सेवामा, खुम्च्याइएका **मोडेलहरू**, **वेब खोज** र **छविहरू** समूहहरूले विस्तार गरेपछि मात्र आफ्ना विवरण पढ्छन्। + 1. कार्यस्थान खोलेर **सेटिङहरू → प्रदायकहरू** खोल्नुहोस्। **मोडेलहरू** विस्तारित अवस्थामा सुरु हुन्छ; खोज प्रदायकका लागि **वेब खोज** विस्तार गर्नुहोस्। **छविहरू** मा छवि सेटिङहरू छन्। 2. त्यस समूहमा **प्रदायक चयन गर्नुहोस्**, अनि **जडान गर्नुहोस्** रोज्नुहोस्। 3. मोडेल प्रदायकका लागि दिइएको नेटिभ **प्रमाणीकरण विधि** पूरा गर्नुहोस्: API key, OAuth वा command। OAuth मा **प्रमाणीकरण पृष्ठ खोल्नुहोस्** प्रयोग गर्नुहोस् र माग्दा मात्र authorization code बुझाउनुहोस्। खोज प्रदायक API key बाट जोडिन्छन्। diff --git a/docs/help/ne/security.md b/docs/help/ne/security.md index d77ce14e0b..5f48691f4d 100644 --- a/docs/help/ne/security.md +++ b/docs/help/ne/security.md @@ -1,5 +1,9 @@ # प्रमाणीकरण र सुरक्षा +संलग्न फाइल छान्दा तपाईंको उपकरणमा पढिन्छ; सन्देश पठाउँदा त्यसका बाइटहरू परियोजनाको OpenCode सर्भरमा सारिन्छन्। साझा स्थानीय सेवा CodeNomad को कार्यान्वयन होस्टमा हुन्छ, जुन तपाईंको उपकरणभन्दा फरक हुन सक्छ। पछि लोड हुने मिडियाले त्रुटिसहित डिकम्प्रेस गरिएको सम्पूर्ण सर्भर जवाफलाई विश्लेषणअघि 16 MiB मा सीमित गर्छ। सीमा नाघ्दा, रद्द हुँदा वा परियोजना/जडानको अधिकार हट्दा पढाइ असफल हुन्छ। तस्बिरका आयाम र डिकोड गरिएको तस्बिरको मेमोरी ब्राउजरले व्यवस्थापन गर्छ; उपकरणबाट गरिने अपलोडका आफ्नै बजेट कायम रहन्छन्। + +स्पष्ट सर्भरको आन्तरिक च्याटले देखाउन वा डाउनलोड गर्नुअघि मिडिया अनुमति जाँच्छ। बाह्य तस्बिर URL, सक्रिय SVG/HTML तस्बिर र HTML मिडिया इम्बेड अस्वीकार हुन्छन्; डाउनलोडमा तपाईंको कार्य चाहिन्छ र असफल पढाइ असफल नै रहन्छ। प्रत्येक डेटा URI को 8 MiB सीमा सङ्केतित इनपुटको सीमा हो, डिकोड गरिएका तस्बिरका आयाम र उपकरण अपलोड सीमाभन्दा अलग। + CodeNomad पहुँचले OpenCode मार्फत backend host मा काम चलाउन सक्छ। server password, browser session र paired device लाई शक्तिशाली credential मान्नुहोस्। CodeNomad multi-tenant execution sandbox होइन। ## server प्रमाणीकरण रोज्नुहोस् {#authentication} diff --git a/docs/help/ne/settings.md b/docs/help/ne/settings.md index 202c19f887..8c6685b7a1 100644 --- a/docs/help/ne/settings.md +++ b/docs/help/ne/settings.md @@ -2,6 +2,8 @@ ## सेटिङ खोलेर दायरा चिनाउनुहोस् {#open-settings} +**चयन गरिएको OpenCode सर्भर** ले परियोजनाको सन्दर्भ चिनाउँछ (साझा स्थानीय सेवाका लागि `local-shared`); CodeNomad प्राथमिकताहरू साझा रहन्छन्। अनुपलब्ध परियोजनाका OpenCode नियन्त्रणहरू निष्क्रिय रहन्छन्। कन्फिगरेसन फाइल, वातावरण चर र OpenCode मर्मतले **स्थानीय CodeNomad ब्याकएन्ड** जनाउँछन्: HOME फाइलहरू, प्रोफाइल वातावरण र साझा सेवा यसकै हुन्। **स्थानीय ब्याकएन्ड व्यवस्थापन गर्नुहोस्** ले चयन गरिएको परियोजनाबाट छुट्टै ती स्थानीय नियन्त्रणहरू स्पष्ट रूपमा खोल्छ। + 1. ट्याब पट्टी (macOS डेस्कटप एपमा शीर्षक पट्टी) वा गृह पृष्ठको **सेटिङहरू खोल्नुहोस्** gear बाट **सेटिङहरू** खोल्नुहोस्। मोडेल selector को **प्रदायकहरू व्यवस्थापन गर्नुहोस्**, Missions प्यानलको gear वा सूचना इतिहासको **सेटिङहरू** gear जस्ता shortcut ले सम्बन्धित खण्ड सोझै खोल्छन्। 2. खण्ड चयन गर्नुहोस्। स्थानीय Electron र Tauri विन्डोले एउटै नेटिभ Preferences विन्डो खोल्छन् वा focus गर्छन्; ब्राउजर र रिमोट दृश्यले embedded सेटिङ स्क्रिन प्रयोग गर्छन्। 3. छोड्नुअघि सेटिङको दायरा र **बचत गर्नुहोस्** कार्य जाँच्नुहोस्। @@ -15,7 +17,9 @@ | Global/Project OpenCode सेटिङ | देखाइएको दायरामा native plugin/configuration परिवर्तन। Project नियन्त्रणलाई सक्रिय परियोजना/Location चाहिन्छ। | | डेस्कटप डेटा प्रोफाइल | कन्फिगरेसन फाइल र साझा OpenCode सेवाबाट स्वतन्त्र नेटिभ विन्डो, restore अवस्था र ब्राउजर भण्डारण। [डेस्कटप विन्डो र डेटा](desktop.md) हेर्नुहोस्। | -**तथ्याङ्क** ले खोलिएको फोल्डर मात्र होइन, पूरै जोडिएको OpenCode सेवा (सबै परियोजना, स्वतन्त्र clone र उप-सत्र) लाई पछिल्ला 7, 30, 90 वा 365 दिनका लागि समेट्छ। यसलाई खुला परियोजना चाहिन्छ र यसले OpenCode ले अभिलेख गरेका token र लागत देखाउँछ, provider invoice वा subscription allowance होइन; refresh हुँदै गर्दा अघिल्ला सुरक्षित कुल देखिन सक्छन्। plan quota Status को **प्रयोग** खण्डमा पर्छन्। +स्पष्ट रूपमा तोकिएका र योग्य ठहरिएका सर्भरहरूले प्रदायक र मोडेलहरूको सूची पढ्न मात्र मिल्ने गरी देखाउँछन्। स्थगित खण्डहरू चयन गर्न मिल्छ र तिनले आफ्नो सीमा स्पष्ट पार्छन्; ती सर्भर सेटिङहरू सर्भरमै सीधै व्यवस्थापन गर्नुहोस्। + +**तथ्याङ्क** ले खोलिएको फोल्डर मात्र होइन, पूरै साझा स्थानीय OpenCode सेवा (सबै परियोजना, स्वतन्त्र clone र उप-सत्र) लाई पछिल्ला 7, 30, 90 वा 365 दिनका लागि समेट्छ। यसलाई खुला परियोजना चाहिन्छ र यसले OpenCode ले अभिलेख गरेका token र लागत देखाउँछ, provider invoice वा subscription allowance होइन; refresh हुँदै गर्दा अघिल्ला सुरक्षित कुल देखिन सक्छन्। plan quota Status को **प्रयोग** खण्डमा पर्छन्। स्पष्ट रूपमा तोकिएका सर्भरहरूका लागि **तथ्याङ्क** उपलब्ध हुँदैन; यसको खण्डले कारण स्पष्ट पार्छ। प्रदर्शन प्राथमिकता बदल्दा OpenCode restart वा prompt replay हुँदैन। native configuration, सेवा मर्मत र credential का छुट्टै असर छन्: [OpenCode सेटअप](opencode.md), [प्रदायक](providers.md) र [एकीकरण](integrations.md) हेर्नुहोस्। @@ -42,6 +46,8 @@ Status मा token जानकारी, Yolo मोड, provider Usage, background shell, MCP र Plugins छन्। कुराकानीमा [लक्ष्य](conversations.md#goal) रहुन्जेल यी खण्डहरूमाथि लक्ष्य लाइनले त्यसलाई देखाउँछ; त्यो लाइन खण्ड होइन र लुकाउन वा सार्न मिल्दैन। खण्ड लुकाउँदा सेवा अक्षम वा अनुमति खारेज हुँदैन। साँघुरो लेआउटले कुराकानी खुम्च्याउनुको सट्टा नअट्ने प्यानल बन्द गर्छ; त्यहाँ खोलिएको प्यानल कुराकानीमाथि तैरिन्छ, र एउटा floating प्यानल खोल्दा अर्को बन्द हुन्छ। +कन्फिगर गरिएको OpenCode सर्भरमा रहेको परियोजनाका लागि यी खण्डहरूले त्यो सर्भर पढ्छन्। **प्रयोग** ले नेटिभ OpenCode Go quota र [प्रदायक](providers.md#usage) मा वर्णित credential नचाहिने Zen अनुमान देखाउँछ; अन्य provider ले quota देखाउँदैनन्। **प्लगइनहरू** ले सर्भरका plugin तिनको अवस्थासहित सूचीबद्ध गर्छ; OpenCode ले सर्भरको plugin configuration परिवर्तन गर्ने API नदिने भएकाले तिनका switch पढ्न-मात्र रहन्छन्। MCP सर्भरहरू अझै जडान वा विच्छेद गर्न सकिन्छ। **पृष्ठभूमि शेलहरू** ले खोलिएको फोल्डरका सर्भर shell सूचीबद्ध गर्छ र रोक्छ। + built-in लेआउट विन्डो लेआउट हो, परियोजना परिवर्तन होइन। विस्तार checkbox फरक छन्: तिनले कन्फिगरेसन प्रयोग गर्ने सबै परियोजनामा code सक्रिय गर्छन्। **रिसेट गर्नुहोस्** ले विस्तार सहमति बदल्दैन। [प्यानल विस्तार](extensions.md) हेर्नुहोस्। ## Transcript विवरण र कम्पोजर आकार {#transcript-composer} diff --git a/docs/help/ne/troubleshooting.md b/docs/help/ne/troubleshooting.md index c89b83cf6a..cc0881b26f 100644 --- a/docs/help/ne/troubleshooting.md +++ b/docs/help/ne/troubleshooting.md @@ -1,5 +1,9 @@ # समस्या समाधान +उस्तै नाम भएका कार्यान्वयन सर्भर छुट्याउन अनुरोध विवरण र परियोजना सूचनामा नामसँग देखिने स्थिर ID प्रयोग गर्नुहोस्। अनिश्चित जवाफ मूल सम्पादकमै रहन्छ; फोकस सारिँदैन र स्वतः फेरि पठाइँदैन। + +**स्पष्ट रूपमा कन्फिगर गरिएका OpenCode सर्भरहरू:** जडान टुटेपछि वा ब्याकएन्ड पुनः सुरु भएपछि डक खाली भए पनि पर्खिरहेका अनुरोधहरूको पूर्णता अज्ञात हुन्छ। मस्यौदा राख्नुहोस्; पुराना अनुमति अनुरोधले हालको प्रत्यक्ष अनुरोध पर्खन्छन्। ज्ञात Form मा मूल सम्पादकको **यो फारमको स्थिति जाँच्नुहोस्** प्रयोग गर्नुहोस्; अनिर्णीत नतिजाले जवाफ बन्द राख्छ र अर्को स्पष्ट जाँच गर्न दिन्छ। सीमा समग्र 10 सेकेन्ड र प्रति प्रतिक्रिया 4 MiB हो; पूर्णता अज्ञात रहन्छ। संवाद खोल्दा छुटेका अनुरोध स्वतः भेटिँदैनन्। पहिलेको जवाफ सफल भएको हुन सक्छ; स्वतः फेरि पठाइँदैन। तलको स्वचालित पुनःप्राप्ति साझा स्थानीय सेवाका लागि हो। [प्रश्न र अनुमति](permissions.md) हेर्नुहोस्। + असफल कार्यको स्वामी—browser, CodeNomad backend, OpenCode service वा provider—पहिले जाँचेर पुनःप्राप्ति गर्नुहोस्। reply हराउनु mutation असफल भएको प्रमाण होइन; दोहोर्‍याउनुअघि current state फेरि पढ्नुहोस्। ## desktop launch समस्या {#desktop-launch} diff --git a/docs/help/ru/browser-sidecars.md b/docs/help/ru/browser-sidecars.md index e3d1b018fe..f0d73a9cea 100644 --- a/docs/help/ru/browser-sidecars.md +++ b/docs/help/ru/browser-sidecars.md @@ -1,5 +1,7 @@ # Браузерные предпросмотры и SideCars +Ссылки во внутреннем чате явно настроенных серверов, включая loopback-URL, остаются внешними и открываются вашим действием. Они сохраняют записанный адрес и используют сетевой контекст браузера. Предпросмотр хоста в этом чате недоступен; туннель к серверу выполнения не предоставляется. + ## Открытие браузера сессии {#session-browser} 1. В панели инструментов разговора выберите **Открыть веб-предпросмотр**. diff --git a/docs/help/ru/conversations.md b/docs/help/ru/conversations.md index c981dba1a4..8cf90d48af 100644 --- a/docs/help/ru/conversations.md +++ b/docs/help/ru/conversations.md @@ -1,11 +1,17 @@ # Разговоры +Чат явно настроенных серверов показывает поддерживаемые встроенные изображения и проверенные нативные медиа того же разговора. Для остальных источников выводится сообщение о недоступности. Локальные пути находят только уже имеющиеся в этом разговоре изображения; `/btw` принимает только встроенные изображения. Корректные встроенные файлы предлагают явную загрузку. + CodeNomad представляет нативные сессии OpenCode как разговоры с иерархией делегированной работы и отдельными средствами управления следующей отправкой. Сообщения отображают Markdown, код, диффы и поддерживаемые изображения из результатов инструментов. Копирование текста, поиск по всей истории и озвучивание используют текстовые проекции, а не байты встроенных изображений. **Содержимое сообщений** меняет видимость без удаления сохранённых частей; раздел [История](history.md#operation-reference) различает управление отображением и очистку. Заголовки рассуждений и инструментов показывают, сколько длился каждый шаг, с живым отсчётом во время выполнения; длительность меньше секунды не показывается. Когда в **Содержимое сообщений** показываются **Токены** (их показывает набор **Всё**), каждое сообщение агента завершается одной строкой токенов и стоимости после его последнего текста. Эта строка суммирует само сообщение и сообщения с инструментами и рассуждениями, которые охватывает его действие **Удалить инструменты и рассуждения из этого ответа**, в пределах загруженной переписки; разверните её, чтобы увидеть счётчики рассуждений и кэша. Шаги, которые только запускали инструменты, собственной строки не имеют. +Во внутреннем чате с явно заданным сервером `@` предлагает его агентов и навыки и поясняет недоступность ссылок на файлы проекта. Смена подключения во время действия останавливает оставшиеся шаги. Перед повтором действия с неизвестным результатом проверьте разговор: оно уже могло дойти до OpenCode. + +Прерванное действие или неизвестный результат оставляет немодальное уведомление в исходном разговоре и сохраняет текущий фокус. Если редактирование сообщения в очереди прервано, его известное содержимое остаётся доступно в открытом исходном разговоре: проверьте очередь, очистите черновик и вложения и выберите **Восстановить сохранённое сообщение**. Восстанавливается редактируемый черновик; отправка остаётся отдельным действием. После завершения устаревшего запроса `/btw` можно явно задать новый вопрос. + ## Поиск разговоров и навигация {#navigate-conversations} 1. Выберите строку в **Сессии** или нажмите **Новая сессия**, чтобы начать родительский разговор. diff --git a/docs/help/ru/extensions.md b/docs/help/ru/extensions.md index d04a9025ee..792f327b84 100644 --- a/docs/help/ru/extensions.md +++ b/docs/help/ru/extensions.md @@ -43,6 +43,8 @@ ## Контекст, согласие на ресурсы и ограничения песочницы {#permissions-sandbox} +Элементы репозитория API 3 доступны только проектам, использующим общий локальный сервис OpenCode. Они недоступны для любого явно настроенного сервера OpenCode, включая loopback и отключённые цели, независимо от его встроенной поддержки Git; отказ происходит до обращения к Git на хосте, входам в платформы размещения кода или сети. + | Контракт | Что разрешает активация | | --- | --- | | API 1 / `session.context` | Идентификатор текущей сессии (или его отсутствие), язык и оформление интерфейса. Без текста переписки и доступа к файловой системе. | diff --git a/docs/help/ru/files.md b/docs/help/ru/files.md index b73c8b41d7..404629c990 100644 --- a/docs/help/ru/files.md +++ b/docs/help/ru/files.md @@ -19,6 +19,10 @@ Действия строки включают **Скопировать путь** и, если клиент умеет открывать пути серверной части, действия файлового менеджера/редактора/терминала: **Открыть в приложении по умолчанию**, **Показать в папке**, **Открыть в файловом менеджере** и **Открыть терминал здесь**. При нехватке места действия переходят в **Дополнительные действия для {name}**; `{name}` заменяется именем файла или папки. Удалённый браузер не может считать серверный путь локальным путём устройства; см. [удалённое управление](remote-control.md). +### Проекты на сервере OpenCode {#opencode-server-files} + +Для проекта, открытого на настроенном сервере OpenCode, **Файлы** читает этот сервер через его API OpenCode и никогда не обращается к диску или Git этого компьютера. **Рабочая область** показывает список и предпросмотр открытой папки только для чтения (без **Сохранить**; предпросмотр ограничен 5 MiB). **Изменения** показывает изменения рабочей копии открытой папки и её ветки в одном списке **Изменения**, без подготовки, коммита, **Коммиты** и **Инициализировать Git**. Если сервер не может сообщить полное и однозначное состояние, панель показывает **Содержимое недоступно или неполно.** вместо пустого списка. Используйте **Обновить** после того, как агент изменит файлы; панель также обновляется, когда сервер сообщает об изменениях файлов или ветки. Действия открытия на этом компьютере остаются недоступными. + ## Редактирование исходника и безопасное сохранение {#edit-save} 1. Откройте текстовый файл рабочей области значком глаза. diff --git a/docs/help/ru/history.md b/docs/help/ru/history.md index 87358ed887..c35e7ca562 100644 --- a/docs/help/ru/history.md +++ b/docs/help/ru/history.md @@ -2,6 +2,8 @@ Сохранённая история, текущее отображение переписки и компактированный контекст модели — разные вещи. Прежде чем что-либо удалять, выберите навигацию или фильтрацию. +Эти расширенные функции истории относятся к общей локальной службе OpenCode. Проекты на явно настроенных серверах используют нативные страницы и шкалу загруженных сообщений, сохраняют позицию чтения, когда фрагмент недоступен, и предлагают явный переход к последней странице. Полнотекстовый поиск, предпросмотр незагруженных сообщений и техническая очистка там недоступны; предпросмотр уже загруженного текста доступен. + ## Поиск по всей истории {#full-history-search} 1. Откройте **Поиск по истории чата** в заголовке разговора или используйте настроенное сочетание (по умолчанию **Ctrl/Cmd+F**). diff --git a/docs/help/ru/integrations.md b/docs/help/ru/integrations.md index a1678864e7..0b989324e2 100644 --- a/docs/help/ru/integrations.md +++ b/docs/help/ru/integrations.md @@ -1,5 +1,7 @@ # Нативные интеграции +Описанные ниже установка, подключение приложения и настройка доступны для проектов общей локальной службы OpenCode. На явно настроенных серверах остаются список плагинов и статус интеграций только для чтения; подключение приложения и установка там недоступны. + CodeNomad предоставляет нативные подключения MCP, активацию плагинов, навыки и пользовательские команды OpenCode. Они работают на хосте выполнения. Это отдельно от изолированных [расширений панели](extensions.md) и [SideCars](browser-sidecars.md). ## Выбор нужного управления {#integration-scopes} diff --git a/docs/help/ru/permissions.md b/docs/help/ru/permissions.md index d45822af8f..4d3902f78e 100644 --- a/docs/help/ru/permissions.md +++ b/docs/help/ru/permissions.md @@ -1,5 +1,11 @@ # Вопросы и разрешения +Контекст явно настроенного сервера включает имя и постоянный ID, позволяя различать одинаковые имена. Неопределённый или устаревший ответ отображается ненавязчивым немодальным уведомлением в редакторе запроса; обычные сбои сохраняют индикацию ошибки. + +**Явно настроенные серверы OpenCode:** вопросы и запросы разрешений приходят только в реальном времени. Черновики можно редактировать. Устаревшие разрешения ждут актуального запроса в реальном времени; известные формы предлагают явную проверку ниже. Раскрываемые сведения панели объясняют ограничение. Открытие беседы позволяет просмотреть её, без автоматического восстановления пропущенных запросов. Режим Yolo работает на этих серверах: после переподключения CodeNomad заново считывает ожидающие разрешения только бесед с Yolo и одобряет их один раз. Описанные ниже восстановление и квитанции относятся к общей локальной службе. + +Для известной формы выберите **Проверить состояние этой формы** в исходном редакторе. Подтверждённая ожидающая форма включает только свои действия; проверьте черновик и отдельно ответьте или отмените её. У отвеченной или отменённой формы черновик остаётся для просмотра, без показа чужого ответа и догадок об авторе или результате вашего прежнего действия. Неопределённая проверка сохраняет редактирование и блокирует ответы; повторите её явно при необходимости. Лимит проверки — 10 секунд целиком и 4 MiB на ответ; изменённая схема полей также остаётся неопределённой. Автопроверок и повторных отправок нет. Полнота остаётся неизвестной; пропущенные формы и разрешения не обнаруживаются. + На нативные вопросы, формы и запросы разрешений отвечают в панели прерываний непосредственно над полем ввода, а не в ожидающих карточках инструментов в переписке. ## Найдите запрос и проверьте источник {#request-dock} diff --git a/docs/help/ru/projects.md b/docs/help/ru/projects.md index da4ff180eb..a55ad5b9e3 100644 --- a/docs/help/ru/projects.md +++ b/docs/help/ru/projects.md @@ -21,6 +21,16 @@ Обычное нажатие по-прежнему открывает полную главную страницу. Меню — быстрый переход, а не средство управления: переименовывайте/удаляйте недавние проекты и управляйте закладками серверов на главной странице. Escape закрывает меню и возвращает фокус на `+`. +## Открыть проект на сервере OpenCode {#remote-project} + +1. На главной странице или в панели запуска разверните **УДАЛЁННЫЕ** и выберите **+ Проект** у сервера. Его имя остаётся видимым рядом с путём папки. +2. Выберите сервер, просмотрите его папки и выберите **Открыть**. **Backspace** переходит к родительской папке; **Esc** возвращает к серверам. +3. Чтобы добавить сервер, вставьте его ссылку `opencode pair` или `https://opencode:<пароль>@host:port` в **Ссылка для сопряжения или адрес**. Щёлкните сервер правой кнопкой (или **Shift+F10**), чтобы выбрать **Удалить сохраненный сервер**. + +Вкладка отмечена значком сервера, а папка попадает в недавние проекты. **Обзор папок**, **Клонировать Git-репозиторий** и временные экземпляры остаются на этом компьютере. + +Backend хоста сохраняет токены сопряжения и введённые пароли между запусками в закрытом файле `opencode-server-pairings.json` (0600) рядом с `config.yaml`. Истечение срока, HTTP 401, смена адреса источника или удаление сервера стирают секрет. Сохранённые проекты восстанавливаются на своём сервере; добавление и удаление серверов доступны только на хосте. + ## Закрытие вкладки проекта {#close-stop} 1. Нажмите кнопку закрытия вкладки или выполните **Закрыть вкладку** в палитре команд (`Ctrl/Cmd+W` в интерфейсе). diff --git a/docs/help/ru/providers.md b/docs/help/ru/providers.md index 468e21e673..b18e971405 100644 --- a/docs/help/ru/providers.md +++ b/docs/help/ru/providers.md @@ -4,6 +4,8 @@ ## Подключение провайдера моделей или поиска {#connect} +Проверьте **Выбранный сервер OpenCode**. Описанные ниже настройки подключений, аккаунтов, поиска в интернете и изображений относятся к общей локальной службе. Явно указанный сервер, прошедший проверку, показывает только нативный каталог провайдеров и моделей в режиме чтения; управляйте его аутентификацией и конфигурацией непосредственно на сервере, за пределами текущих возможностей CodeNomad. Элементы управления недоступных проектов остаются неактивными; настройки CodeNomad остаются доступными. В локальной службе свёрнутые группы **Модели**, **Поиск в интернете** и **Изображения** читают данные только при раскрытии. + 1. Откройте рабочее пространство, затем **Настройки → Провайдеры**. **Модели** изначально раскрыты; для поисковых провайдеров раскройте **Поиск в интернете**. В **Изображения** собраны настройки изображений. 2. В этой группе нажмите **Выберите провайдера**, затем **Подключить**. 3. Для провайдера моделей выполните предложенный нативный **Способ аутентификации**: API-ключ, OAuth или команду. Для OAuth используйте **Открыть страницу авторизации** и отправляйте код авторизации только по запросу. Поисковые провайдеры подключаются по API-ключу. diff --git a/docs/help/ru/security.md b/docs/help/ru/security.md index 7e1b97316f..94f92b03b9 100644 --- a/docs/help/ru/security.md +++ b/docs/help/ru/security.md @@ -1,5 +1,9 @@ # Аутентификация и безопасность +Выбор вложения читает файл на вашем устройстве; отправка сообщения передаёт его байты на сервер OpenCode проекта. Общий локальный сервис относится к хосту выполнения CodeNomad, который может отличаться от вашего устройства. Чтение отложенных медиа ограничивает весь распакованный ответ сервера, включая ошибки, до 16 MiB перед разбором. Превышение, отмена или отзыв проекта/соединения приводят к отказу чтения. Размеры изображений и память декодированных изображений управляются браузером; загрузки с устройства сохраняют отдельные бюджеты. + +Внутренний чат явно настроенных серверов проверяет медиа до показа или загрузки. Внешние URL изображений, активные SVG/HTML-изображения и HTML-медиавставки отклоняются; загрузка требует вашего действия, а ошибка чтения остаётся ошибкой. Лимит URI данных в 8 МиБ ограничивает кодированный ввод отдельно от размеров декодированного изображения и лимитов отправки с устройства. + Доступ к CodeNomad позволяет выполнять работу на серверном хосте через OpenCode. Считайте пароли сервера, браузерные сессии и сопряжённые устройства мощными учётными данными. CodeNomad — не многопользовательская песочница выполнения. ## Выбор аутентификации сервера {#authentication} diff --git a/docs/help/ru/settings.md b/docs/help/ru/settings.md index fb1587a5e4..b6cdc11623 100644 --- a/docs/help/ru/settings.md +++ b/docs/help/ru/settings.md @@ -2,6 +2,8 @@ ## Открытие настроек и проверка области {#open-settings} +**Выбранный сервер OpenCode** обозначает контекст проекта (`local-shared` для общей локальной службы); настройки CodeNomad остаются общими. Элементы OpenCode недоступного проекта неактивны. Файлы конфигурации, переменные окружения и обслуживание OpenCode относятся к **локальному backend CodeNomad**: файлам HOME, окружению профиля и общей службе. **Управлять локальным backend** явно открывает эти локальные элементы отдельно от выбранного проекта. + 1. Откройте **Настройки** шестерёнкой **Открыть настройки** на панели вкладок (в настольном приложении для macOS — в строке заголовка) или на главной странице. Ярлыки вроде **Управление провайдерами** в переключателе модели, шестерёнки панели миссий или шестерёнки **Настройки** в истории уведомлений сразу открывают нужный раздел. 2. Выберите раздел. Локальные окна Electron и Tauri открывают или фокусируют одно нативное окно настроек; браузерные и удалённые виды используют встроенный экран. 3. Перед уходом проверьте область настройки и наличие действия **Сохранить**. @@ -15,7 +17,9 @@ | Глобальные/проектные настройки OpenCode | Нативные изменения плагинов/конфигурации в показанной области. Для проектных элементов нужен активный проект/Location. | | Профиль настольных данных | Нативные окна, состояние восстановления и хранилище браузера независимо от файла конфигурации и общей службы OpenCode. См. [Настольные окна и данные](desktop.md). | -**Статистика** охватывает всю подключённую службу OpenCode (все проекты, независимые клоны и подсессии), а не только открытую папку, за последние 7, 30, 90 или 365 дней. Ей нужен открытый проект; она показывает записанные OpenCode токены и стоимость, а не счета провайдеров или лимиты подписок; во время обновления могут показываться прежние сохранённые итоги. Квоты планов относятся к разделу статуса **Использование**. +Явно указанные серверы, прошедшие проверку, предоставляют каталог провайдеров и моделей только для чтения. Отложенные разделы остаются доступными для выбора и объясняют свои ограничения; управляйте этими настройками непосредственно на сервере. + +**Статистика** охватывает всю общую локальную службу OpenCode (все проекты, независимые клоны и подсессии), а не только открытую папку, за последние 7, 30, 90 или 365 дней. Ей нужен открытый проект; она показывает записанные OpenCode токены и стоимость, а не счета провайдеров или лимиты подписок; во время обновления могут показываться прежние сохранённые итоги. Квоты планов относятся к разделу статуса **Использование**. **Статистика** недоступна для явно указанных серверов; причина объясняется в самом разделе. Изменение отображения не перезапускает OpenCode и не повторяет запрос. Нативная конфигурация, обслуживание службы и учётные данные имеют отдельные эффекты: см. [настройку OpenCode](opencode.md), [провайдеры](providers.md) и [интеграции](integrations.md). @@ -42,6 +46,8 @@ Статус включает информацию о токенах, режим Yolo, использование провайдера, фоновые оболочки, MCP и плагины. Пока у разговора есть [цель](conversations.md#goal), её показывает строка цели над этими разделами; эта строка не является разделом, её нельзя скрыть или переместить. Скрытие раздела не отключает службу и не отзывает разрешения. Узкие раскладки закрывают панели, которые больше не помещаются, вместо сжатия разговора; панель, открытая в такой раскладке, плавает поверх него, а открытие одной плавающей панели закрывает другую. +Для проекта на настроенном сервере OpenCode эти разделы читают этот сервер. **Использование** показывает нативные квоты OpenCode Go и не требующую учётных данных оценку Zen из раздела [Провайдеры](providers.md#usage); у других провайдеров квота не отображается. **Плагины** перечисляет плагины сервера с их состоянием; их переключатели остаются только для чтения, потому что OpenCode не предоставляет API для изменения конфигурации плагинов сервера. Серверы MCP по-прежнему можно подключать и отключать. **Фоновые оболочки** перечисляет и останавливает оболочки сервера для открытой папки. + Встроенная раскладка — раскладка окна, не изменение проекта. Флажки расширений отличаются: активируют код во всех проектах этой конфигурации. **Сбросить** не меняет согласие на расширения. См. [расширения панели](extensions.md). ## Детализация переписки и размер поля ввода {#transcript-composer} diff --git a/docs/help/ru/troubleshooting.md b/docs/help/ru/troubleshooting.md index 741b0da201..2857072c9e 100644 --- a/docs/help/ru/troubleshooting.md +++ b/docs/help/ru/troubleshooting.md @@ -1,5 +1,9 @@ # Устранение неполадок +Серверы выполнения с одинаковыми именами различайте по постоянному ID рядом с именем в сведениях запроса и уведомлениях проекта. Неопределённый ответ остаётся в исходном редакторе без перехвата фокуса и автоматической повторной отправки. + +**Явно настроенные серверы OpenCode:** после разрыва соединения или перезапуска бэкенда полнота ожидающих запросов неизвестна, даже при пустой панели. Сохраните черновики; устаревшие разрешения ждут актуального запроса в реальном времени. Для известной формы выберите **Проверить состояние этой формы** в исходном редакторе; неопределённый результат блокирует ответы и допускает новую явную проверку. Лимит — 10 секунд целиком и 4 MiB на ответ; полнота остаётся неизвестной. Открытие беседы не ищет пропущенные запросы автоматически. Ответ до разрыва мог быть принят; автоматической повторной отправки нет. Автоматическое восстановление ниже относится к общей локальной службе. См. [Вопросы и разрешения](permissions.md). + Для восстановления сначала проверьте владельца неудачной операции: браузер, серверная часть CodeNomad, служба OpenCode или провайдер. Потерянный ответ не доказывает сбой изменения; перечитайте текущее состояние перед повтором. ## Проблемы запуска настольного приложения {#desktop-launch} diff --git a/docs/help/tr/browser-sidecars.md b/docs/help/tr/browser-sidecars.md index 3902bca804..94e0dad0fc 100644 --- a/docs/help/tr/browser-sidecars.md +++ b/docs/help/tr/browser-sidecars.md @@ -1,5 +1,7 @@ # Tarayıcı önizlemeleri ve SideCars +Açıkça yapılandırılmış sunucuların dahili sohbetindeki bağlantılar, loopback URL’leri dahil, sizin işleminizle açılan harici bağlantılar olarak kalır. Yazılan adresi korur ve tarayıcınızın ağ bağlamını kullanırlar. Bu sohbette ana makine önizlemeleri kullanılamaz; yürütme sunucusuna tünel sağlanmaz. + ## Bir oturum tarayıcısı açın {#session-browser} 1. Konuşmanın araç çubuğunda **Web önizlemesini aç** öğesini seçin. diff --git a/docs/help/tr/conversations.md b/docs/help/tr/conversations.md index 690d12aca1..cf7049be4c 100644 --- a/docs/help/tr/conversations.md +++ b/docs/help/tr/conversations.md @@ -1,11 +1,17 @@ # Konuşmalar +Açıkça yapılandırılmış sunucuların sohbeti, desteklenen gömülü resimleri veya aynı konuşmanın doğrulanmış yerel medyasını gösterir. Diğer kaynaklar kullanılamıyor etiketi gösterir. Yerel yollar yalnızca bu konuşmada zaten tutulan resimleri bulur; `/btw` yalnızca gömülü resimleri kabul eder. Geçerli gömülü dosyalar açık bir indirme işlemi sunar. + CodeNomad, yerel OpenCode oturumlarını, devredilen işler için bir hiyerarşi ve bir sonraki göndereceğiniz şey için ayrı kontrollerle konuşmalar olarak sunar. Mesajlar Markdown, kod, farklar ve desteklenen araç sonucu görüntülerini işler. Metin kopyalama, tam geçmiş araması ve seslendirme gömülü görüntü baytlarını değil, metin izdüşümünü kullanır. **Mesaj içeriği** saklanan parçaları silmeden görünürlüğü değiştirir; [Geçmiş](history.md#operation-reference) görünüm kontrolleriyle temizliği ayırır. Akıl yürütme ve araç başlıkları her adımın ne kadar sürdüğünü gösterir; süre, adım çalışırken canlı olarak sayılır ve bir saniyenin altındaki süreler gösterilmez. **Mesaj içeriği** içinde **Tokenlar** gösterildiğinde (**Her şey** hazır ayarı bunu gösterir), her ajan mesajı son metninden sonra tek bir token ve maliyet satırıyla biter. Bu satır, yüklenmiş konuşma dökümü içinde mesajı ve **Bu yanıttan araçları ve akıl yürütmeyi kaldır** eyleminin kapsadığı araçları ve akıl yürütmeyi içeren mesajları toplar; akıl yürütme ve önbellek sayıları için satırı genişletin. Yalnızca araç çalıştıran adımların kendi satırı yoktur. +Açık sunucunun dahili sohbetinde `@`, o sunucunun aracılarını ve becerilerini sunar ve proje dosyası başvurularının kullanılamadığını açıklar. Bir işlem sırasında bağlantı değişirse kalan adımlar durur. Sonucu belirsiz bir işlemi yeniden göndermeden önce konuşmayı kontrol edin: işlem OpenCode’a ulaşmış olabilir. + +Kesilen veya sonucu belirsiz bir işlem, kaynak konuşmada modal olmayan bir bildirim bırakır ve mevcut odağı korur. Kuyruktaki mesajın düzenlenmesi kesilirse, bilinen içerik açık kaynak konuşmada geri yüklenebilir: kuyruğu kontrol edin, taslağı ve ekleri temizleyip **Kaydedilen mesajı geri yükle** seçeneğini kullanın. Düzenlenebilir bir taslak geri gelir; göndermek ayrı bir işlemdir. Eski `/btw` isteği tamamlandığında açıkça yeni bir soru gönderilebilir. + ## Konuşmaları bulma ve gezinme {#navigate-conversations} 1. **Session'lar** altında satır seçin veya üst konuşma başlatmak için **Yeni session** eylemini kullanın. diff --git a/docs/help/tr/extensions.md b/docs/help/tr/extensions.md index 306ae51bdb..6ebfe37df0 100644 --- a/docs/help/tr/extensions.md +++ b/docs/help/tr/extensions.md @@ -43,6 +43,8 @@ Paketin her değiştirilmesi, izin listesi değişmese bile tüm projelerde etki ## Bağlam, varlık izni ve korumalı alan sınırları {#permissions-sandbox} +API 3 depo öğeleri yalnızca paylaşılan yerel OpenCode hizmetini kullanan projelerde kullanılabilir. Yerel geri döngü sunucuları ve bağlantısı kesilmiş hedefler dahil, açıkça yapılandırılmış tüm OpenCode sunucularında yerel Git desteğinden bağımsız olarak kullanılamaz; istek, ana makinenin Git'ine, kod barındırma platformu oturumlarına veya ağa erişilmeden reddedilir. + | Sözleşme | Etkinleştirmeye izin verilenler | | --- | --- | | API 1 / `session.context` | Geçerli oturum tanımlayıcısı (veya hiçbiri), arayüz dili ve görünümü. Konuşma dökümü metni veya dosya sistemi erişimi yok. | diff --git a/docs/help/tr/files.md b/docs/help/tr/files.md index a1a0248025..fb30475801 100644 --- a/docs/help/tr/files.md +++ b/docs/help/tr/files.md @@ -19,6 +19,10 @@ Genişletilmiş klasörler mod değişikliklerinden etkilenmez. Listeleme/durum/ Satır eylemleri arasında **Yolu kopyala** ve istemcinin arka uç yollarının açılmasını desteklediği durumlarda **Varsayılan uygulamayla aç**, **Klasörde göster**, **Dosya yöneticisinde aç** ve **Burada terminal aç** gibi dosya yöneticisi/düzenleyici/terminal eylemleri bulunur. Alan sınırlı olduğunda eylemler **{name} için daha fazla eylem** öğesine taşınabilir; dosya veya klasör adı `{name}`'nin yerine geçer. Uzak bir tarayıcı, sunucu yolunun yerel aygıt yolu olduğunu varsayamaz; bkz. [Uzaktan Kontrol](remote-control.md). +### OpenCode sunucusundaki projeler {#opencode-server-files} + +Yapılandırılmış bir OpenCode sunucusunda açılan bir proje için **Dosyalar** bu sunucuyu OpenCode API'si üzerinden okur; bu bilgisayarın diskini veya Git'ini asla okumaz. **Çalışma alanı** açılan klasörü salt okunur olarak listeler ve önizler (**Kaydet** yok; önizlemeler 5 MiB'de durur). **Değişiklikler** açılan klasörün ve dalının çalışma kopyası değişikliklerini tek bir **Değişiklikler** listesinde gösterir; stage, commit, **Commitler** veya **Git'i başlat** yoktur. Sunucu eksiksiz ve kesin bir durum bildiremediğinde panel boş bir liste yerine **İçerik kullanılamıyor veya eksik.** gösterir. Ajan dosyaları değiştirdikten sonra **Yenile**'yi kullanın; panel, sunucu dosya veya dal değişikliği bildirdiğinde de yenilenir. Bu bilgisayarda açma eylemleri kullanılamaz durumda kalır. + ## Kaynağı düzenleyin ve güvenle kaydedin {#edit-save} 1. Çalışma Alanındaki bir metin dosyasını göz simgesiyle açın. diff --git a/docs/help/tr/history.md b/docs/help/tr/history.md index 086b537b49..f9bf242d4c 100644 --- a/docs/help/tr/history.md +++ b/docs/help/tr/history.md @@ -2,6 +2,8 @@ Saklanan geçmiş, konuşma dökümünün şu anda görüntüledikleri ve modelin sıkıştırılmış bağlamı ayrıdır. Herhangi bir şeyi silmeden önce gezinmeyi veya filtrelemeyi seçin. +Bu zenginleştirilmiş geçmiş iş akışları paylaşılan yerel OpenCode hizmeti içindir. Açık sunuculardaki projeler yerel API sayfalarını ve yüklenen iletilerin zaman çizelgesini kullanır, bölüm kullanılamadığında kayıtlı okuma konumunu korur ve son sayfaya açıkça dönmeyi sunar. Tam metin araması, yüklenmemiş iletilerin önizlemesi ve teknik temizleme orada kullanılamaz; yüklenmiş metnin önizlemesi kullanılabilir. + ## Tüm geçmişi ara {#full-history-search} 1. Konuşma başlığında **Sohbet geçmişinde ara** öğesini açın veya yapılandırılmış kısayolunu (varsayılan **Ctrl/Cmd+F**) kullanın. diff --git a/docs/help/tr/integrations.md b/docs/help/tr/integrations.md index 93237479b8..8248f1ed9b 100644 --- a/docs/help/tr/integrations.md +++ b/docs/help/tr/integrations.md @@ -1,5 +1,7 @@ # Yerel entegrasyonlar +Aşağıdaki kurulum, uygulama bağlama ve yapılandırma kontrolleri paylaşılan yerel OpenCode projeleri içindir. Açık sunucularda salt okunur eklenti envanteri ve entegrasyon durumu korunur; uygulama bağlama ve kurulum kullanılamaz. + CodeNomad OpenCode'un MCP bağlantılarını, eklenti etkinleştirmesini, becerilerini ve özel komutlarını sunar. Bunlar yürütme ana bilgisayarında çalışır. Korumalı [panel uzantılarından](extensions.md) ve [SideCars](browser-sidecars.md) araçlarından ayrıdır. ## Doğru kontrolü seçin {#integration-scopes} diff --git a/docs/help/tr/permissions.md b/docs/help/tr/permissions.md index 5fcc093abc..09f51f9ace 100644 --- a/docs/help/tr/permissions.md +++ b/docs/help/tr/permissions.md @@ -1,5 +1,11 @@ # Sorular ve izinler +Açık sunucunun bağlamında ad ve kalıcı kimlik bulunur; aynı adlar ayırt edilebilir. Belirsiz veya geçerliliğini yitirmiş yanıtlar istek düzenleyicisinde nazik, modal olmayan bir bildirimle gösterilir; normal hatalar hata gösterimini korur. + +**Açıkça yapılandırılmış OpenCode sunucuları:** sorular ve izinler yalnızca canlı gelir. Taslaklar düzenlenebilir. Eski izinler güncel canlı isteği bekler; bilinen Formlar aşağıdaki açık denetimi sunar. Panelin açılabilir ayrıntıları sınırı açıklar. Konuşmayı açmak eksik istekleri otomatik kurtarmaz. Yolo modu bu sunucularda çalışır: yeniden bağlandıktan sonra CodeNomad yalnızca Yolo görüşmelerinin bekleyen izinlerini yeniden okur ve bunları bir kez onaylar. Aşağıdaki kurtarma ve karar kaydı akışları paylaşılan yerel hizmet içindir. + +Bilinen Formun kaynak düzenleyicisinde **Bu formun durumunu denetle** seçin. Beklediği doğrulanan Form yalnız kendi yanıt/iptal işlemlerini açar; taslağı inceleyip ayrı bir açık hareketle karar verin. Yanıtlanmış veya iptal edilmiş Form taslağı başvuru için korur; başka istemcinin yanıtı, yazarı veya önceki denemenizin sonucu uydurulmaz. Belirsiz denetimde düzenleme açık, yanıt kapalı kalır; açıkça yeniden denetleyebilirsiniz. Her denetim toplam 10 saniye ve yanıt başına 4 MiB ile sınırlıdır; değişen alan şeması da belirsiz kalır. Otomatik denetim veya yeniden gönderim yapılmaz. Genel kapsam bilinmez; eksik Formlar veya izinler bulunmaz. + OpenCode soruları, Formları ve izin istekleri, konuşma dökümündeki bekleyen araç kartlarında değil, ileti düzenleyicisinin hemen üstündeki istek panelinde yanıtlanır. ## İsteği bulun ve kaynağını kontrol edin {#request-dock} diff --git a/docs/help/tr/projects.md b/docs/help/tr/projects.md index 4b20c5e9a2..049358ca4a 100644 --- a/docs/help/tr/projects.md +++ b/docs/help/tr/projects.md @@ -21,6 +21,16 @@ Son kullanılan kayıtlar birer kısayoldur. **Workspace'i yeniden adlandır** g Normal bir tıklama yine de tam ana sayfayı açar. Başlatıcı, yönetim yüzeyi değil, bir kısayoldur: ana sayfadaki son projeleri yeniden adlandırın/kaldırın ve sunucu yer imlerini yönetin. Escape, başlatıcıyı kapatır ve odağı `+`'ye döndürür. +## Bir OpenCode sunucusunda proje açın {#remote-project} + +1. Ana sayfada veya başlatıcıda **UZAKLAR** bölümünü genişletin ve bir sunucuda **+ Proje** seçin. Sunucunun adı klasör yolunun yanında görünür kalır. +2. Bir sunucu seçin, klasörlerine göz atın ve **Aç** seçin. **Backspace** üst klasöre gider; **Esc** sunuculara döner. +3. Sunucu eklemek için `opencode pair` bağlantısını veya `https://opencode:@host:port` adresini **Eşleştirme bağlantısı veya adres** alanına yapıştırın. **Kayıtlı sunucuyu kaldır** için sunucuya sağ tıklayın (veya **Shift+F10**). + +Sekmede sunucu simgesi görünür ve klasör son projelere eklenir. **Klasörlere Göz At**, **Git Deposunu Klonla** ve geçici örnekler bu bilgisayarda kalır. + +Ana makine arka ucu, eşleştirme belirteçlerini ve elle girilen parolaları yeniden başlatmalar arasında `config.yaml` yanındaki özel `opencode-server-pairings.json` (0600) dosyasında saklar. Süre sonu, HTTP 401, kaynak değişikliği veya sunucunun kaldırılması sırrı siler. Kayıtlı projeler kendi sunucularında geri yüklenir; yalnızca ana makine sunucu ekler veya kaldırır. + ## Bir projeyi kapatın {#close-stop} 1. Sekmenin kapat düğmesini veya komut paletindeki **Sekmeyi Kapat** öğesini (arayüzde `Ctrl/Cmd+W`) kullanın. diff --git a/docs/help/tr/providers.md b/docs/help/tr/providers.md index 02facd06a0..34e76718a9 100644 --- a/docs/help/tr/providers.md +++ b/docs/help/tr/providers.md @@ -4,6 +4,8 @@ Sağlayıcı kimlik doğrulaması, tarayıcı cihazına veya bir CodeNomad proje ## Bir modeli veya arama sağlayıcısını bağlayın {#connect} +**Seçili OpenCode sunucusu** bilgisini kontrol edin. Aşağıda açıklanan bağlantı, hesap, web araması ve görsel ayarları ortak yerel hizmet için geçerlidir. Açıkça belirtilmiş ve uygunluğu doğrulanmış bir sunucu yalnızca sunucunun kendi sağlayıcı/model kataloğunu salt okunur olarak gösterir; kimlik doğrulamasını ve yapılandırmasını CodeNomad’in mevcut yetenekleri dışında, doğrudan o sunucuda yönetin. Kullanılamayan projelerin denetimleri devre dışı kalır; CodeNomad tercihleri kullanılabilir. Yerel hizmette daraltılmış **Modeller**, **Web araması** ve **Görseller** grupları, verilerini genişletilene kadar okumaz. + 1. Çalışma alanı açıp **Ayarlar → Provider'lar** yoluna gidin. **Modeller** açık olarak başlar; arama sağlayıcıları için **Web araması** bölümünü genişletin. **Görseller** görsel ayarlarını içerir. 2. O grupta **Provider seç** öğesini, ardından **Bağlan** öğesini seçin. 3. Model sağlayıcısı için sunulan yerel **Kimlik doğrulama yöntemi** öğesini tamamlayın: API anahtarı, OAuth veya komut. OAuth için **Yetkilendirme sayfasını aç** öğesini kullanın ve yalnızca istendiğinde bir yetkilendirme kodu gönderin. Arama sağlayıcıları API anahtarıyla bağlanır. diff --git a/docs/help/tr/security.md b/docs/help/tr/security.md index f8f843f252..a5e6b0dcda 100644 --- a/docs/help/tr/security.md +++ b/docs/help/tr/security.md @@ -1,5 +1,9 @@ # Kimlik doğrulama ve güvenlik +Ek seçimi dosyayı cihazınızda okur; mesajı göndermek baytları projenin OpenCode sunucusuna aktarır. Paylaşılan yerel hizmet, cihazınızdan farklı olabilen CodeNomad yürütme ana makinesine aittir. Ertelenen medya okumaları, hatalar dahil açılmış sunucu yanıtının tamamını ayrıştırmadan önce 16 MiB ile sınırlar. Aşım, iptal veya proje/bağlantı yetkisinin kaldırılması okumayı başarısız kılar. Görsel boyutları ve çözümlenen görsellerin belleği tarayıcı tarafından yönetilir; cihazdan yüklemelerin kendi bütçeleri korunur. + +Açıkça yapılandırılmış sunucuların dahili sohbeti, gösterim veya indirme öncesinde medyayı doğrular. Harici resim URL’leri, etkin SVG/HTML resimleri ve HTML medya gömmeleri reddedilir; indirmeler sizin işleminizi gerektirir ve başarısız okuma başarısız kalır. Veri URI’si başına 8 MiB sınırı, kodlanmış girdiyi çözümlenmiş resim boyutlarından ve cihaz yükleme sınırlarından ayrı sınırlar. + CodeNomad erişimi, OpenCode aracılığıyla arka uç ana bilgisayarında iş yürütmeye olanak tanır. Sunucu parolalarını, tarayıcı oturumlarını ve eşleştirilmiş cihazları güçlü kimlik bilgileri olarak değerlendirin. CodeNomad çok kiracılı bir yürütme korumalı alanı değildir. ## Sunucunun kimlik doğrulama yöntemini seçin {#authentication} diff --git a/docs/help/tr/settings.md b/docs/help/tr/settings.md index 4582cf3c58..2fe92de175 100644 --- a/docs/help/tr/settings.md +++ b/docs/help/tr/settings.md @@ -2,6 +2,8 @@ ## Ayarları açın ve kapsamını belirleyin {#open-settings} +**Seçili OpenCode sunucusu** proje bağlamını belirtir (ortak yerel hizmet için `local-shared`); CodeNomad tercihleri ortak kalır. Kullanılamayan projelerin OpenCode denetimleri etkinleşmez. Yapılandırma dosyaları, ortam değişkenleri ve OpenCode bakımı **yerel CodeNomad arka ucuna** aittir: HOME dosyaları, profil ortamı ve ortak hizmet. **Yerel arka ucu yönet**, bu yerel denetimleri seçili projeden ayrı olarak açıkça açar. + 1. Sekme çubuğundaki (macOS masaüstü uygulamasında başlık çubuğundaki) veya ana sayfadaki **Ayarları aç** dişli simgesiyle **Ayarlar** öğesini açın. Model seçicideki **Provider'ları yönet**, Görevler panelinin dişli simgesi veya bildirim geçmişindeki **Ayarlar** dişli simgesi gibi kısayollar ilgili bölümü doğrudan açar. 2. Bir bölüm seçin. Yerel Electron ve Tauri pencereleri bir yerel Tercihler penceresini açar veya odaklar; tarayıcı ve uzak görünümler yerleşik ayarlar ekranını kullanır. 3. Ayrılmadan önce ayarın kapsamını ve herhangi bir **Kaydet** eylemini kontrol edin. @@ -15,7 +17,9 @@ Her değişikliği siz yaptıkça kaydeden Görev tercihleri dahil, çoğu seçi | Genel/Proje OpenCode ayarları | Görüntülenen kapsamda yerel eklenti/yapılandırma değişiklikleri. Proje kontrolleri etkin bir proje/Location gerektirir. | | Masaüstü veri profili | Yerel pencereler, yapılandırma dosyasından ve paylaşılan OpenCode hizmetinden bağımsız olarak geri yükleme durumu ve tarayıcı depolaması. Bkz. [Masaüstü pencereleri ve veriler](desktop.md). | -**İstatistikler**, yalnızca açılan klasörü değil, bağlı OpenCode hizmetinin tamamını (tüm projeler, bağımsız klonlar ve alt oturumlar) son 7, 30, 90 veya 365 gün için kapsar. Açık bir proje gerektirir ve sağlayıcı faturalarını veya abonelik haklarını değil, OpenCode'un kaydettiği token ve maliyetleri gösterir; yenileme sırasında daha önce kaydedilmiş toplamlar görünebilir. Plan kotaları **Kullanım** Durum bölümüne aittir. +Açıkça belirtilmiş ve uygunluğu doğrulanmış sunucular salt okunur bir sağlayıcı/model kataloğu sunar. Ertelenen bölümler seçilebilir durumda kalır ve kısıtlamalarını açıklar; bu sunucu ayarlarını doğrudan sunucuda yönetin. + +**İstatistikler**, yalnızca açılan klasörü değil, ortak yerel OpenCode hizmetinin tamamını (tüm projeler, bağımsız klonlar ve alt oturumlar) son 7, 30, 90 veya 365 gün için kapsar. Açık bir proje gerektirir ve sağlayıcı faturalarını veya abonelik haklarını değil, OpenCode'un kaydettiği token ve maliyetleri gösterir; yenileme sırasında daha önce kaydedilmiş toplamlar görünebilir. Plan kotaları **Kullanım** Durum bölümüne aittir. **İstatistikler** açıkça belirtilmiş sunucularda kullanılamaz; ilgili bölüm bunun nedenini açıklar. Görüntü tercihlerinin değiştirilmesi OpenCode'u yeniden başlatmaz veya bir istemi yeniden oynatmaz. Yerel yapılandırma, hizmet bakımı ve kimlik bilgilerinin ayrı etkileri vardır: bkz. [OpenCode kurulumu](opencode.md), [Sağlayıcılar](providers.md) ve [Entegrasyonlar](integrations.md). @@ -42,6 +46,8 @@ Tanınan [entegrasyonların](integrations.md#integration-sections) da Durum böl Durum; belirteç bilgilerini, Yolo modunu, sağlayıcı Kullanımı, arka plan kabuklarını, MCP ve Eklentileri içerir. Görüşmenin bir [hedefi](conversations.md#goal) olduğu sürece bu bölümlerin üzerindeki bir hedef satırı onu gösterir; bu satır bir bölüm değildir, gizlenemez ve taşınamaz. Bir bölümün gizlenmesi, o bölümün hizmetini devre dışı bırakmaz veya izinleri iptal etmez. Dar düzenler, konuşmayı sıkıştırmak yerine artık sığmayan panelleri kapatır; orada açılan bir panel konuşmanın üzerinde yüzer ve bir yüzer panelin açılması diğerini kapatır. +Yapılandırılmış bir OpenCode sunucusundaki bir proje için bu bölümler o sunucuyu okur. **Kullanım**, yerel API OpenCode Go kotalarını ve [Sağlayıcılar](providers.md#usage) bölümünde açıklanan kimlik bilgisi gerektirmeyen Zen tahminini gösterir; diğer sağlayıcılar kota göstermez. **Eklentiler** sunucunun eklentilerini durumlarıyla listeler; OpenCode sunucunun eklenti yapılandırmasını değiştirecek bir API sunmadığı için anahtarları salt okunur kalır. MCP sunucularına yine de bağlanılabilir veya bağlantıları kesilebilir. **Arka Plan Shell'leri** açılan klasör için sunucunun shell'lerini listeler ve durdurur. + Yerleşik düzen proje değişikliği değil, pencere yerleşimidir. Uzantı onay kutuları farklıdır: yapılandırmayı kullanan tüm projelerde kodu etkinleştirir. **Sıfırla** uzantı onayını değiştirmez. Bkz. [Panel uzantıları](extensions.md). ## Konuşma dökümü ayrıntıları ve ileti düzenleyicisi boyutu {#transcript-composer} diff --git a/docs/help/tr/troubleshooting.md b/docs/help/tr/troubleshooting.md index 8bb2010719..c210e44761 100644 --- a/docs/help/tr/troubleshooting.md +++ b/docs/help/tr/troubleshooting.md @@ -1,5 +1,9 @@ # Sorun giderme +Aynı adlı yürütme sunucularını istek ayrıntıları ve proje bildirimlerinde adın yanındaki kalıcı kimlikle ayırt edin. Belirsiz yanıt özgün düzenleyicide kalır; odağı değiştirmez ve otomatik yeniden gönderilmez. + +**Açıkça yapılandırılmış OpenCode sunucuları:** bağlantı kesilmesi veya arka uç yeniden başlatılması sonrasında panel boş olsa da bekleyen isteklerin kapsamı bilinmez. Taslakları koruyun; eski izinler güncel canlı isteği bekler. Bilinen Formun kaynak düzenleyicisinde **Bu formun durumunu denetle** kullanın; belirsiz sonuç yanıtı engeller ve yeni bir açık denetime izin verir. Sınır toplam 10 saniye ve yanıt başına 4 MiB'dir; kapsam bilinmez. Konuşmayı açmak eksik istekleri otomatik bulmaz. Önceki yanıt başarılı olmuş olabilir; otomatik tekrar gönderilmez. Aşağıdaki otomatik kurtarma paylaşılan yerel hizmet içindir. [Sorular ve izinler](permissions.md) bölümüne bakın. + Önce başarısız işlemin sahibini kontrol ederek kurtarın: tarayıcı, CodeNomad arka ucu, OpenCode hizmeti veya sağlayıcısı. Kayıp bir yanıt, değişiklik işleminin başarısız olduğunu kanıtlamaz; tekrarlamadan önce mevcut durumu yeniden okuyun. ## Masaüstü başlatma sorunları {#desktop-launch} diff --git a/docs/help/zh-Hans/browser-sidecars.md b/docs/help/zh-Hans/browser-sidecars.md index f39ae34e6f..83ee98cafe 100644 --- a/docs/help/zh-Hans/browser-sidecars.md +++ b/docs/help/zh-Hans/browser-sidecars.md @@ -1,5 +1,7 @@ # 浏览器预览与 SideCar +显式服务器内部聊天中的链接(包括回环 URL)仍是由用户主动打开的外部链接。它们保留原始地址并使用浏览器的网络环境。此聊天中的主机预览不可用,也不提供通往执行服务器的隧道。 + ## 打开会话浏览器 {#session-browser} 1. 在对话工具栏中选择**打开网页预览**。 diff --git a/docs/help/zh-Hans/conversations.md b/docs/help/zh-Hans/conversations.md index 85a66c367a..ea7f3cfaa7 100644 --- a/docs/help/zh-Hans/conversations.md +++ b/docs/help/zh-Hans/conversations.md @@ -1,11 +1,17 @@ # 对话 +显式服务器的聊天显示受支持的内嵌图片,或属于同一对话的已验证原生媒体。其他来源显示不可用提示。本地路径只能匹配该对话中已持有的图片;`/btw` 仅接受内嵌图片。有效的内嵌文件提供需主动操作的下载。 + CodeNomad 将原生 OpenCode 会话呈现为对话,为委派工作提供层级结构,并单独控制下一次发送的内容。 消息可呈现 Markdown、代码、差异和受支持的工具结果图片。文本复制、完整历史搜索和语音使用文本投影,而非嵌入的图片字节。**消息内容**只更改可见性,不会删除已存储部分;[历史记录](history.md#operation-reference)区分了显示控件和清理操作。 推理和工具标题会显示每个步骤所用的时间,运行期间实时计时;不足一秒的时长不显示。当**消息内容**中显示**令牌**时(**全部**预设会显示),每条智能体消息会在其最终文本之后以一行令牌和费用信息结束。该行合计这条消息,以及其**从此回复中删除工具和推理**操作所涵盖的、包含工具和推理的消息,范围限于已加载的对话记录;展开该行可查看推理和缓存计数。仅运行了工具的步骤没有单独的这一行。 +在显式服务器的内部聊天中,`@` 提供该服务器的智能体和技能,并说明项目文件引用不可用。操作期间连接发生变化时,剩余步骤将停止。重新发送结果不确定的操作前,请先检查会话:该操作可能已到达 OpenCode。 + +操作中断或结果不确定时,原会话会显示非模态提示,并保留当前焦点。如果排队消息的编辑中断,已知内容仍可在打开的原会话中恢复:请检查队列,清空草稿和附件,然后选择**恢复已保存的消息**。这会恢复可编辑的草稿,发送仍需单独操作。过期的 `/btw` 请求结束后,可以主动提交新的问题。 + ## 查找和导航对话 {#navigate-conversations} 1. 选择**会话**下的一行,或使用**新建会话**开始父对话。 diff --git a/docs/help/zh-Hans/extensions.md b/docs/help/zh-Hans/extensions.md index 55741e60b9..741e3e4d6a 100644 --- a/docs/help/zh-Hans/extensions.md +++ b/docs/help/zh-Hans/extensions.md @@ -43,6 +43,8 @@ ## 上下文、资源同意和沙箱限制 {#permissions-sandbox} +API 3 仓库条目仅适用于使用共享本地 OpenCode 服务的项目。对于所有显式配置的 OpenCode 服务器,包括回环服务器和已断开的目标,无论其原生 Git 支持情况如何,这些条目均不可用;请求会在访问宿主机 Git、代码托管平台登录信息或网络之前被拒绝。 + | 契约 | 激活允许的内容 | | --- | --- | | API 1 / `session.context` | 当前会话标识符(或无)、界面语言和外观。无对话文本或文件系统访问。 | diff --git a/docs/help/zh-Hans/files.md b/docs/help/zh-Hans/files.md index df212d09d2..aa80f1f2ab 100644 --- a/docs/help/zh-Hans/files.md +++ b/docs/help/zh-Hans/files.md @@ -19,6 +19,10 @@ 行操作包括**复制路径**,以及在客户端支持打开后端路径时可用的文件管理器/编辑器/终端操作,如**使用默认应用打开**、**在文件夹中显示**、**在文件管理器中打开**和**在此处打开终端**。空间不足时,操作可能移入 **{name}的更多操作**;文件或文件夹名替换 `{name}`。远程浏览器不能假定服务器路径就是本地设备路径;参阅[远程控制](remote-control.md)。 +### OpenCode 服务器上的项目 {#opencode-server-files} + +对于在已配置 OpenCode 服务器上打开的项目,**文件**通过该服务器的 OpenCode API 读取该服务器,绝不读取本机的磁盘或 Git。**工作区**以只读方式列出并预览打开的文件夹(没有**保存**;预览上限为 5 MiB)。**更改**在一个**更改**列表中显示打开的文件夹及其分支的工作副本更改,没有暂存、提交操作、**提交**或**初始化 Git**。当服务器无法报告完整、明确的状态时,面板会显示**内容不可用或不完整。**,而不是空列表。代理更改文件后请使用**刷新**;服务器报告文件或分支更改时,面板也会刷新。在本机打开的操作仍不可用。 + ## 编辑源码并安全保存 {#edit-save} 1. 使用眼睛操作打开工作区文本文件。 diff --git a/docs/help/zh-Hans/history.md b/docs/help/zh-Hans/history.md index 7313ef80a8..58c224189e 100644 --- a/docs/help/zh-Hans/history.md +++ b/docs/help/zh-Hans/history.md @@ -2,6 +2,8 @@ 已存储历史、对话当前显示的内容和模型压缩后的上下文彼此独立。删除任何内容前,先考虑导航或筛选。 +这些增强历史功能适用于共享本地 OpenCode 服务。显式服务器上的项目使用原生分页和已加载消息的时间线,在段落不可用时保留已保存的阅读位置,并提供明确打开最新页面的恢复操作。历史全文搜索、未加载消息的预览和技术内容清理仍不可用;已加载文本的预览仍可使用。 + ## 搜索完整历史 {#full-history-search} 1. 在对话标题栏打开**搜索聊天历史**,或使用其配置的快捷键(默认 **Ctrl/Cmd+F**)。 diff --git a/docs/help/zh-Hans/integrations.md b/docs/help/zh-Hans/integrations.md index c925367cb5..9e17b71951 100644 --- a/docs/help/zh-Hans/integrations.md +++ b/docs/help/zh-Hans/integrations.md @@ -1,5 +1,7 @@ # 原生集成 +以下安装、应用连接和配置操作适用于共享本地 OpenCode 项目。显式服务器保留只读插件清单和集成状态,应用连接和安装操作在这些服务器上不可用。 + CodeNomad 提供 OpenCode 的原生 MCP 连接、插件激活、技能和自定义命令。这些在执行主机上运行,与沙箱[面板扩展](extensions.md)和 [SideCar](browser-sidecars.md) 分开。 ## 选择正确的控件 {#integration-scopes} diff --git a/docs/help/zh-Hans/permissions.md b/docs/help/zh-Hans/permissions.md index cbb10a2129..c603ce4667 100644 --- a/docs/help/zh-Hans/permissions.md +++ b/docs/help/zh-Hans/permissions.md @@ -1,5 +1,11 @@ # 问题与权限 +显式服务器的上下文包含名称和稳定 ID,因此可以区分同名服务器。不确定或已失效的回答会在请求编辑区中以非模态、低优先级通知显示;普通失败仍按错误处理。 + +**显式配置的 OpenCode 服务器:** 问题和权限请求仅实时到达。草稿仍可编辑。过期权限请求须等待当前实时请求;已知 Form 可按下述方式主动检查。停靠区的可展开详情会解释此限制。打开会话可以查看内容,不会自动恢复缺失的请求。Yolo 模式可在这些服务器上使用:重新连接后,CodeNomad 仅重新读取 Yolo 对话的待处理权限请求,并只批准一次。下述恢复和决策记录工作流程适用于共享本地服务。 + +对于已知 Form,请在其来源编辑区选择 **检查此表单的状态**。验证为仍在等待的 Form 只会启用自身操作;请检查草稿,再主动回答或取消。已回答或已取消的 Form 会保留草稿供参考,不展示其他客户端的回答,也不推断作者或你之前尝试的结果。无法确认时仍可编辑,但回答保持禁用;你可以主动再次检查。每次检查总限时 10 秒,每个响应最多 4 MiB;字段结构变化也视为无法确认。不会自动检查或重发。总体覆盖情况仍未知;此检查不会发现缺失的 Form 或权限请求。 + 原生问题、Form 和权限请求在紧邻输入框上方的中断停靠区中回答,而非在待处理的对话工具卡片内回答。 ## 找到请求并检查来源 {#request-dock} diff --git a/docs/help/zh-Hans/projects.md b/docs/help/zh-Hans/projects.md index 6d3ecd00cf..89b7d41d51 100644 --- a/docs/help/zh-Hans/projects.md +++ b/docs/help/zh-Hans/projects.md @@ -21,6 +21,16 @@ 普通点击仍会打开完整主页。启动器是快捷入口,而非管理界面:请在主页重命名/移除最近项目和管理服务器书签。Escape 会关闭启动器并将焦点返回 `+`。 +## 在 OpenCode 服务器上打开项目 {#remote-project} + +1. 在主页或启动器中展开 **远程**,然后选择服务器上的 **+ 项目**。服务器名称会一直显示在文件夹路径旁。 +2. 选择服务器,浏览其文件夹,然后选择 **打开**。**Backspace** 返回上级文件夹;**Esc** 返回服务器列表。 +3. 要添加服务器,请将其 `opencode pair` 链接或 `https://opencode:<密码>@host:port` 粘贴到 **配对链接或地址**。右键单击服务器(或按 **Shift+F10**)可选择 **删除已保存服务器**。 + +该标签页带有服务器图标,文件夹会加入最近项目。**浏览文件夹**、**克隆 Git 仓库** 和临时实例仍留在本机。 + +主机后端将配对令牌和手动输入的密码保存在 `config.yaml` 旁的私有文件 `opencode-server-pairings.json`(0600)中,重启后继续使用。过期、HTTP 401、来源地址变更或移除服务器时会清除秘密。已保存的项目在各自服务器上恢复;只有主机可以添加或移除服务器。 + ## 关闭标签页以关闭项目 {#close-stop} 1. 使用标签页关闭按钮或命令面板中的**关闭标签页**(渲染器中为 `Ctrl/Cmd+W`)。 diff --git a/docs/help/zh-Hans/providers.md b/docs/help/zh-Hans/providers.md index d81ffd8dd4..1b4aa1af63 100644 --- a/docs/help/zh-Hans/providers.md +++ b/docs/help/zh-Hans/providers.md @@ -4,6 +4,8 @@ ## 连接模型或搜索提供商 {#connect} +检查**所选 OpenCode 服务器**。下述连接、账户、网页搜索和图像设置适用于共享本地服务。通过资格检查的显式指定服务器仅显示只读的原生提供商和模型目录;请直接在该服务器上管理认证和配置,这超出了 CodeNomad 当前的能力范围。不可用项目的控件保持停用;CodeNomad 偏好设置仍可使用。在本地服务上,折叠的**模型**、**网页搜索**和**图像**分组会等到展开后才读取数据。 + 1. 打开工作区,然后打开**设置 → 提供商**。**模型**默认展开;搜索提供商请展开**网页搜索**。**图像**包含图像设置。 2. 在该组中选择**选择提供商**,然后选择**连接**。 3. 对于模型提供商,完成提供的原生**认证方式**:API 密钥、OAuth 或命令。对于 OAuth,使用**打开授权页面**,仅在要求时提交授权码。搜索提供商通过 API 密钥连接。 diff --git a/docs/help/zh-Hans/security.md b/docs/help/zh-Hans/security.md index ca7714e193..5d2c498db4 100644 --- a/docs/help/zh-Hans/security.md +++ b/docs/help/zh-Hans/security.md @@ -1,5 +1,9 @@ # 认证与安全 +选择附件时在设备上读取文件,发送消息时才将字节传输到项目的 OpenCode 服务器。共享本地服务位于 CodeNomad 执行主机上,该主机可能不是您当前使用的设备。延迟媒体读取在解析前将解压后的整个服务器响应限制为 16 MiB,包括错误响应。超限、取消或项目/连接权限失效都会使读取失败。图片尺寸和解码图片所需的内存由浏览器管理;设备上传仍受独立预算约束。 + +显式服务器的内部聊天在显示或下载前验证媒体。外部图片 URL、活动 SVG/HTML 图片和 HTML 媒体嵌入会被拒绝;下载需要主动操作,读取失败会保持失败状态。每个数据 URI 的 8 MiB 上限约束编码输入,与解码后的图片尺寸及设备上传限额相互独立。 + 访问 CodeNomad 可以通过 OpenCode 在后端主机上执行工作。请将服务器密码、浏览器会话和配对设备视为强权限凭据。CodeNomad 不是多租户执行沙箱。 ## 选择服务器认证方式 {#authentication} diff --git a/docs/help/zh-Hans/settings.md b/docs/help/zh-Hans/settings.md index 03fab84dfa..33a7966a61 100644 --- a/docs/help/zh-Hans/settings.md +++ b/docs/help/zh-Hans/settings.md @@ -2,6 +2,8 @@ ## 打开设置并识别范围 {#open-settings} +**所选 OpenCode 服务器**标识项目上下文(共享本地服务为 `local-shared`);CodeNomad 偏好设置仍由所有项目共享。不可用项目的 OpenCode 控件保持停用。配置文件、环境变量和 OpenCode 维护明确属于**本地 CodeNomad 后端**:HOME 文件、配置环境和共享服务。**管理本地后端**会明确打开这些本地控件,与所选项目分开管理。 + 1. 使用标签栏(macOS 桌面应用中为标题栏)或主页上的**打开设置**齿轮打开**设置**。模型选择器中的**管理提供商**、任务面板齿轮或通知历史中的**设置**齿轮等快捷入口会直接打开相应部分。 2. 选择部分。本地 Electron 和 Tauri 窗口会打开或聚焦唯一的原生偏好设置窗口;浏览器和远程视图使用内嵌设置界面。 3. 离开前检查设置范围及所有**保存**操作。 @@ -15,7 +17,9 @@ | 全局/项目 OpenCode 设置 | 在显示范围内的原生插件/配置更改。项目控件要求活动项目/Location。 | | 桌面数据配置文件 | 原生窗口、恢复状态和浏览器存储,独立于配置文件和共享 OpenCode 服务。参阅[桌面窗口与数据](desktop.md)。 | -**统计**涵盖整个已连接的 OpenCode 服务(所有项目、独立克隆和子会话),而不仅是已打开的文件夹,时间范围为最近 7、30、90 或 365 天。它需要打开一个项目,显示的是 OpenCode 记录的令牌和费用,而非提供商账单或订阅额度;刷新期间可能显示先前保存的总计。计划配额属于**用量**状态部分。 +通过资格检查的显式指定服务器提供只读的提供商和模型目录。暂缓支持的部分仍可选择,并会说明其限制;请直接在服务器上管理这些设置。 + +**统计**涵盖整个共享本地 OpenCode 服务(所有项目、独立克隆和子会话),而不仅是已打开的文件夹,时间范围为最近 7、30、90 或 365 天。它需要打开一个项目,显示的是 OpenCode 记录的令牌和费用,而非提供商账单或订阅额度;刷新期间可能显示先前保存的总计。计划配额属于**用量**状态部分。显式指定的服务器无法使用**统计**;该部分会说明原因。 更改显示偏好不会重启 OpenCode 或重放提示词。原生配置、服务维护和凭据有各自影响:参阅 [OpenCode 设置](opencode.md)、[提供商](providers.md)和[集成](integrations.md)。 @@ -42,6 +46,8 @@ 状态包含 Token 信息、Yolo 模式、提供商用量、后台 Shell、MCP 和插件。只要对话有[目标](conversations.md#goal),这些部分上方就会有一行显示它;该行不是部分,无法隐藏或移动。隐藏部分不会禁用服务或撤销权限。窄布局会关闭放不下的面板,而非挤压对话;在此布局中打开的面板浮于对话之上,打开一个浮动面板会关闭另一个。 +对于已配置 OpenCode 服务器上的项目,这些部分读取该服务器。**用量**显示原生 OpenCode Go 配额及[提供商](providers.md#usage)中说明的无需凭据的 Zen 估算值;其他提供商不显示配额。**插件**列出服务器的插件及其状态;由于 OpenCode 未提供更改服务器插件配置的 API,其开关保持只读。仍可连接或断开 MCP 服务器。**后台 Shell** 列出并停止服务器上打开文件夹的 Shell。 + 内置布局属于窗口布局,而非项目修改。扩展复选框不同:它们会为使用该配置的全部项目激活代码。**重置**不改变扩展同意。参阅[面板扩展](extensions.md)。 ## 对话详情与输入框尺寸 {#transcript-composer} diff --git a/docs/help/zh-Hans/troubleshooting.md b/docs/help/zh-Hans/troubleshooting.md index 53d22b93da..73b4b342dc 100644 --- a/docs/help/zh-Hans/troubleshooting.md +++ b/docs/help/zh-Hans/troubleshooting.md @@ -1,5 +1,9 @@ # 故障排查 +同名执行服务器可通过请求详情和项目通知中名称旁的稳定 ID 区分。不确定的回答会保留在原编辑区,不会抢占焦点或自动重发。 + +**显式配置的 OpenCode 服务器:** 连接中断或后端重启后,即使停靠区为空,等待中请求的覆盖情况也未知。请保留草稿;过期权限请求须等待当前实时请求。对于已知 Form,请在来源编辑区使用 **检查此表单的状态**;无法确认时回答仍被禁用,但可主动再次检查。每次总限时 10 秒,每个响应最多 4 MiB;覆盖情况仍未知。打开会话不会自动找到缺失的请求。中断前的回答可能已成功,不会自动重发。下述自动恢复步骤适用于共享本地服务。请参阅[问题与权限](permissions.md)。 + 恢复时先检查失败操作由谁负责:浏览器、CodeNomad 后端、OpenCode 服务或提供商。回复丢失不证明修改失败;重复前先重读当前状态。 ## 桌面启动问题 {#desktop-launch} diff --git a/packages/electron-app/electron/main/client-state-attachment-metadata.ts b/packages/electron-app/electron/main/client-state-attachment-metadata.ts new file mode 100644 index 0000000000..2f5b21f905 --- /dev/null +++ b/packages/electron-app/electron/main/client-state-attachment-metadata.ts @@ -0,0 +1,47 @@ +import type { ClientWindowStateRecord } from "./client-state-envelope" +import { isPartitionKey, validateClientStatePartitionRoot } from "./client-state-partitions" + +export interface RetainedProjectMetadata { index: number; serverId: string; directory: string; occurrence?: number } +const object = (value: unknown): value is Record => Boolean(value) && typeof value === "object" && !Array.isArray(value) +const onlyKeys = (value: Record, keys: string[]) => Object.keys(value).every(key => keys.includes(key)) + +/** Only the tab manifest is inspected. Never follow workspace/session/blob partitions. */ +export async function retainedProjectMetadata(record: ClientWindowStateRecord, load: (key: string) => Promise): Promise { + if (!record.restoreEnabled) return [] + if (!object(record.snapshot)) return + const root = record.snapshot + let session: unknown + const partitioned = record.partitionProtocolVersion === 1 + if (partitioned) { + const keys = validateClientStatePartitionRoot(root) + if (!keys || typeof root.sessionPartition !== "string" || !record.partitionKeys?.includes(root.sessionPartition)) return + const text = await load(root.sessionPartition) + if (text === null) return + let manifest: unknown + try { manifest = JSON.parse(text) } catch { return } + if (!object(manifest) || manifest.format !== 2 || !onlyKeys(manifest, ["format", "session"])) return + session = manifest.session + } else { + if (root.version !== undefined && root.version !== 1) return + session = root.session + } + if (session === null) return [] + if (!object(session) || !Array.isArray(session.tabs) || session.tabs.length > 32 + || !onlyKeys(session, ["tabs", "activeTabIndex", "homeActive"]) || !Number.isInteger(session.activeTabIndex) + || Number(session.activeTabIndex) < -1 || Number(session.activeTabIndex) >= session.tabs.length + || session.homeActive !== undefined && typeof session.homeActive !== "boolean") return + const result: RetainedProjectMetadata[] = [] + for (const [index, tab] of session.tabs.entries()) { + if (!object(tab)) return + const kind = tab.kind ?? tab.type + if (kind === "sidecar") { if (typeof tab.sidecarId !== "string" || !tab.sidecarId || tab.sidecarId.length > 512) return; continue } + if (kind !== "workspace" && (partitioned || kind !== "instance")) return + if (typeof tab.folder !== "string" || !tab.folder.trim() || tab.folder.length > 4096 || tab.folder.includes("\0")) return + if (tab.serverId !== undefined && (typeof tab.serverId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(tab.serverId))) return + if (tab.occurrence !== undefined && (!Number.isInteger(tab.occurrence) || Number(tab.occurrence) < 0 || Number(tab.occurrence) >= 32)) return + if (partitioned && (!isPartitionKey(tab.workspacePartition) || !record.partitionKeys?.includes(tab.workspacePartition))) return + result.push({ index, serverId: (tab.serverId as string | undefined) ?? "local-shared", directory: tab.folder, + ...(tab.occurrence === undefined ? {} : { occurrence: Number(tab.occurrence) }) }) + } + return result +} diff --git a/packages/electron-app/electron/main/client-state-attachment-vector.json b/packages/electron-app/electron/main/client-state-attachment-vector.json new file mode 100644 index 0000000000..1b679edb31 --- /dev/null +++ b/packages/electron-app/electron/main/client-state-attachment-vector.json @@ -0,0 +1,21 @@ +{ + "root": { + "version": 2, + "revision": 1, + "savedAt": 1, + "layout": {}, + "sessionPartition": "4d77c030cf26b6b3396377510bf82efdd83c22615f93833bb48bbc35e8786df0", + "partitionKeys": [ + "4d77c030cf26b6b3396377510bf82efdd83c22615f93833bb48bbc35e8786df0", + "f38de955f3e6fcde33d55c4d3ff9981c23c4935c5079e10f096cba491a25777a" + ] + }, + "partitions": { + "4d77c030cf26b6b3396377510bf82efdd83c22615f93833bb48bbc35e8786df0": "{\"format\":2,\"session\":{\"activeTabIndex\":0,\"tabs\":[{\"folder\":\"Z:\\\\Case\\\\Project/ \",\"kind\":\"workspace\",\"serverId\":\"unknown-A\",\"workspacePartition\":\"f38de955f3e6fcde33d55c4d3ff9981c23c4935c5079e10f096cba491a25777a\"}]}}", + "f38de955f3e6fcde33d55c4d3ff9981c23c4935c5079e10f096cba491a25777a": "{\"format\":2,\"sessions\":{}}" + }, + "partitionKeys": [ + "4d77c030cf26b6b3396377510bf82efdd83c22615f93833bb48bbc35e8786df0", + "f38de955f3e6fcde33d55c4d3ff9981c23c4935c5079e10f096cba491a25777a" + ] +} diff --git a/packages/electron-app/electron/main/client-state-cross-host-child.ts b/packages/electron-app/electron/main/client-state-cross-host-child.ts index 079032bb40..9d13ac827e 100644 --- a/packages/electron-app/electron/main/client-state-cross-host-child.ts +++ b/packages/electron-app/electron/main/client-state-cross-host-child.ts @@ -3,6 +3,7 @@ import { CrossHostRegistration, createCrossHostOwner } from "./client-state-cros import { getProcessStartIdentity } from "./client-state-process-identity" import { isPidAlive } from "./client-state-process" import { ClientStateManager } from "./client-state" +import { requirePreferencesRequest } from "./preferences-window" const [directory, startPath, readyPath, mode, userDataPath, participantReadyPath, participantContinuePath, legacyTauriDataPath, operation, payload] = process.argv.slice(2) if (!directory || !startPath) throw new Error("Expected election directory and start path") @@ -36,9 +37,14 @@ if (manager?.isPrimary && operation === "save") { await manager.setRestoreEnabled(true) await manager.saveClientState(JSON.parse(payload)) } +if (manager?.isPrimary && operation === "save-preferences") { + const request = JSON.parse(payload) + await manager.setPreferences(requirePreferencesRequest(request.section, request)) +} process.stdout.write(`${JSON.stringify({ acquired: manager?.isPrimary ?? Boolean(registration?.isPrimary), state: operation === "load" ? manager?.loadClientState() : undefined, + preferences: operation === "load" ? manager?.preferences : undefined, })}\n`) process.stdin.resume() process.stdin.once("end", () => { diff --git a/packages/electron-app/electron/main/client-state-partitions-bound.test.ts b/packages/electron-app/electron/main/client-state-partitions-bound.test.ts new file mode 100644 index 0000000000..d014e9465a --- /dev/null +++ b/packages/electron-app/electron/main/client-state-partitions-bound.test.ts @@ -0,0 +1,158 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { createHash } from "node:crypto" +import fs from "node:fs/promises" +import { appendFileSync, mkdirSync, mkdtempSync, rmSync, rmdirSync, symlinkSync, truncateSync, writeFileSync } from "node:fs" +import { join } from "node:path" +import { syncBuiltinESMExports } from "node:module" +import { ClientStatePartitionStore } from "./client-state-partitions" +import { ClientStateManager } from "./client-state" +import { DesktopAttachments } from "./desktop-attachments" +import { LocalWindowRegistry } from "./local-window-registry" +import vector from "./client-state-attachment-vector.json" + +const limit = 1024 * 1024 +const digest = (bytes: string) => createHash("sha256").update(bytes).digest("hex") + +test("verified partitions bound real reads before retain/hash/concat and close every handle", async t => { + const root = mkdtempSync(join(process.cwd(), ".tmp/partition-bound-")) + t.after(() => rmSync(root, { recursive: true, force: true })) + t.after(() => { t.mock.restoreAll(); syncBuiltinESMExports() }) + mkdirSync(join(root, "partitions")) + const store = new ClientStatePartitionStore(root) + const open = fs.open + let readBytes = 0, maxRead = 0, closes = 0, failRead = false + t.mock.method(fs, "open", async (...args: Parameters) => { + const file = await open(...args) + const read = file.read.bind(file) + const close = file.close.bind(file) + t.mock.method(file, "read", async (buffer: Buffer, offset: number, length: number, position: number | null) => { + maxRead = Math.max(maxRead, length) + if (failRead) throw new Error("owned read failure") + const result = await read(buffer, offset, length, position) + readBytes += result.bytesRead + return result + }) + t.mock.method(file, "close", async () => { closes++; await close() }) + return file + }) + syncBuiltinESMExports() + for (const size of [0, limit, limit + 1, 16 * limit]) { + const content = size <= limit + 1 ? "x".repeat(size) : "large" + const key = digest(content), path = join(root, "partitions", key) + writeFileSync(path, content) + if (size > limit + 1) truncateSync(path, size) + readBytes = maxRead = closes = 0 + assert.equal(await store.load(key, () => {}), size <= limit ? content : null) + assert.ok(readBytes <= limit + 1) + assert.ok(maxRead <= 64 * 1024) + assert.equal(closes, 1) + rmSync(path) + writeFileSync(path, content) + if (size <= limit) assert.equal(await store.load(key, () => {}), content, "fresh positive after rejection") + rmSync(path) + } + const content = "été", key = digest(content), path = join(root, "partitions", key) + writeFileSync(path, content) + assert.equal(await store.load(key, () => {}), content) + writeFileSync(path, "wrong hash") + closes = 0 + assert.equal(await store.load(key, () => {}), null) + assert.equal(closes, 1) + writeFileSync(path, content) + closes = 0; failRead = true + await assert.rejects(store.load(key, () => {}), /owned read failure/) + assert.equal(closes, 1) + failRead = false; closes = 0 + await assert.rejects(store.load(key, () => { throw new Error("retired authority") }), /retired authority/) + assert.equal(closes, 1) + assert.equal(await store.load(key, () => {}), content) +}) + +test("partition growth after lstat is bounded; symlink/type guards and fresh reads survive", async t => { + const root = mkdtempSync(join(process.cwd(), ".tmp/partition-growth-")) + t.after(() => rmSync(root, { recursive: true, force: true })) + t.after(() => { t.mock.restoreAll(); syncBuiltinESMExports() }) + const directory = join(root, "partitions") + mkdirSync(directory) + const content = "valid", key = digest(content), path = join(directory, key) + const store = new ClientStatePartitionStore(root) + writeFileSync(path, content) + const lstat = fs.lstat + let grow = true + const spy = t.mock.method(fs, "lstat", async (...args: Parameters) => { + const result = await lstat(...args) + if (String(args[0]) === path && grow) { + grow = false + appendFileSync(path, "x".repeat(4 * limit)) + } + return result + }) + const open = fs.open + let bytes = 0 + t.mock.method(fs, "open", async (...args: Parameters) => { + const file = await open(...args), read = file.read.bind(file) + t.mock.method(file, "read", async (buffer: Buffer, offset: number, length: number, position: number | null) => { + const result = await read(buffer, offset, length, position) + bytes += result.bytesRead + return result + }) + return file + }) + syncBuiltinESMExports() + assert.equal(await store.load(key, () => {}), null) + assert.equal(bytes, limit + 1) + spy.mock.restore() + syncBuiltinESMExports() + rmSync(path) + mkdirSync(path) + assert.equal(await store.load(key, () => {}), null) + rmdirSync(path) + const target = join(root, "target") + writeFileSync(target, content) + symlinkSync(target, path, "file") + assert.equal(await store.load(key, () => {}), null) + rmSync(path) + writeFileSync(path, content) + assert.equal(await store.load(key, () => {}), content) + rmSync(directory, { recursive: true }) + const other = join(root, "other") + mkdirSync(other) + symlinkSync(other, directory, process.platform === "win32" ? "junction" : "dir") + await assert.rejects(store.load(key, () => {}), /Invalid client state partition directory/) + rmSync(directory, { recursive: true }) + mkdirSync(directory) + writeFileSync(path, content) + assert.equal(await store.load(key, () => {}), content) +}) + +test("real retained owner accepts exact-limit manifest, rejects +1 and recovers without content reads", async t => { + const root = mkdtempSync(join(process.cwd(), ".tmp/manifest-limit-")) + mkdirSync(join(root, "partitions")) + const original = vector.partitions[vector.root.sessionPartition as keyof typeof vector.partitions] + const manifest = original + " ".repeat(limit - Buffer.byteLength(original)) + const key = digest(manifest) + const keys = vector.partitionKeys.map(old => old === vector.root.sessionPartition ? key : old).sort() + writeFileSync(join(root, "client-state.json"), JSON.stringify({ version: 2, restoreEnabled: true, protocolVersion: 1, + snapshot: { ...vector.root, sessionPartition: key, partitionKeys: keys }, partitionKeys: keys })) + const path = join(root, "partitions", key) + writeFileSync(path, manifest) + // Workspace partition is deliberately absent: metadata must only open the manifest. + const state = new ClientStateManager(root, undefined, { crossHostElectionDirectory: join(root, "election") }) + t.after(async () => { await state.drainAndReleasePrimary(); rmSync(root, { recursive: true, force: true }) }) + const owner = new DesktopAttachments(state, new LocalWindowRegistry(() => {})) + const first = await owner.read() + assert.equal(first.retainedStatus, "complete") + assert.equal(first.refs.length, 1) + assert.equal(owner.current(first.receipt), true) + appendFileSync(path, " ") + const refused = await owner.read() + assert.equal(refused.retainedStatus, "unknown") + assert.equal(owner.current(first.receipt), false) + writeFileSync(path, manifest) + const fresh = await owner.read() + assert.equal(fresh.retainedStatus, "complete") + assert.equal(fresh.status, "unknown") + assert.equal(owner.current(fresh.receipt), true) + assert.equal(owner.current(refused.receipt), false) +}) diff --git a/packages/electron-app/electron/main/client-state-partitions.ts b/packages/electron-app/electron/main/client-state-partitions.ts index df4a482c27..9aeff85fba 100644 --- a/packages/electron-app/electron/main/client-state-partitions.ts +++ b/packages/electron-app/electron/main/client-state-partitions.ts @@ -1,5 +1,5 @@ import { createHash, randomUUID } from "node:crypto" -import { link, lstat, mkdir, open, readFile, readdir, rm, unlink } from "node:fs/promises" +import { link, lstat, mkdir, open, readdir, rm, unlink } from "node:fs/promises" import { join } from "node:path" import { hasErrorCode } from "./client-state-process" @@ -175,9 +175,26 @@ export class ClientStatePartitionStore { const path = join(this.directory, key) const stats = await lstat(path) if (!stats.isFile() || stats.isSymbolicLink()) return null - const bytes = await readFile(path) - if (bytes.length > MAX_PARTITION_BYTES || digest(bytes) !== key) return null - return bytes.toString("utf8") + const file = await open(path, "r") + try { + const chunk = Buffer.allocUnsafe(64 * 1024) + const chunks: Buffer[] = [] + const hash = createHash("sha256") + let size = 0 + for (;;) { + const { bytesRead } = await file.read(chunk, 0, Math.min(chunk.length, MAX_PARTITION_BYTES + 1 - size), null) + if (bytesRead === 0) break + size += bytesRead + if (size > MAX_PARTITION_BYTES) return null + const bytes = chunk.subarray(0, bytesRead) + hash.update(bytes) + chunks.push(Buffer.from(bytes)) + } + if (hash.digest("hex") !== key) return null + return Buffer.concat(chunks, size).toString("utf8") + } finally { + await file.close() + } } catch (error) { if (hasErrorCode(error, "ENOENT")) return null throw error diff --git a/packages/electron-app/electron/main/client-state.test.ts b/packages/electron-app/electron/main/client-state.test.ts index 69462340c9..56c5b036f4 100644 --- a/packages/electron-app/electron/main/client-state.test.ts +++ b/packages/electron-app/electron/main/client-state.test.ts @@ -37,6 +37,7 @@ test("Preferences restoration survives final local-window shutdown and clears on const manager = h.create() const request = { section: "providers" as const, + serverId: "unknown-A", scrollTop: 420, instanceId: "instance-1", workspacePath: "C:\\repo", diff --git a/packages/electron-app/electron/main/client-state.ts b/packages/electron-app/electron/main/client-state.ts index ce35d9b79a..79aa50f1e5 100644 --- a/packages/electron-app/electron/main/client-state.ts +++ b/packages/electron-app/electron/main/client-state.ts @@ -44,6 +44,7 @@ import { type PersistedClientState, } from "./client-state-envelope" import type { PreferencesRequest } from "./preferences-window" +import { retainedProjectMetadata } from "./client-state-attachment-metadata" const CLIENT_STATE_FILENAME = "client-state.json" const PRIMARY_LOCK_FILENAME = "client-state.primary.lock" @@ -134,6 +135,8 @@ export class ClientStateManager { private unsupportedFutureEnvelope = false private frozen = false private rendererAccessTokens = new Map() + private attachmentEpoch = randomUUID() + private attachmentPublicationUnknown = false constructor( userDataPath: string, @@ -243,6 +246,33 @@ export class ClientStateManager { return [...this.state.windowOrder] } + /** Private parent transport only; the existing publication queue owns this projection. */ + retainedAttachments() { + const receipt = this.attachmentEpoch + const current = () => { + if (receipt !== this.attachmentEpoch || this.frozen || this.unsupportedFutureEnvelope || this.attachmentPublicationUnknown) throw new Error("attachment_inventory_changed") + this.assertReplacementAllowed() + } + const operation = this.writeQueue.catch(() => {}).then(async () => { + const windows: Array<{ windowId: string; tabs: Awaited> }> = [] + try { + current() + for (const windowId of this.state.windowOrder) { + const tabs = await retainedProjectMetadata(this.windowRecord(windowId), key => this.partitions.load(key, current)) + current() + windows.push({ windowId, tabs }) + } + return { receipt, status: windows.every(window => window.tabs !== undefined) ? "complete" as const : "unknown" as const, windows } + } catch { return { receipt, status: "unknown" as const, windows: [] } } + }) + this.writeQueue = operation.then(() => {}) + return operation + } + + attachmentReceiptCurrent(receipt: string): boolean { + try { this.assertReplacementAllowed(); return !this.frozen && !this.unsupportedFutureEnvelope && !this.attachmentPublicationUnknown && receipt === this.attachmentEpoch } catch { return false } + } + get preferences(): PreferencesRequest | undefined { return this.isPrimary && !this.unsupportedFutureEnvelope ? this.state.preferences : undefined } @@ -341,6 +371,7 @@ export class ClientStateManager { } resetRendererAccessToken(windowId = this.activeWindowId): void { + this.attachmentEpoch = randomUUID() this.windowRecord(windowId) this.rendererAccessTokens.delete(windowId) } @@ -480,6 +511,7 @@ export class ClientStateManager { } this.frozen = true + this.attachmentEpoch = randomUUID() // The primary locks stay held until the queued root publication and GC have both drained. const drain = this.writeQueue.then( () => { @@ -633,6 +665,7 @@ export class ClientStateManager { prepare?: () => Promise, committed?: () => Promise, ): Promise { + this.attachmentEpoch = randomUUID() const operation = this.writeQueue.catch(() => {}).then(async () => { if (rendererToken !== undefined) this.assertRendererAccessToken(rendererToken, windowId) if (skipWhenSuppressed && this.persistenceSuppressed.has(windowId)) { @@ -648,11 +681,13 @@ export class ClientStateManager { await this.writeAtomically(JSON.stringify(this.state), rendererToken, windowId) } catch (error) { this.state = previousState + this.attachmentPublicationUnknown = true this.persistenceSuppressed = previousPersistenceSuppressed this.unsupportedFutureEnvelope = previousUnsupportedFutureEnvelope throw error } await committed?.().catch((error) => console.warn("[client-state] failed to sweep partitions", error)) + this.attachmentEpoch = randomUUID() }) this.writeQueue = operation return operation.then(() => true) @@ -663,6 +698,7 @@ export class ClientStateManager { committed?: () => Promise, ): Promise { if (this.frozen) return Promise.reject(new Error("Client state persistence is frozen for shutdown")) + this.attachmentEpoch = randomUUID() const operation = this.writeQueue.catch(() => {}).then(async () => { const previousState = JSON.parse(JSON.stringify(this.state)) as PersistedClientState try { @@ -671,9 +707,11 @@ export class ClientStateManager { await this.writeAtomically(JSON.stringify(this.state)) } catch (error) { this.state = previousState + this.attachmentPublicationUnknown = true throw error } await committed?.().catch((error) => console.warn("[client-state] failed to sweep partitions", error)) + this.attachmentEpoch = randomUUID() return true }) this.writeQueue = operation.then(() => {}) @@ -690,6 +728,7 @@ export class ClientStateManager { this.assertReplacementAllowed(rendererToken, windowId) await rename(temporaryPath, this.statePath) await syncDirectory(dirname(this.statePath)) + this.attachmentPublicationUnknown = false } catch (error) { await rm(temporaryPath, { force: true }).catch(() => {}) throw error diff --git a/packages/electron-app/electron/main/desktop-attachments.test.ts b/packages/electron-app/electron/main/desktop-attachments.test.ts new file mode 100644 index 0000000000..14e7ae3b92 --- /dev/null +++ b/packages/electron-app/electron/main/desktop-attachments.test.ts @@ -0,0 +1,201 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { randomUUID } from "node:crypto" +import { mkdirSync, mkdtempSync, writeFileSync, readFileSync, rmSync } from "node:fs" +import { writeFile } from "node:fs/promises" +import { join } from "node:path" +import { ClientStateManager, type ClientStateWriter } from "./client-state" +import { ClientStatePartitionStore } from "./client-state-partitions" +import { LocalWindowRegistry } from "./local-window-registry" +import { DesktopAttachments } from "./desktop-attachments" +import { retainedProjectMetadata } from "./client-state-attachment-metadata" +import { encodeClientSnapshotV2 } from "../../../ui/src/stores/client-state-partitions" +import vector from "./client-state-attachment-vector.json" +import { NativeParent } from "../../../server/src/native-parent" +import { dispatchNativeRequest, parseNativeRequest } from "./native-request" + +function harness(t: test.TestContext, initial?: unknown, writer?: ClientStateWriter, partitions?: Record) { + const directory = mkdtempSync(join(process.cwd(), ".tmp-attachments-")) + if (initial !== undefined) writeFileSync(join(directory, "client-state.json"), typeof initial === "string" ? initial : JSON.stringify(initial)) + if (partitions) { + mkdirSync(join(directory, "partitions")) + for (const [key, text] of Object.entries(partitions)) writeFileSync(join(directory, "partitions", key), text) + } + const state = new ClientStateManager(directory, writer, { crossHostElectionDirectory: join(directory, "election") }) + const windows = new LocalWindowRegistry(() => {}) + const owner = new DesktopAttachments(state, windows) + t.after(async () => { await state.drainAndReleasePrimary().catch(() => {}); rmSync(directory, { recursive: true, force: true }) }) + const add = (id = state.activeWindowId, persisted = true, connectOnly = false) => windows.add({ id, persisted, connectOnly, + window: { webContents: { id: Math.random(), isDestroyed: () => false }, isDestroyed: () => false } as never, + navigation: {} as never, tracker: null, loading: true, backendUrl: null, pendingFolders: [] }) + return { state, windows, owner, add, directory } +} + +const tab = (serverId = "orphan", folder = "Z:\\Case\\Opaque/ ") => ({ kind: "workspace" as const, serverId, folder, + drafts: { secret: "DRAFT_SENTINEL" } as Record, attachments: {}, scrollSnapshots: {}, unseenIdleSince: {}, generationRecovery: {} }) +const snapshot = (tabs = [tab()]) => ({ version: 1 as const, revision: 1, savedAt: 1, layout: {}, session: { tabs, activeTabIndex: 0 } }) + +test("both hosts' shared fixture comes from the real renderer encoder", async () => { + const source = snapshot([{ ...tab("unknown-A", "Z:\\Case\\Project/ "), drafts: {} }]) + assert.deepEqual(await encodeClientSnapshotV2(source), vector) +}) + +test("real V1/V2/V3 owners retain exact shells; private inventory unions retained and ephemeral live windows with unknown coverage", async t => { + for (const version of [1, 2, 3]) { + const encoded = await encodeClientSnapshotV2(snapshot()) + const h = version === 2 + ? harness(t, { version: 2, restoreEnabled: true, protocolVersion: 1, snapshot: encoded.root, partitionKeys: encoded.partitionKeys }, undefined, encoded.partitions) + : harness(t, version === 1 ? { version: 1, restoreEnabled: true, snapshot: snapshot() } : undefined) + if (version === 3) { + await h.state.commitClientStatePartitions({ protocolVersion: 1, snapshot: encoded.root, partitions: encoded.partitions, partitionKeys: encoded.partitionKeys }) + } + if (version !== 1) { + const loads: string[] = [], original = ClientStatePartitionStore.prototype.load + const spy = t.mock.method(ClientStatePartitionStore.prototype, "load", function(this: ClientStatePartitionStore, key: string, valid: () => void) { loads.push(key); return original.call(this, key, valid) }) + const result = await h.owner.read() + assert.deepEqual(loads, [encoded.root.sessionPartition]) + spy.mock.restore() + assert.equal(result.refs[0]!.serverId, "orphan") + } + h.add() + h.add(randomUUID(), false) + const result = await h.owner.read() + assert.equal(result.status, "unknown") + assert.equal(result.retainedStatus, "complete") + assert.equal(result.owners.length, 2) + assert.equal(result.owners.filter(owner => owner.live && owner.retained).length, 1) + assert.equal(result.refs.length, 1) + assert.equal(result.refs[0]!.directory, tab().folder) + assert.equal(h.owner.current(result.receipt), true) + assert.doesNotMatch(JSON.stringify(result), /DRAFT_SENTINEL|workspacePartition|sessionPartition|rendererAccessToken/) + h.windows.remove(h.state.activeWindowId) + assert.equal(h.owner.current(result.receipt), false) + h.add() + assert.equal(h.owner.current(result.receipt), false) + } +}) + +test("real partition verification, overflow, corrupt/future state and secondary ownership never become empty-complete", async t => { + for (const initial of ["{", { version: 99 }, { version: 3, windows: {}, windowOrder: [] }]) { + const h = harness(t, initial) + assert.equal((await h.owner.read()).retainedStatus, "unknown") + } + const h = harness(t) + const encoded = await encodeClientSnapshotV2(snapshot()) + await h.state.commitClientStatePartitions({ protocolVersion: 1, snapshot: encoded.root, partitions: encoded.partitions, partitionKeys: encoded.partitionKeys }) + writeFileSync(join(h.directory, "partitions", encoded.root.sessionPartition), "corrupt") + assert.equal((await h.owner.read()).retainedStatus, "unknown") + rmSync(join(h.directory, "partitions", encoded.root.sessionPartition)) + assert.equal((await h.owner.read()).retainedStatus, "unknown") + await h.state.saveClientState(snapshot(Array.from({ length: 33 }, () => tab()))) + assert.equal((await h.owner.read()).retainedStatus, "unknown") + await h.state.setRestoreEnabled(false) + const disabled = await h.owner.read() + assert.equal(disabled.status, "unknown") + assert.deepEqual(disabled.refs, []) + const secondary = new ClientStateManager(h.directory, undefined, { crossHostElectionDirectory: join(h.directory, "election") }) + t.after(() => secondary.drainAndReleasePrimary()) + assert.equal((await secondary.retainedAttachments()).status, "unknown") +}) + +test("receipt retirement spans queued publication, rollback, navigation, remove/reuse and shutdown", async t => { + let fail = false, release!: () => void, entered!: () => void + let hold = false + const arrived = new Promise(resolve => { entered = resolve }) + const gate = new Promise(resolve => { release = resolve }) + const h = harness(t, { version: 1, restoreEnabled: true, snapshot: snapshot() }, async (path, text) => { + if (hold) { entered(); await gate } + if (fail) throw new Error("owned write failure") + await writeFile(path, text) + }) + const first = await h.owner.read() + hold = true; fail = true + const pending = h.state.saveClientState(snapshot([tab("A", "/new")])) + const rejected = assert.rejects(pending, /owned write failure/) + await arrived + assert.equal(h.owner.current(first.receipt), false) + let settled = false + const reading = h.owner.read().then(value => { settled = true; return value }) + await new Promise(resolve => setImmediate(resolve)) + assert.equal(settled, false) + release(); await rejected + assert.equal((await reading).retainedStatus, "unknown") + hold = false; fail = false + await h.state.saveClientState(snapshot()) + const stable = await h.owner.read() + assert.equal(stable.refs[0]!.serverId, "orphan") + h.state.resetRendererAccessToken() + assert.equal(h.owner.current(stable.receipt), false) + const again = await h.owner.read() + const id = h.state.activeWindowId + await h.state.removeWindow(id); await h.state.addWindow(id as ReturnType) + assert.equal(h.owner.current(again.receipt), false) + const last = await h.owner.read() + await h.state.drainAndReleasePrimary() + assert.equal(h.owner.current(last.receipt), false) + assert.doesNotMatch(readFileSync(join(h.directory, "client-state.json"), "utf8"), /receipt|ownerId|tabId|DRAFT_SENTINEL/) +}) + +test("metadata projection ignores draft getters and refuses malformed shell identities without following content", async () => { + const shell = tab() + Object.defineProperty(shell, "drafts", { get() { throw new Error("draft read forbidden") } }) + const read = () => { throw new Error("partition read forbidden") } + const result = await retainedProjectMetadata({ restoreEnabled: true, snapshot: snapshot([shell]) }, read) + assert.equal(result![0]!.directory, shell.folder) + for (const malformed of [{ ...tab(), serverId: "../bad" }, { ...tab(), folder: "x\0y" }, { ...tab(), occurrence: 32 }, { kind: "unknown" }]) { + assert.equal(await retainedProjectMetadata({ restoreEnabled: true, snapshot: { version: 1, session: { tabs: [malformed], activeTabIndex: 0 } } }, read), undefined) + } +}) + +test("real private parent and child dispatch carry only metadata and fence a retired backend", async t => { + const h = harness(t, { version: 1, restoreEnabled: true, snapshot: snapshot() }) + let current = true + let dispatched: Promise | undefined + const parent = new NativeParent({ write(line) { + const request = parseNativeRequest(String(line))! + const child = { stdin: { writable: true, write(response: string) { parent.handleLine(response); return true } } } + dispatched = dispatchNativeRequest(child as never, request, (method, params) => h.owner.handle(method, params), () => current) + return true + } }, true) + t.after(() => parent.close()) + const result = await parent.request<{ receipt: string; status: string; refs: unknown[] }>("projects.attachments.read", {}) + await dispatched + assert.equal(result.status, "unknown") + assert.equal(result.refs.length, 1) + assert.equal(await parent.request("projects.attachments.current", { receipt: result.receipt }), true) + await dispatched + await assert.rejects(parent.request("projects.attachments.generic", { path: "forbidden" }), /attachment_inventory_unavailable/) + await dispatched + current = false + const stale = parent.request("projects.attachments.read", {}) + const rejected = assert.rejects(stale, /shutting down/) + await dispatched + parent.close() + await rejected +}) + +test("native receipts belong to the actual backend child object, including zero-project replacement", async t => { + const h = harness(t, { version: 1, restoreEnabled: true, snapshot: { version: 1, session: null } }) + const firstBackend = {}, secondBackend = {} + const first = await h.owner.handle("projects.attachments.read", {}, firstBackend) as { receipt: string; status: string } + assert.equal(await h.owner.handle("projects.attachments.current", { receipt: first.receipt }, firstBackend), true) + assert.equal(await h.owner.handle("projects.attachments.current", { receipt: first.receipt }, secondBackend), false) + const fresh = await h.owner.handle("projects.attachments.read", {}, secondBackend) as { receipt: string; status: string } + assert.equal(fresh.status, "unknown") + assert.equal(await h.owner.handle("projects.attachments.current", { receipt: fresh.receipt }, secondBackend), true) + assert.notEqual(first.receipt, fresh.receipt) +}) + +test("hidden launch windows retire attachment receipts without taking the user window's MRU", async t => { + const h = harness(t) + h.add() + const previous = await h.owner.read() + const hidden = randomUUID() + h.add(hidden, false, true) + assert.equal(h.owner.current(previous.receipt), false) + assert.equal(h.windows.mruRecord()?.id, h.state.activeWindowId) + const current = await h.owner.read() + assert.equal(current.owners.length, 2) + h.windows.remove(hidden) + assert.equal(h.owner.current(current.receipt), false) +}) diff --git a/packages/electron-app/electron/main/desktop-attachments.ts b/packages/electron-app/electron/main/desktop-attachments.ts new file mode 100644 index 0000000000..b994cfb86b --- /dev/null +++ b/packages/electron-app/electron/main/desktop-attachments.ts @@ -0,0 +1,50 @@ +import { randomUUID } from "node:crypto" +import type { ClientStateManager } from "./client-state" +import type { LocalWindowRegistry } from "./local-window-registry" + +/** Narrow private-parent adapter. Live tab and browser participation coverage remains unknown. */ +export class DesktopAttachments { + private captured?: { receipt: string; state: string; windows: string; + backend?: object; owners: Map; tabs: Map } + private backend?: object + constructor(private readonly state: ClientStateManager, private readonly windows: LocalWindowRegistry) {} + + async handle(method: string, params?: unknown, backend?: object) { + if (backend && backend !== this.backend) { this.backend = backend; this.captured = undefined } + if (method === "projects.attachments.read") return this.read() + if (method === "projects.attachments.current") return this.current((params as { receipt?: unknown } | undefined)?.receipt) + throw new Error("attachment_inventory_unavailable") + } + + async read() { + const backend = this.backend + const windowReceipt = this.windows.attachmentReceipt + const live = this.windows.all() + const retained = await this.state.retainedAttachments() + const receipt = randomUUID() + const ownerHandles = new Map(), tabHandles = new Map() + this.captured = { receipt, state: retained.receipt, windows: windowReceipt, backend, owners: ownerHandles, tabs: tabHandles } + const owners: Array<{ ownerId: string; live: boolean; retained: boolean }> = [] + const refs: Array<{ ownerId: string; tabId: string; source: "retained"; serverId: string; directory: string }> = [] + if (!this.current(receipt)) return { receipt, status: "unknown", retainedStatus: "unknown", owners, refs } + const ids = new Set([...live.map(record => record.id), ...retained.windows.map(record => record.windowId)]) + for (const id of ids) { + const ownerId = randomUUID() + ownerHandles.set(ownerId, id) + const record = retained.windows.find(record => record.windowId === id) + owners.push({ ownerId, live: live.some(record => record.id === id), retained: record !== undefined }) + for (const tab of record?.tabs ?? []) { + const tabId = randomUUID() + tabHandles.set(tabId, { windowId: id, index: tab.index }) + refs.push({ ownerId, tabId, source: "retained", serverId: tab.serverId, directory: tab.directory }) + } + } + return { receipt, status: "unknown", retainedStatus: retained.status, owners, refs } + } + + current(receipt: unknown): boolean { + const captured = this.captured + return typeof receipt === "string" && captured?.receipt === receipt + && captured.backend === this.backend && captured.windows === this.windows.attachmentReceipt && this.state.attachmentReceiptCurrent(captured.state) + } +} diff --git a/packages/electron-app/electron/main/ipc.ts b/packages/electron-app/electron/main/ipc.ts index 0bc569ce6f..3a59122239 100644 --- a/packages/electron-app/electron/main/ipc.ts +++ b/packages/electron-app/electron/main/ipc.ts @@ -7,6 +7,7 @@ import { popupTitlebarMenu, setWorkspaceMenuEnabled, type TitlebarMenu } from ". import { requireHttpUrl } from "./navigation-security" import { validateMainFrame } from "./ipc-security" import type { BrowserController } from "./browser-controller" +import { resolveLocalWorkspaceFolder } from "./workspace-folder" interface LocalSender { id: string @@ -45,23 +46,17 @@ interface DialogOpenResult { paths: string[] } -async function resolveLocalWorkspaceFolder(window: BrowserWindow, cliManager: CliProcessManager, instanceId: string, worktreeSlug: string): Promise { +async function resolveWindowWorkspaceFolder(window: BrowserWindow, cliManager: CliProcessManager, instanceId: string, worktreeSlug: string): Promise { const baseUrl = cliManager.getStatus().url if (!baseUrl) throw new Error("Local CodeNomad server is unavailable") const cookieName = cliManager.getAuthCookieName() const cookie = (await window.webContents.session.cookies.get({ url: baseUrl, name: cookieName }))[0] const headers = cookie ? { Cookie: `${cookie.name}=${cookie.value}` } : undefined - const workspaceResponse = await fetch(`${baseUrl.replace(/\/$/, "")}/api/workspaces/${encodeURIComponent(instanceId)}`, { headers, signal: AbortSignal.timeout(5_000) }) - if (!workspaceResponse.ok) throw new Error("Workspace is not active") - const workspace = await workspaceResponse.json() as { path?: unknown } - if (typeof workspace.path !== "string") throw new Error("Workspace path is unavailable") - if (worktreeSlug === "root") return workspace.path - const response = await fetch(`${baseUrl.replace(/\/$/, "")}/api/workspaces/${encodeURIComponent(instanceId)}/worktrees`, { headers, signal: AbortSignal.timeout(5_000) }) - if (!response.ok) throw new Error("Workspace worktrees are unavailable") - const payload = await response.json() as { worktrees?: Array<{ slug?: unknown; directory?: unknown }> } - const worktree = payload.worktrees?.find((candidate) => candidate.slug === worktreeSlug) - if (!worktree || typeof worktree.directory !== "string") throw new Error("Selected worktree is unavailable") - return worktree.directory + return resolveLocalWorkspaceFolder(instanceId, worktreeSlug, async (path) => { + const response = await fetch(`${baseUrl.replace(/\/$/, "")}${path}`, { headers, signal: AbortSignal.timeout(5_000) }) + if (!response.ok) throw new Error("Workspace is not active") + return response.json() + }) } export function setupCliIPC(cliManager: CliProcessManager, dependencies: CliIPCDependencies) { @@ -194,7 +189,7 @@ export function setupCliIPC(cliManager: CliProcessManager, dependencies: CliIPCD || (editor !== undefined && editor !== "vscode" && editor !== "cursor" && editor !== "zed" && editor !== "vscodium")) { throw new Error("Invalid workspace open request") } - const folder = await resolveLocalWorkspaceFolder(window, cliManager, instanceId, worktreeSlug) + const folder = await resolveWindowWorkspaceFolder(window, cliManager, instanceId, worktreeSlug) await openWorkspaceTarget(target as WorkspaceOpenTarget, folder, payload?.path as string | undefined, editor as WorkspaceEditor | undefined, { openPath: (path) => shell.openPath(path), revealPath: (path) => shell.showItemInFolder(path), }) diff --git a/packages/electron-app/electron/main/local-window-registry.ts b/packages/electron-app/electron/main/local-window-registry.ts index cc82221558..fb98d514d8 100644 --- a/packages/electron-app/electron/main/local-window-registry.ts +++ b/packages/electron-app/electron/main/local-window-registry.ts @@ -1,6 +1,7 @@ import type { BrowserWindow, WebContents } from "electron" import type { ClientStateNavigationController } from "./client-state-navigation" import type { WindowStateTracker } from "./window-state" +import { randomUUID } from "node:crypto" export interface LocalWindowRecord { id: string @@ -39,6 +40,9 @@ export class LocalWindowRegistry { private readonly records = new Map() private readonly webContentsIds = new Map() private mru: string[] = [] + private attachmentEpoch = randomUUID() + + get attachmentReceipt(): string { return this.attachmentEpoch } constructor(private readonly setActiveWindow: (id: string) => void | Promise) {} @@ -48,6 +52,7 @@ export class LocalWindowRegistry { if (!record.connectOnly && this.userWindowCount() >= MAX_LOCAL_WINDOWS) throw new RangeError("Too many local windows") record.id = id this.records.set(id, record) + this.attachmentEpoch = randomUUID() this.webContentsIds.set(record.window.webContents.id, id) if (!record.connectOnly) this.mru = [id, ...this.mru.filter((candidate) => candidate !== id)] } @@ -187,6 +192,7 @@ export class LocalWindowRegistry { const record = this.get(id) if (!record) return undefined this.records.delete(record.id) + this.attachmentEpoch = randomUUID() for (const [webContentsId, windowId] of this.webContentsIds) { if (windowId === record.id) this.webContentsIds.delete(webContentsId) } diff --git a/packages/electron-app/electron/main/main.ts b/packages/electron-app/electron/main/main.ts index faf0d82410..efddcf74a2 100644 --- a/packages/electron-app/electron/main/main.ts +++ b/packages/electron-app/electron/main/main.ts @@ -17,6 +17,7 @@ import { abandonLaunchWindow, acknowledgeLaunchConnection, CONNECT_LAUNCH_TIMEOU import { setupCliIPC } from "./ipc" import { notificationBadgeBitmap, setupNotificationBadgeIPC } from "./notification-badge" import { LocalWindowRegistry, type LocalWindowRecord } from "./local-window-registry" +import { DesktopAttachments } from "./desktop-attachments" import { clearWorkspaceMenuWindow, createApplicationMenu, setWorkspaceMenuEnabled } from "./menu" import { resolveApplicationTarget, resolveFocusedLocalTarget, resolveWindowTarget } from "./menu-target" import { MultiwindowLifecycle } from "./multiwindow-lifecycle" @@ -146,6 +147,7 @@ function runPrimary(firstIntent: LaunchIntent) { ? { crossHostElectionDirectory: storageScope.clientStateElectionDirectory } : undefined) const registry = new LocalWindowRegistry(async (id) => { await clientState.setActiveWindow(id) }) + const attachments = new DesktopAttachments(clientState, registry) let lifecycle: MultiwindowLifecycle const developerMode = new DeveloperMode({ devtoolsDataPath: sessionDataPath, @@ -163,7 +165,9 @@ function runPrimary(firstIntent: LaunchIntent) { if (!record.window.isDestroyed()) record.window.webContents.send("browser-target:open", { sessionID, url, requestID }) } }) - const cli = new CliProcessManager((method, params, deadline) => method.startsWith("browser.") + const cli = new CliProcessManager((method, params, deadline, owner) => method.startsWith("projects.attachments.") + ? attachments.handle(method, params, owner) + : method.startsWith("browser.") ? handleNativeBrowserRequest(browserController, method, params, deadline) : developerMode.handleNativeRequest(method)) const remoteOrigins = new Map>() diff --git a/packages/electron-app/electron/main/native-request.test.ts b/packages/electron-app/electron/main/native-request.test.ts index be4b59f46e..8b76559871 100644 --- a/packages/electron-app/electron/main/native-request.test.ts +++ b/packages/electron-app/electron/main/native-request.test.ts @@ -51,3 +51,14 @@ test("a closing or superseded backend cannot start a native service", async () = await dispatchNativeRequest(child, request, async () => { executed = true }, () => false) assert.equal(executed, false) }) + +test("attachment response preserves its opaque scoped request ID and canonical v1 header", async () => { + const id = "attachments-00000000-0000-4000-8000-000000000000" + const request = parseNativeRequest(`${NATIVE_REQUEST_PREFIX}${JSON.stringify({ + v: 1, id, method: "projects.attachments.current", deadline: Date.now() + 5_000, + })}`)! + let wire = "" + const child = { stdin: { writable: true, write(line: string) { wire = line; return true } } } as unknown as ChildProcess + await dispatchNativeRequest(child, request, async () => true, () => true) + assert.equal(wire, `CODENOMAD_NATIVE_RESPONSE:{"v":1,"id":"${id}","ok":true,"result":true}\n`) +}) diff --git a/packages/electron-app/electron/main/preferences-ipc.test.ts b/packages/electron-app/electron/main/preferences-ipc.test.ts index 13f3f7e36b..1607fafde8 100644 --- a/packages/electron-app/electron/main/preferences-ipc.test.ts +++ b/packages/electron-app/electron/main/preferences-ipc.test.ts @@ -89,3 +89,12 @@ test("Preferences IPC rejects unregistered, subframe, and cross-origin senders", h.frame.url = "https://outside.example/preferences" assert.throws(() => minimize(h.event(h.preferencesContents)), /allowed renderer origin/) }) + +test("Preferences IPC rejects malformed binding before opening or accepting", async () => { + const h = harness() + for (const serverId of [null, "", "a/b", 42]) { + await assert.rejects(h.handlers.get("preferences:open")!(h.event(h.localContents), "providers", { serverId }), /server ID/) + await assert.rejects(h.handlers.get("preferences:acceptRequest")!(h.event(h.preferencesContents), { section: "providers", serverId }), /server ID/) + } + assert.deepEqual(h.calls, []) +}) diff --git a/packages/electron-app/electron/main/preferences-window.test.ts b/packages/electron-app/electron/main/preferences-window.test.ts index 9e446e2570..272c0189ea 100644 --- a/packages/electron-app/electron/main/preferences-window.test.ts +++ b/packages/electron-app/electron/main/preferences-window.test.ts @@ -2,6 +2,7 @@ import assert from "node:assert/strict" import test from "node:test" import type { BrowserWindow } from "electron" import { createPreferencesUrl, PreferencesWindowRegistry, requirePreferencesRequest, requirePreferencesSection } from "./preferences-window" +import { createClientState, parseClientState } from "./client-state-envelope" function fakeWindow() { const windowEvents = new Map() @@ -84,7 +85,42 @@ test("Preferences sections and backend URLs are constrained", () => { assert.deepEqual(requirePreferencesRequest("providers", { instanceId: "workspace-1", workspacePath: "C:\\repo", location: { directory: "/mnt/c/repo" } }), { section: "providers", instanceId: "workspace-1", workspacePath: "C:\\repo", location: { directory: "/mnt/c/repo" }, }) - for (const workspacePath of [42, "x".repeat(32769), "bad\0path"]) { + for (const workspacePath of ["", 42, "x".repeat(32769), "bad\0path"]) { assert.throws(() => requirePreferencesRequest("providers", { workspacePath }), /Invalid Preferences workspace path/) } }) + +test("server-bound Preferences survives normalization, guarded reuse, acceptance and the strict state codec", () => { + const request = requirePreferencesRequest("providers", { serverId: "unknown-A", instanceId: "same", workspacePath: "C:\\App/", location: { directory: "/App//" }, scrollTop: 123 }) + assert.equal(request.serverId, "unknown-A") + const registry = new PreferencesWindowRegistry(), target = fakeWindow() + registry.register(target.window, request) + target.contentEvents.get("did-finish-load")?.() + registry.markReady(target.window) + const next = { ...request, serverId: "B" } + registry.reuse(next) + assert.deepEqual(registry.request(target.window), request) + registry.acceptRequest(target.window, next) + assert.deepEqual(registry.request(target.window), next) + const state = createClientState() + state.preferences = next + state.lastPreferences = request + const parsed = parseClientState(JSON.stringify(state)) + assert.equal(parsed.unsupportedFutureEnvelope, false) + assert.deepEqual(parsed.state.preferences, next) + assert.deepEqual(parsed.state.lastPreferences, request) + for (const serverId of [null, undefined, "", "a/b", "a".repeat(129), 42]) { + assert.throws(() => requirePreferencesRequest("providers", { serverId }), /server ID/) + } + assert.throws(() => requirePreferencesRequest("providers", { serverId: "A", token: "forbidden" }), /context/) + assert.equal(Object.prototype.hasOwnProperty.call(requirePreferencesRequest("general", {}), "serverId"), false) + assert.equal(parseClientState(JSON.stringify({ ...state, preferences: { ...next, serverId: null } })).unsupportedFutureEnvelope, true) + for (const workspacePath of ["", 42, "x".repeat(32769), "bad\0path"]) { + assert.equal(parseClientState(JSON.stringify({ ...state, preferences: { ...next, workspacePath } })).unsupportedFutureEnvelope, true) + } + state.preferences = { section: "general" } + state.lastPreferences = { section: "general" } + const legacy = parseClientState(JSON.stringify(state)).state + assert.deepEqual(legacy.preferences, { section: "general" }) + assert.deepEqual(legacy.lastPreferences, { section: "general" }) +}) diff --git a/packages/electron-app/electron/main/preferences-window.ts b/packages/electron-app/electron/main/preferences-window.ts index 62ae6c5d59..bb2d179a8c 100644 --- a/packages/electron-app/electron/main/preferences-window.ts +++ b/packages/electron-app/electron/main/preferences-window.ts @@ -12,6 +12,7 @@ export interface PreferencesRequest { section: PreferencesSection scrollTop?: number instanceId?: string + serverId?: string workspacePath?: string location?: { directory: string; workspaceID?: string } } @@ -34,10 +35,15 @@ export function requirePreferencesRequest(section: unknown, context: unknown): P if (context === undefined || context === null) return request if (typeof context !== "object") throw new Error("Invalid Preferences context") const candidate = context as Record + if (Array.isArray(context) || Object.keys(candidate).some(key => !["section", "scrollTop", "instanceId", "serverId", "workspacePath", "location"].includes(key))) throw new Error("Invalid Preferences context") + if (Object.prototype.hasOwnProperty.call(candidate, "serverId")) { + if (typeof candidate.serverId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(candidate.serverId)) throw new Error("Invalid Preferences server ID") + request.serverId = candidate.serverId + } const instanceId = optionalString(candidate.instanceId, "instance ID", 512) if (instanceId) request.instanceId = instanceId const workspacePath = optionalString(candidate.workspacePath, "workspace path", 32768) - if (workspacePath?.includes("\0")) throw new Error("Invalid Preferences workspace path") + if (candidate.workspacePath === "" || workspacePath?.includes("\0")) throw new Error("Invalid Preferences workspace path") if (workspacePath) request.workspacePath = workspacePath if (candidate.scrollTop !== undefined) { if (!Number.isSafeInteger(candidate.scrollTop) || (candidate.scrollTop as number) < 0 || (candidate.scrollTop as number) > 10_000_000) throw new Error("Invalid Preferences scroll position") @@ -46,8 +52,9 @@ export function requirePreferencesRequest(section: unknown, context: unknown): P if (candidate.location !== undefined && candidate.location !== null) { if (typeof candidate.location !== "object") throw new Error("Invalid Preferences location") const location = candidate.location as Record + if (Array.isArray(location) || Object.keys(location).some(key => !["directory", "workspaceID"].includes(key))) throw new Error("Invalid Preferences location") const directory = optionalString(location.directory, "directory", 32768) - if (!directory) throw new Error("Invalid Preferences directory") + if (!directory || directory.includes("\0")) throw new Error("Invalid Preferences directory") request.location = { directory, ...(optionalString(location.workspaceID, "workspace ID", 512) ? { workspaceID: location.workspaceID as string } : {}), diff --git a/packages/electron-app/electron/main/process-manager.ts b/packages/electron-app/electron/main/process-manager.ts index 06aeb34580..9f910398c8 100644 --- a/packages/electron-app/electron/main/process-manager.ts +++ b/packages/electron-app/electron/main/process-manager.ts @@ -164,7 +164,7 @@ export class CliProcessManager extends EventEmitter { private shutdownStatus: "complete" | "incomplete" | null = null private lifecycle = new SerializedLifecycle() - constructor(private readonly nativeRequestHandler?: (method: string, params: unknown, deadline: number) => Promise) { + constructor(private readonly nativeRequestHandler?: (method: string, params: unknown, deadline: number, owner: ChildProcess) => Promise) { super() } @@ -485,7 +485,7 @@ export class CliProcessManager extends EventEmitter { request, (method, params, deadline) => method === "opencode.service.start" ? startNativeService(params, deadline) - : this.nativeRequestHandler?.(method, params, deadline) ?? Promise.reject(new Error(`Unsupported native method: ${method}`)), + : this.nativeRequestHandler?.(method, params, deadline, child) ?? Promise.reject(new Error(`Unsupported native method: ${method}`)), () => this.child === child && !this.requestedStop, ) } diff --git a/packages/electron-app/electron/main/workspace-folder.ts b/packages/electron-app/electron/main/workspace-folder.ts new file mode 100644 index 0000000000..2436fddb50 --- /dev/null +++ b/packages/electron-app/electron/main/workspace-folder.ts @@ -0,0 +1,27 @@ +import type { WorkspaceDescriptor } from "../../../server/src/api-types" + +export class WorkspaceLocalOnlyError extends Error { + readonly code = "explicit_capability_unavailable" + readonly capability = "files" + readonly reason = { code: "localOnly" } as const + constructor() { + super(JSON.stringify({ code: "explicit_capability_unavailable", capability: "files", reason: { code: "localOnly" } })) + } +} + +/** Read authority from the local backend, before handing any path to host adapters. */ +export async function resolveLocalWorkspaceFolder( + instanceId: string, + worktreeSlug: string, + getJson: (path: string) => Promise, +): Promise { + const route = `/api/workspaces/${encodeURIComponent(instanceId)}` + const workspace = await getJson(route) as Pick + if (workspace.binding !== undefined && workspace.binding?.serverId !== "local-shared") throw new WorkspaceLocalOnlyError() + if (typeof workspace.path !== "string") throw new Error("Workspace path is unavailable") + if (worktreeSlug === "root") return workspace.path + const payload = await getJson(`${route}/worktrees`) as { worktrees?: Array<{ slug?: unknown; directory?: unknown }> } + const worktree = payload.worktrees?.find(candidate => candidate.slug === worktreeSlug) + if (!worktree || typeof worktree.directory !== "string") throw new Error("Selected worktree is unavailable") + return worktree.directory +} diff --git a/packages/electron-app/electron/main/workspace-open.test.ts b/packages/electron-app/electron/main/workspace-open.test.ts index a59b824d4d..82c829ca16 100644 --- a/packages/electron-app/electron/main/workspace-open.test.ts +++ b/packages/electron-app/electron/main/workspace-open.test.ts @@ -6,6 +6,46 @@ import { join } from "node:path" import test from "node:test" import type { ChildProcess } from "node:child_process" import { defaultOpenMode, editorCandidates, openWorkspaceTarget } from "./workspace-open" +import { resolveLocalWorkspaceFolder, WorkspaceLocalOnlyError } from "./workspace-folder" + +test("explicit binding refuses every native target before worktree reads, filesystem or launch", async () => { + for (const serverId of ["loopback-profile", "remote", "missing-profile"]) { + for (const folder of [process.cwd(), "C:\\workspace\\app", "/workspace/app"]) { + for (const slug of ["root", "branch"]) { + for (const target of ["default", "reveal", "terminal", "editor"] as const) { + const reads: string[] = [] + let opens = 0 + const action = async () => { + const root = await resolveLocalWorkspaceFolder("id/%2F..", slug, async route => { + reads.push(route) + assert.equal(reads.length, 1, "worktree reads must be refused") + return { path: folder, binding: { serverId, directory: folder } } + }) + opens++ + await openWorkspaceTarget(target, root, ".", "vscode", { + openPath: async () => assert.fail("openPath"), revealPath: () => assert.fail("revealPath"), + spawnProcess: () => assert.fail("spawnProcess"), + }) + } + await assert.rejects(action(), (error: unknown) => error instanceof WorkspaceLocalOnlyError + && error.code === "explicit_capability_unavailable" && error.reason.code === "localOnly") + assert.deepEqual(reads, ["/api/workspaces/id%2F%252F.."]) + assert.equal(opens, 0, "filesystem/open adapter must not be entered") + } + } + } + } +}) + +test("native folder authority keeps legacy/local paths and fails missing occurrences closed", async () => { + for (const binding of [undefined, { serverId: "local-shared", directory: "local" }]) { + const read = async (route: string) => route.endsWith("/worktrees") + ? { worktrees: [{ slug: "branch", directory: "local/branch" }] } : { path: "local", binding } + assert.equal(await resolveLocalWorkspaceFolder("id", "root", read), "local") + assert.equal(await resolveLocalWorkspaceFolder("id", "branch", read), "local/branch") + } + await assert.rejects(resolveLocalWorkspaceFolder("stale", "root", async () => { throw new Error("Workspace is not active") }), /not active/) +}) test("selects only the requested editor", () => { assert.deepEqual(editorCandidates("zed", "linux", {}), [{ command: "zed", verifyStart: true }]) diff --git a/packages/server/src/api-types.ts b/packages/server/src/api-types.ts index 7259e3e5e8..c8a3154173 100644 --- a/packages/server/src/api-types.ts +++ b/packages/server/src/api-types.ts @@ -7,6 +7,8 @@ import type { RecentFolder, } from "./config/schema" import type { FormInfo, OpenCodeEvent, PermissionRequest } from "@opencode/client" +import type { ProjectExecutionBinding } from "./opencode/servers/types" +import type { ServerCapabilities } from "./opencode/servers/capabilities" export type { PanelExtensionManifest, PanelExtensionSummary, PanelExtensionContext, PanelExtensionCatalog, PanelExtensionCatalogEntry } from "./panel-extensions/contract" export type { ForgeRepository, ForgeWorkItem, ForgeWorkItemKind, ForgeWorkItemsResult } from "./panel-extensions/contract" export type { GitHistoryCommit, GitHistoryPage, GitCommitFile, GitCommitDetails, GitCommitDiff } from "./git-history-types" @@ -119,8 +121,10 @@ export interface WorkspaceDescriptor { id: string /** Correlates creation events with the client request that initiated them. */ requestId?: string - /** Absolute path on the server host. */ + /** Directory in the bound OpenCode server's namespace. */ path: string + binding?: Readonly + capabilities?: ServerCapabilities name?: string status: WorkspaceStatus /** PID/port are populated when the workspace is running. */ @@ -129,8 +133,8 @@ export interface WorkspaceDescriptor { /** Canonical proxy path the CLI exposes for this instance. */ proxyPath: string /** Identifier of the binary resolved from config. */ - binaryId: string - binaryLabel: string + binaryId?: string + binaryLabel?: string binaryVersion?: string createdAt: string updatedAt: string @@ -142,6 +146,7 @@ export interface WorkspaceDescriptor { export interface WorkspaceCreateRequest { path: string + serverId?: string name?: string requestId?: string } @@ -606,6 +611,16 @@ export type InstanceStreamStatus = "connecting" | "connected" | "error" | "disco export type InstanceStreamEvent = OpenCodeEvent +export interface InstanceEventSource { + serverId: string + /** Monotonic relay attempt; independent of connection and daemon identity. */ + generation: number + /** Native connection captured by the relay; independent of its attempt. */ + connectionGeneration?: number +} + +export type InstanceEventGap = "eof" | "transport" | "overflow" | "deadline" | "ownership" | "revoked" + export type SideCarKind = "port" export type SideCarPrefixMode = "strip" | "preserve" @@ -665,6 +680,7 @@ export interface BinaryUpdateRequest { export const OPENCODE_V2_REQUIRED_ERROR_CODE = "opencode_v2_required" as const export const SESSION_ENVIRONMENT_FAILED_ERROR_CODE = "session_environment_failed" as const +export const EXPLICIT_REQUEST_UNCERTAIN_ERROR_CODE = "explicit_request_uncertain" as const export const PENDING_RECONCILIATION_HEADER = "x-codenomad-pending-reconciliation" as const export const PENDING_REQUEST_SNAPSHOT_TIMEOUT_MS = 30_000 @@ -877,8 +893,8 @@ export type WorkspaceEventPayload = | { type: "storage.configChanged"; owner: SettingsOwner; value: SettingsBucket } | { type: "storage.stateChanged"; owner: SettingsOwner; value: SettingsBucket } | { type: "instance.dataChanged"; instanceId: string; data: InstanceData } - | { type: "instance.event"; instanceId: string; event: InstanceStreamEvent } - | { type: "instance.eventStatus"; instanceId: string; status: InstanceStreamStatus; generation: number; reason?: string } + | { type: "instance.event"; instanceId: string; event: InstanceStreamEvent; source?: InstanceEventSource; liveGeneration?: number } + | { type: "instance.eventStatus"; instanceId: string; status: InstanceStreamStatus; generation: number; reason?: string; source?: InstanceEventSource; gap?: InstanceEventGap; liveGeneration?: number } | { type: "yolo.stateChanged"; instanceId: string; sessionId: string; enabled: boolean } | { type: "yolo.autoAccepted"; instanceId: string; sessionId: string; permissionId: string } | { type: "permission.receiptsChanged"; instanceId: string; sessionId: string; messageId?: string } @@ -970,3 +986,6 @@ export interface ServiceUsageSnapshot { export type LoginStartState = "on" | "off" | "unavailable" export interface LoginStartResponse { state: LoginStartState } export interface LoginStartControl { enabled: boolean } + +export type { OpenCodeServerId, OpenCodeServerProfile, OpenCodeServerSummary, ProjectExecutionBinding } from "./opencode/servers/types" +export type { ServerCapabilities, ServerCapability, ServerCapabilityStatus } from "./opencode/servers/capabilities" diff --git a/packages/server/src/config/schema.ts b/packages/server/src/config/schema.ts index a96558f668..9e07c0813f 100644 --- a/packages/server/src/config/schema.ts +++ b/packages/server/src/config/schema.ts @@ -1,6 +1,43 @@ import { z } from "zod" +import { normalizeExplicitOrigin } from "../opencode/servers/origin" + +export const OpenCodeServerIdSchema = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/) +const ExplicitServerIdSchema = OpenCodeServerIdSchema.refine(id => id !== "local-shared") +// Synchronous metadata validation; network admission also checks every DNS answer. +const ServerOriginSchema = z.string().superRefine((value, ctx) => { + try { + if (value !== normalizeExplicitOrigin(value)) throw new Error() + } catch { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Expected a normalized HTTPS origin or HTTP loopback origin" }) + } +}) +export const OpenCodeServerProfileSchema = z.preprocess(value => { + if (!value || typeof value !== "object" || !("kind" in value) || value.kind !== "explicit") return value + // Development metadata migrates by discarding private references without accessing a vault. + const { credentialMode, credentialRef, ...metadata } = value as Record + if (credentialMode !== undefined && credentialMode !== "keychain" && credentialMode !== "memory") return value + return metadata +}, z.discriminatedUnion("kind", [ + z.object({ kind: z.literal("local-shared"), id: z.literal("local-shared") }).strict(), + z.object({ + kind: z.literal("explicit"), id: ExplicitServerIdSchema, + label: z.string().trim().min(1).max(200), origin: ServerOriginSchema, + }).strict(), +])) +export const OpenCodeServersSchema = z.array(OpenCodeServerProfileSchema).superRefine((profiles, ctx) => { + const ids = new Set() + for (const profile of profiles) { + if (ids.has(profile.id)) ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Duplicate OpenCode server ID" }) + ids.add(profile.id) + } +}) +export const ProjectExecutionBindingSchema = z.object({ + serverId: OpenCodeServerIdSchema.default("local-shared"), + directory: z.string().min(1).refine(value => !value.includes("\0")), +}).strict() const ModelPreferenceSchema = z.object({ + serverId: OpenCodeServerIdSchema.optional(), providerId: z.string(), modelId: z.string(), }) @@ -39,6 +76,7 @@ const PreferencesSchema = z .passthrough() const RecentFolderSchema = z.object({ + serverId: OpenCodeServerIdSchema.optional(), path: z.string(), lastAccessed: z.number().nonnegative(), projectName: z.string().optional(), diff --git a/packages/server/src/events/bus.test.ts b/packages/server/src/events/bus.test.ts index 40ebf1c1f9..9e65c7f08f 100644 --- a/packages/server/src/events/bus.test.ts +++ b/packages/server/src/events/bus.test.ts @@ -5,6 +5,35 @@ import { EventBus } from "./bus" import type { WorkspaceEventPayload } from "../api-types" describe("event bus instance status replay", () => { + it("purges only the terminated occurrence before notifying stop/error subscribers", () => { + const bus = new EventBus() + const publish = (instanceId: string, serverId: string, generation = 1) => bus.publish({ + type: "instance.eventStatus", instanceId, source: { serverId, generation }, generation, status: "connected", + }) + const replay = () => { + const frames: WorkspaceEventPayload[] = [] + const off = bus.onEvent(frame => frames.push(frame)); off() + return frames + } + publish("local", "local-shared") + publish("sibling", "B") + bus.publish({ type: "instance.eventStatus", instanceId: "offline", source: { serverId: "A", generation: 1 }, generation: 1, status: "error", gap: "transport" }) + for (const type of ["workspace.stopped", "workspace.error"] as const) { + publish("closed", "A") + publish("closed", "B") + const check = () => assert.deepEqual(replay().map(frame => "instanceId" in frame && frame.instanceId), ["local", "sibling", "offline"]) + bus.once(type, check) + if (type === "workspace.stopped") bus.publish({ type, workspaceId: "closed", reason: "deleted" }) + else bus.publish({ type, workspace: { id: "closed" } as Extract["workspace"] }) + check() + } + publish("closed", "A", 2) + publish("closed", "A", 1) + const fresh = replay().find(frame => "instanceId" in frame && frame.instanceId === "closed") + assert.equal(fresh?.type === "instance.eventStatus" && fresh.source?.generation, 2) + assert.equal(bus.listenerCount("instance.eventStatus"), 0) + }) + it("replays the latest instance status to a late subscriber", () => { const bus = new EventBus() bus.publish({ type: "instance.eventStatus", instanceId: "workspace-1", status: "connecting", generation: 1 }) diff --git a/packages/server/src/events/bus.ts b/packages/server/src/events/bus.ts index 5076fb6538..a2678c98e3 100644 --- a/packages/server/src/events/bus.ts +++ b/packages/server/src/events/bus.ts @@ -10,13 +10,27 @@ export class EventBus extends EventEmitter { } publish(event: WorkspaceEventPayload): boolean { + if (event.type === "workspace.stopped" || event.type === "workspace.error") { + const instanceId = event.type === "workspace.stopped" ? event.workspaceId : event.workspace.id + // The last lease can dispose its relay before the workspace stop is published. + for (const [key, status] of this.instanceStatuses) { + if (status.instanceId === instanceId) this.instanceStatuses.delete(key) + } + } if (event.type === "instance.eventStatus") { + const key = JSON.stringify([event.source?.serverId ?? "local-shared", event.instanceId]) + const previous = this.instanceStatuses.get(key) + if (previous?.source && event.source && previous.source.generation > event.source.generation) return false + if (previous?.source?.generation === event.source?.generation && previous?.liveGeneration !== undefined && event.liveGeneration !== undefined + && previous.liveGeneration > event.liveGeneration) return false + if (previous?.source?.generation === event.source?.generation && previous?.liveGeneration !== undefined && previous.liveGeneration === event.liveGeneration + && (previous.status !== event.status || previous.source?.connectionGeneration !== event.source?.connectionGeneration)) return false const terminal = event.status === "disconnected" && (event.reason === "workspace stopped" || event.reason === "workspace error") if (terminal) { - this.instanceStatuses.delete(event.instanceId) + this.instanceStatuses.delete(key) } else { - this.instanceStatuses.set(event.instanceId, event) + this.instanceStatuses.set(key, event) } } if (event.type !== "instance.event" && event.type !== "instance.eventStatus") { diff --git a/packages/server/src/events/explicit-observers.test.ts b/packages/server/src/events/explicit-observers.test.ts new file mode 100644 index 0000000000..b3157a55a4 --- /dev/null +++ b/packages/server/src/events/explicit-observers.test.ts @@ -0,0 +1,55 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import type { Logger } from "../logger" +import { WorkspaceCapabilityError } from "../opencode/servers/capabilities" +import { PermissionReceipts } from "../permissions/receipts" +import type { PermissionReceiptStore } from "../permissions/receipt-store" +import { observeProviderQuotaFailures } from "../provider-accounts/quota-observer" +import type { WorkspaceManager } from "../workspaces/manager" +import { nativeEventConnections, type ServiceConnection } from "../workspaces/opencode-service" +import { EventBus } from "./bus" + +test("explicit events/statuses cannot wake receipt or quota readers, or consume local bare-ID deduplication", async () => { + const effects: string[] = [], bus = new EventBus() + const connection = { + endpoint: { url: "https://a.example" }, + client: { config: { get: async () => { effects.push("config"); return [] } } }, + } as unknown as ServiceConnection + const manager = { + get: () => ({ path: "/same" }), + requireWorkspaceCapability(_id: string, capability: "historyEnrichment" | "pendingRecovery") { + throw new WorkspaceCapabilityError(capability, { code: "deferred" }) + }, + getSharedServiceConnection: async () => { effects.push("acquire"); return connection }, + getServiceWslDistro: () => { effects.push("wsl"); return undefined }, + getServicePathStyle: () => { effects.push("path"); return "posix" }, + } as unknown as WorkspaceManager + const receipts = new PermissionReceipts({} as PermissionReceiptStore, manager, bus, { error() {} } as unknown as Logger) + const off = observeProviderQuotaFailures(bus, { + observeSwitch: () => { effects.push("switch") }, + observeStepStart: () => { effects.push("step") }, + switchWatermark: () => { effects.push("watermark"); return 0 }, + markQuotaFailure: async () => { effects.push("quota"); return true }, + }) + receipts.start() + try { + for (const serverId of ["A", "B"]) { + const source = { serverId, generation: 1 } + bus.publish({ type: "instance.eventStatus", instanceId: serverId, status: "connected", generation: 1, source }) + for (const type of ["permission.asked", "session.deleted", "credential.switched", "session.step.started", "session.execution.failed"]) { + const event = { type, id: "same-event", created: 1, data: { + id: "same-request", sessionID: "same-session", integrationID: "same-integration", error: { type: "provider.quota" }, + } } + nativeEventConnections.set(event, connection) + bus.publish({ type: "instance.event", instanceId: serverId, event, source } as never) + } + await assert.rejects(receipts.list(serverId, "same-session", {}), WorkspaceCapabilityError) + } + await new Promise(resolve => setImmediate(resolve)) + assert.deepEqual(effects.slice(), []) + const localEvent = { type: "credential.switched", id: "same-event", data: { integrationID: "same-integration" } } + nativeEventConnections.set(localEvent, connection) + bus.publish({ type: "instance.event", instanceId: "local", event: localEvent } as never) + assert.deepEqual(effects, ["switch"]) + } finally { off(); await receipts.stop() } +}) diff --git a/packages/server/src/events/status-lifecycle.test.ts b/packages/server/src/events/status-lifecycle.test.ts new file mode 100644 index 0000000000..be5d442774 --- /dev/null +++ b/packages/server/src/events/status-lifecycle.test.ts @@ -0,0 +1,121 @@ +import assert from "node:assert/strict" +import { once } from "node:events" +import { createServer, type ServerResponse } from "node:http" +import { test } from "node:test" +import pino from "pino" +import type { WorkspaceEventPayload } from "../api-types" +import { explicitContractFixture } from "../opencode/compatibility/contract-fixture" +import { OpenCodeServerConnections } from "../opencode/servers/connections" +import { OpenCodeServerCredentials } from "../opencode/servers/credentials" +import { OpenCodeServerRegistry } from "../opencode/servers/registry" +import { InstanceEventBridge } from "../workspaces/instance-events" +import { WorkspaceManager } from "../workspaces/manager" +import { EventBus } from "./bus" + +async function until(check: () => boolean) { + const end = Date.now() + 5000 + while (!check()) { + assert.ok(Date.now() < end, "lifecycle condition timed out") + await new Promise(resolve => setTimeout(resolve, 5)) + } +} + +test("actual project lifecycle bounds status replay by live occurrences, including late routing and last detach", async t => { + const streams = new Set() + let lateRead: ServerResponse | undefined + const send = (res: ServerResponse, event: object) => res.write(`data: ${JSON.stringify(event)}\n\n`) + const upstream = createServer((req, res) => { + const url = new URL(req.url!, "http://fixture") + const directory = url.searchParams.get("location[directory]") + if (url.pathname === "/api/event") { + res.writeHead(200, { "content-type": "text/event-stream" }) + streams.add(res) + res.on("close", () => streams.delete(res)) + send(res, { type: "server.connected", id: "same", created: 1, data: {} }) + return + } + res.setHeader("content-type", "application/json") + if (url.pathname === "/api/session/late") { lateRead = res; return } + res.end(JSON.stringify(url.pathname === "/openapi.json" ? explicitContractFixture() + : url.pathname === "/api/location" ? { directory, project: { id: "same", directory, canonical: directory } } + : url.pathname === "/api/fs/list" ? { location: { directory }, data: [] } + : { version: "99.0.0" })) + }) + upstream.listen(0, "127.0.0.1"); await once(upstream, "listening") + const origin = `http://127.0.0.1:${(upstream.address() as { port: number }).port}` + let profiles = [{ kind: "explicit" as const, id: "A", label: "A", origin }] + const registry = new OpenCodeServerRegistry(() => profiles, next => { profiles = next as typeof profiles }) + const credentials = new OpenCodeServerCredentials({ profileKey: "fixture", configIdentity: "memory" }, registry) + await credentials.set("A", JSON.stringify({ username: "fixture", password: "synthetic" })) + const forbidden = (): never => { throw new Error("Host operation forbidden") } + const connections = new OpenCodeServerConnections({ registry, credentials, local: { acquire: forbidden, existing: forbidden, invalidate: forbidden } }) + const bus = new EventBus() + const live: WorkspaceEventPayload[] = [] + const off = bus.onEvent(frame => live.push(frame)) + t.after(off) + const manager = new WorkspaceManager({ rootDir: "D:/unused-fixture", eventBus: bus, logger: pino({ level: "silent" }), + binaryResolver: { resolveDefault: forbidden } as never, + settings: { getOpenCodeServerConnections: () => connections, getOwner: forbidden, readEnvironmentForAdmission: forbidden, + disposeOpenCodeServers: () => connections.dispose() } as never, + sharedService: { endpoint: forbidden, client: forbidden, headers: forbidden, validateLocation: forbidden, subscribe: forbidden, shutdown: async () => {} }, + wslHostDirectoryResolver: forbidden, wslServiceDirectoryResolver: forbidden, + }) + const bridge = new InstanceEventBridge({ workspaceManager: manager, eventBus: bus, logger: pino({ level: "silent" }) }) + t.after(async () => { + bridge.shutdown(); await manager.shutdown() + upstream.closeAllConnections() + await new Promise(resolve => upstream.close(() => resolve())) + }) + const replay = () => { + const frames: WorkspaceEventPayload[] = [] + const off = bus.onEvent(frame => frames.push(frame)); off() + return frames.filter(frame => frame.type === "instance.eventStatus") + } + const listeners = () => ["workspace.started", "workspace.stopped", "workspace.error"].map(type => bus.listenerCount(type)) + const baseline = listeners() + const open = async () => { + const { workspace } = await manager.create("/same", undefined, { serverId: "A" }) + await until(() => replay().some(frame => frame.instanceId === workspace.id && frame.status === "connected")) + return workspace + } + await connections.connect("A") + assert.deepEqual(replay(), [], "Connect without a project has no occurrence status") + const sibling = await open() + for (let cycle = 0; cycle < 20; cycle++) { + const workspace = await open() + if (cycle === 0) { + for (const stream of streams) send(stream, { type: "session.text.delta", id: "late-event", created: 1, data: { sessionID: "late", delta: "fixture" } }) + await until(() => Boolean(lateRead)) + } + await manager.delete(workspace.id) + if (cycle === 0) { + lateRead!.end(JSON.stringify({ data: { id: "late", location: { directory: "/same" } } })) + await until(() => live.some(frame => frame.type === "instance.event" && frame.instanceId === sibling.id && frame.event.type === "session.text.delta")) + const stopped = live.findIndex(frame => frame.type === "workspace.stopped" && frame.workspaceId === workspace.id) + assert.ok(stopped >= 0) + assert.equal(live.slice(stopped + 1).some(frame => frame.type === "instance.eventStatus" && frame.instanceId === workspace.id && frame.reason !== "workspace stopped"), false, + "late routing cannot reinsert a stopped occurrence status") + } + assert.deepEqual(replay().map(frame => frame.instanceId), [sibling.id]) + } + connections.disconnect("A") + assert.deepEqual(replay().map(frame => [frame.instanceId, frame.status, frame.gap]), [[sibling.id, "disconnected", "revoked"]]) + await manager.delete(sibling.id) + assert.deepEqual(replay(), []) + let generation = 0 + for (let cycle = 0; cycle < 20; cycle++) { + await connections.connect("A") + const workspace = await open() + assert.ok(replay()[0].source!.generation > generation) + generation = replay()[0].source!.generation + if (cycle % 2) connections.disconnect("A") + await manager.delete(workspace.id) + await new Promise(resolve => setImmediate(resolve)) + assert.deepEqual(replay(), []) + assert.equal(connections.activeExplicitTargets, 0) + assert.deepEqual(manager.list(), []) + assert.deepEqual(listeners(), baseline, "retired sources release lifecycle callbacks") + } + off() + assert.equal(bus.listenerCount("instance.eventStatus"), 0, "temporary replay subscribers release callbacks") +}) diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts index c937864a52..fa79fe3734 100644 --- a/packages/server/src/index.ts +++ b/packages/server/src/index.ts @@ -734,7 +734,7 @@ async function main() { }) installShutdownSignalHandlers(process, shutdown) - installShutdownStdinHandler(process.stdin, shutdown, (line) => nativeParent.handleLine(line)) + installShutdownStdinHandler(process.stdin, shutdown, (line) => nativeParent.handleLine(line), id => nativeParent.rejectResponse(id)) } if (path.resolve(process.argv[1] ?? "") === __filename) { diff --git a/packages/server/src/missions/compare.test.ts b/packages/server/src/missions/compare.test.ts index 8a7a9c8a9e..3ef32312bf 100644 --- a/packages/server/src/missions/compare.test.ts +++ b/packages/server/src/missions/compare.test.ts @@ -95,13 +95,14 @@ test("unknown creation model leaves judge on the native default, including creat test("Compare refuses missing or identical models before HTTP/recurring admission; variants do not distinguish models", async () => { const app = Fastify() - registerMissionRecurrenceCreate(app, { workspaceManager: {} as never, bridgeToken: "private-fixture", auth: { + const manager = { get: () => ({ id: "fixture" }), requireWorkspaceCapability: () => new AbortController().signal } + registerMissionRecurrenceCreate(app, { workspaceManager: manager as never, bridgeToken: "private-fixture", auth: { isAuthEnabled: () => true, getSessionFromRequest: () => ({ sessionId: "fixture" }) } as never }) try { for (const [value, code] of [[undefined, "compare-models-required"], [{ roles: { "model-a": a } }, "compare-models-required"], [{ roles: { "model-a": a, "model-b": { model: { ...a.model, variant: "high" } } } }, "compare-models-identical"]] as const) { assert.equal(compareModelError(value), code) - await assert.rejects(prepareMissionCreation({ manager: {} as never, workspaceID: "fixture", signal: new AbortController().signal, + await assert.rejects(prepareMissionCreation({ manager: manager as never, workspaceID: "fixture", signal: new AbortController().signal, request: { requestId: "compare", objective: "Compare", template: "compare", profiles: value } }), { status: 400, message: code }) const reply = await app.inject({ method: "POST", url: "/api/workspaces/fixture/missions/recurrence", payload: { requestID: "compare", instructions: "Compare", template: "compare", clock: { time: "09:00", zone: "UTC" }, diff --git a/packages/server/src/missions/journal-read-budget.test.ts b/packages/server/src/missions/journal-read-budget.test.ts index 1c9c55972b..34ba85ded7 100644 --- a/packages/server/src/missions/journal-read-budget.test.ts +++ b/packages/server/src/missions/journal-read-budget.test.ts @@ -119,6 +119,7 @@ test("GET /missions over the plugin observes and loads only open and selected mi const app = Fastify({ logger: false }) const workspace = { id: "workspace-1" } registerMissionRoutes(app, { workspaceManager: { get: () => workspace, getServiceLocation: () => location, + requireWorkspaceCapability: () => new AbortController().signal, getSharedServiceConnection: async () => ({ client, assertCurrent() {} }), ownsLocation: async () => true, getWorktreeIdentityForPath: async (_id: string, directory: string) => directory } as never, worktreeDeletionFence: new WorktreeDeletionFence() }) try { diff --git a/packages/server/src/missions/workspace-capability.ts b/packages/server/src/missions/workspace-capability.ts new file mode 100644 index 0000000000..cc49446cb3 --- /dev/null +++ b/packages/server/src/missions/workspace-capability.ts @@ -0,0 +1,7 @@ +import type { WorkspaceDescriptor } from "../api-types" +import type { WorkspaceManager } from "../workspaces/manager" + +/** Bridge discovery is exclusively within the local service namespace. */ +export function localMissionWorkspaces(manager: Pick): WorkspaceDescriptor[] { + return manager.list().filter(workspace => !workspace.binding || workspace.binding.serverId === "local-shared") +} diff --git a/packages/server/src/native-parent.test.ts b/packages/server/src/native-parent.test.ts index ba5d6e51fb..836eeed514 100644 --- a/packages/server/src/native-parent.test.ts +++ b/packages/server/src/native-parent.test.ts @@ -16,3 +16,94 @@ test("matches native responses to requests and rejects pending work on shutdown" parent.close() await assert.rejects(pending, /shutting down/) }) + +test("monotonic settlement deadline survives wall-clock jumps and delayed timer callbacks", async t => { + let now = 10 + const lines: string[] = [] + const parent = new NativeParent({ write(line) { lines.push(String(line)); return true } }, true) + t.after(() => parent.close()) + t.mock.method(performance, "now", () => now) + const request = parent.request("projects.attachments.current", {}, 5_000) + const rejected = assert.rejects(request, /timed out/) + const envelope = JSON.parse(lines[0]!.slice(NATIVE_REQUEST_PREFIX.length)) + assert.ok(envelope.deadline >= Date.now()) + t.mock.method(Date, "now", () => 0) + now += 5_000 + parent.handleLine(`${NATIVE_RESPONSE_PREFIX}${JSON.stringify({ v: 1, id: envelope.id, ok: true, result: true })}`) + await rejected + assert.equal((parent as any).pending.size, 0) + const fresh = parent.request("projects.attachments.current", {}, 5_000) + const next = JSON.parse(lines[1]!.slice(NATIVE_REQUEST_PREFIX.length)) + parent.handleLine(`${NATIVE_RESPONSE_PREFIX}${JSON.stringify({ v: 1, id: envelope.id, ok: true, result: true })}`) + assert.equal((parent as any).pending.size, 1) + parent.handleLine(`${NATIVE_RESPONSE_PREFIX}${JSON.stringify({ v: 1, id: next.id, ok: true, result: true })}`) + assert.equal(await fresh, true) +}) + +test("direct private responses reject oversize before parsing and ignore expired/replayed IDs", async t => { + const lines: string[] = [] + const parent = new NativeParent({ write(line) { lines.push(String(line)); return true } }, true) + t.after(() => parent.close()) + const read = parent.request("projects.attachments.read", {}, 5_000) + const rejected = assert.rejects(read, /unavailable/) + const { id } = JSON.parse(lines[0]!.slice(NATIVE_REQUEST_PREFIX.length)) + const wire = `${NATIVE_RESPONSE_PREFIX}${JSON.stringify({ v: 1, id, ok: true, result: "x".repeat(9 * 1024 * 1024) })}` + const parse = JSON.parse + let largeParses = 0 + t.mock.method(JSON, "parse", (text: string) => { if (text.length > 8 * 1024 * 1024) largeParses++; return parse(text) }) + parent.handleLine(wire) + await rejected + parent.handleLine(wire); parent.handleLine(wire) + assert.equal(largeParses, 0) + assert.equal((parent as any).pending.size, 0) + const fresh = parent.request("projects.attachments.current", {}) + const next = JSON.parse(lines[1]!.slice(NATIVE_REQUEST_PREFIX.length)) + parent.handleLine(`${NATIVE_RESPONSE_PREFIX}${JSON.stringify({ v: 1, id: next.id, ok: true, result: true })}`) + assert.equal(await fresh, true) +}) + +test("response identity/protocol are checked again after parsing and parsing cannot cross the deadline", async t => { + const lines: string[] = [] + const parent = new NativeParent({ write(line) { lines.push(String(line)); return true } }, true) + t.after(() => parent.close()) + let now = 0 + t.mock.method(performance, "now", () => now) + const request = parent.request("projects.attachments.current", {}, 5_000) + const rejected = assert.rejects(request, /timed out/) + const { id } = JSON.parse(lines[0]!.slice(NATIVE_REQUEST_PREFIX.length)) + for (const extra of ['"id":"forged"', '"v":2']) { + parent.handleLine(`${NATIVE_RESPONSE_PREFIX}{"v":1,"id":"${id}","ok":true,"result":true,${extra}}`) + assert.equal((parent as any).pending.size, 1) + } + const parse = JSON.parse + const spy = t.mock.method(JSON, "parse", (text: string) => { const value = parse(text); now = 5_000; return value }) + parent.handleLine(`${NATIVE_RESPONSE_PREFIX}{"v":1,"id":"${id}","ok":true,"result":true}`) + await rejected + spy.mock.restore() + assert.equal((parent as any).pending.size, 0) + const fresh = parent.request("projects.attachments.current", {}) + const next = JSON.parse(lines[1]!.slice(NATIVE_REQUEST_PREFIX.length)) + parent.handleLine(`${NATIVE_RESPONSE_PREFIX}{"v":1,"id":"${next.id}","ok":true,"result":true}`) + assert.equal(await fresh, true) +}) + +test("32 pending owners, ordinary errors and shutdown retain their existing contracts and release timers", async () => { + const lines: string[] = [] + const parent = new NativeParent({ write(line) { lines.push(String(line)); return true } }, true) + const ordinary = parent.request("opencode.service.start", {}) + const failure = assert.rejects(ordinary, /owned native failure/) + const { id } = JSON.parse(lines[0]!.slice(NATIVE_REQUEST_PREFIX.length)) + parent.handleLine(`${NATIVE_RESPONSE_PREFIX}${JSON.stringify({ v: 1, id, ok: false, error: { code: "native_error", message: "owned native failure" } })}`) + await failure + assert.equal((parent as any).pending.size, 0) + const requests = Array.from({ length: 32 }, () => parent.request("developer.status", {}).catch(error => error)) + await assert.rejects(parent.request("developer.status", {}), /Too many pending/) + assert.equal((parent as any).pending.size, 32) + parent.close() + assert.equal((parent as any).pending.size, 0) + for (const result of await Promise.all(requests)) { + assert.ok(result instanceof Error) + assert.match(result.message, /shutting down/) + } + await assert.rejects(parent.request("developer.status", {}), /shutting down/) +}) diff --git a/packages/server/src/native-parent.ts b/packages/server/src/native-parent.ts index 3f7f6d300b..5dd9bad198 100644 --- a/packages/server/src/native-parent.ts +++ b/packages/server/src/native-parent.ts @@ -1,7 +1,8 @@ import { randomUUID } from "node:crypto" +import { ATTACHMENT_REQUEST_ID_PREFIX, nativeResponseId, nativeResponseLimit, NATIVE_RESPONSE_PREFIX } from "./native-response" +export { NATIVE_RESPONSE_PREFIX } from "./native-response" export const NATIVE_REQUEST_PREFIX = "CODENOMAD_NATIVE_REQUEST:" -export const NATIVE_RESPONSE_PREFIX = "CODENOMAD_NATIVE_RESPONSE:" const DEFAULT_TIMEOUT_MS = 90_000 const MAX_PENDING = 32 @@ -17,6 +18,8 @@ interface PendingRequest { resolve(value: unknown): void reject(error: Error): void timeout: NodeJS.Timeout + expiresAt: number + method: string } export class NativeParent { @@ -33,14 +36,16 @@ export class NativeParent { if (this.closed) return Promise.reject(new Error("Native parent is shutting down")) if (this.pending.size >= MAX_PENDING) return Promise.reject(new Error("Too many pending native requests")) - const id = randomUUID() + const attachment = method === "projects.attachments.read" || method === "projects.attachments.current" + const id = `${attachment ? ATTACHMENT_REQUEST_ID_PREFIX : ""}${randomUUID()}` const deadline = Date.now() + timeoutMs + const expiresAt = performance.now() + timeoutMs return new Promise((resolve, reject) => { const timeout = setTimeout(() => { this.pending.delete(id) reject(new Error(`Native request timed out: ${method}`)) }, timeoutMs) - this.pending.set(id, { resolve: resolve as (value: unknown) => void, reject, timeout }) + this.pending.set(id, { resolve: resolve as (value: unknown) => void, reject, timeout, expiresAt, method }) this.output.write(`${NATIVE_REQUEST_PREFIX}${JSON.stringify({ v: 1, id, method, params, deadline })}\n`) }) } @@ -48,22 +53,41 @@ export class NativeParent { handleLine(line: string): boolean { const trimmed = line.trim() if (!trimmed.startsWith(NATIVE_RESPONSE_PREFIX)) return false + const id = nativeResponseId(trimmed) + if (!id) return true + const pending = this.pending.get(id) + if (!pending) return true + if (performance.now() >= pending.expiresAt) { this.expire(id, pending); return true } + if (Buffer.byteLength(trimmed) > nativeResponseLimit(id)) { this.rejectResponse(id); return true } let response: NativeResponse try { response = JSON.parse(trimmed.slice(NATIVE_RESPONSE_PREFIX.length)) as NativeResponse } catch { return true } - if (response.v !== 1 || typeof response.id !== "string") return true - const pending = this.pending.get(response.id) - if (!pending) return true - this.pending.delete(response.id) + if (!response || response.v !== 1 || response.id !== id || this.pending.get(id) !== pending) return true + if (performance.now() >= pending.expiresAt) { this.expire(id, pending); return true } + this.pending.delete(id) clearTimeout(pending.timeout) if (response.ok) pending.resolve(response.result) else pending.reject(new Error(response.error?.message || response.error?.code || "Native request failed")) return true } + rejectResponse(id: string): void { + const pending = this.pending.get(id) + if (!pending) return + this.pending.delete(id) + clearTimeout(pending.timeout) + pending.reject(new Error("Native response unavailable")) + } + + private expire(id: string, pending: PendingRequest): void { + this.pending.delete(id) + clearTimeout(pending.timeout) + pending.reject(new Error(`Native request timed out: ${pending.method}`)) + } + close(): void { if (this.closed) return this.closed = true diff --git a/packages/server/src/native-response.test.ts b/packages/server/src/native-response.test.ts new file mode 100644 index 0000000000..8ce11cc955 --- /dev/null +++ b/packages/server/src/native-response.test.ts @@ -0,0 +1,144 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { PassThrough } from "node:stream" +import { installShutdownStdinHandler, STDIN_SHUTDOWN_COMMAND } from "./shutdown" +import { NativeParent, NATIVE_REQUEST_PREFIX, NATIVE_RESPONSE_PREFIX } from "./native-parent" +import { MAX_ATTACHMENT_RESPONSE_BYTES, nativeResponseLimit, nativeStdinFramer } from "./native-response" + +function fixture(t: test.TestContext) { + const requests: Array<{ id: string; method: string; deadline: number }> = [] + const parent = new NativeParent({ write(line) { requests.push(JSON.parse(String(line).slice(NATIVE_REQUEST_PREFIX.length))); return true } }, true) + const stdin = new PassThrough() + const lines: number[] = [], shutdowns: string[] = [] + installShutdownStdinHandler(stdin, async trigger => { shutdowns.push(trigger) }, line => { + lines.push(Buffer.byteLength(line)) + return parent.handleLine(line) + }, id => parent.rejectResponse(id)) + t.after(() => { parent.close(); stdin.destroy() }) + const answer = (id: string, result: unknown) => `${NATIVE_RESPONSE_PREFIX}${JSON.stringify({ v: 1, id, ok: true, result })}` + return { parent, stdin, requests, lines, shutdowns, answer } +} + +test("private stdin refuses huge chunks before full retain/decode/parse, drains and handles fresh response plus shutdown", async t => { + const f = fixture(t) + const read = f.parent.request("projects.attachments.read", {}, 5_000) + const rejected = assert.rejects(read, /unavailable/) + const id = f.requests[0]!.id + const wire = Buffer.from(f.answer(id, "x".repeat(9 * 1024 * 1024))) + const parse = JSON.parse, concat = Buffer.concat, toString = Buffer.prototype.toString + const parsed: number[] = [], concats: number[] = [], decoded: number[] = [] + t.mock.method(JSON, "parse", (text: string) => { parsed.push(Buffer.byteLength(text)); return parse(text) }) + t.mock.method(Buffer, "concat", (list: readonly Uint8Array[], length?: number) => { + concats.push(length ?? list.reduce((n, b) => n + b.length, 0)) + return concat(list, length) + }) + t.mock.method(Buffer.prototype, "toString", function (this: Buffer, ...args: Parameters) { + decoded.push(this.length) + return toString.apply(this, args) + }) + f.stdin.write(wire) // no delimiter: overflow releases the matching pending owner now + await rejected + assert.equal((f.parent as any).pending.size, 0) + assert.deepEqual(f.lines, []) + assert.deepEqual(parsed, []) + assert.deepEqual(concats, []) + assert.ok(decoded.every(size => size <= 256)) + const fresh = f.parent.request("projects.attachments.current", {}, 5_000) + f.stdin.write(Buffer.from(`\n${f.answer(f.requests[1]!.id, true)}\r\n${STDIN_SHUTDOWN_COMMAND}\n`)) + assert.equal(await fresh, true) + assert.deepEqual(f.shutdowns, ["stdin"]) + assert.equal((f.parent as any).pending.size, 0) + assert.ok(concats.every(size => size <= nativeResponseLimit(id))) +}) + +test("chunked private wire keeps byte limits, UTF-8 and CRLF; expired and replayed oversized IDs stay unparsed", async t => { + const f = fixture(t) + const read = f.parent.request("projects.attachments.read", {}) + const wire = Buffer.from(f.answer(f.requests[0]!.id, "é🙂\r\nété") + "\r\n") + for (let i = 0; i < wire.length; i++) f.stdin.write(wire.subarray(i, i + 1)) + assert.equal(await read, "é🙂\r\nété") + const expired = f.parent.request("projects.attachments.current", {}, 5) + const id = f.requests[1]!.id + await assert.rejects(expired, /timed out/) + const parse = JSON.parse + let parses = 0 + t.mock.method(JSON, "parse", (text: string) => { parses++; return parse(text) }) + const huge = Buffer.from(f.answer(id, "x".repeat(9 * 1024 * 1024)) + "\n") + for (let replay = 0; replay < 2; replay++) { + f.stdin.write(huge.subarray(0, 180)) + f.stdin.write(huge.subarray(180, MAX_ATTACHMENT_RESPONSE_BYTES)) + f.stdin.write(huge.subarray(MAX_ATTACHMENT_RESPONSE_BYTES)) + } + assert.equal(parses, 0) + assert.equal((f.parent as any).pending.size, 0) + const fresh = f.parent.request("projects.attachments.current", {}) + f.stdin.write(f.answer(f.requests[2]!.id, true) + "\n") + assert.equal(await fresh, true) +}) + +test("exact eight-MiB result plus canonical envelope is accepted; +1 is refused before parse and fresh next line works", async t => { + const f = fixture(t) + const exact = "x".repeat(MAX_ATTACHMENT_RESPONSE_BYTES - 2) // JSON quotes belong to result bytes + const first = f.parent.request("projects.attachments.read", {}) + const wire = f.answer(f.requests[0]!.id, exact) + assert.equal(Buffer.byteLength(wire), nativeResponseLimit(f.requests[0]!.id)) + // CR and LF may arrive separately, including at the exact allowance. + f.stdin.write(Buffer.from(wire + "\r")); f.stdin.write(Buffer.from("\n")) + assert.equal(await first, exact) + const oversized = f.parent.request("projects.attachments.read", {}) + const rejected = assert.rejects(oversized, /unavailable/) + const tooLarge = Buffer.from(f.answer(f.requests[1]!.id, exact + "x") + "\n") + const parse = JSON.parse + let largeParses = 0 + t.mock.method(JSON, "parse", (text: string) => { if (text.length > MAX_ATTACHMENT_RESPONSE_BYTES) largeParses++; return parse(text) }) + f.stdin.write(tooLarge) + await rejected + assert.equal(largeParses, 0) + const fresh = f.parent.request("projects.attachments.current", {}) + f.stdin.write(f.answer(f.requests[2]!.id, true) + "\n") + assert.equal(await fresh, true) +}) + +test("ordinary browser/service/auth/developer method responses retain their existing contract", async t => { + const f = fixture(t) + const large = "x".repeat(9 * 1024 * 1024) + const screenshot = f.parent.request<{ image: { mime: string; data: string }; url: string }>("browser.execute", { sessionID: "owned", command: { action: "screenshot" } }) + assert.doesNotMatch(f.requests[0]!.id, /^attachments-/) + f.stdin.write(f.answer(f.requests[0]!.id, { image: { mime: "image/png", data: large }, url: "https://fixture.invalid/" }) + "\n") + assert.equal((await screenshot).image.data, large) + for (const method of ["opencode.service.start", "developer.status", "browser.execute"]) { + const request = f.parent.request(method, {}) + f.stdin.write(f.answer(f.requests.at(-1)!.id, { stdout: "ok", stderr: "" }) + "\n") + assert.deepEqual(await request, { stdout: "ok", stderr: "" }) + } +}) + +test("multi-block tiny chunks retain bounded slab metadata; string adapters encode in bounded pieces", t => { + const id = "attachments-00000000-0000-4000-8000-000000000000" + const lines: string[] = [], overflows: string[] = [] + const frame = nativeStdinFramer(line => lines.push(line), value => overflows.push(value)) + const exact = `${NATIVE_RESPONSE_PREFIX}${JSON.stringify({ v: 1, id, ok: true, result: "é".repeat(70_000) })}` + const wire = Buffer.from(exact + "\n") + const alloc = Buffer.allocUnsafe + const blocks: number[] = [] + const spy = t.mock.method(Buffer, "allocUnsafe", (size: number) => { blocks.push(size); return alloc(size) }) + const one = Buffer.alloc(1) + for (const byte of wire) { one[0] = byte; frame(one) } + assert.deepEqual(lines, [exact]) + assert.ok(blocks.length <= Math.ceil(wire.length / (64 * 1024)) + 1) + assert.ok(blocks.every(size => size <= 64 * 1024 || size === wire.length - 1)) + spy.mock.restore() + const huge = `${NATIVE_RESPONSE_PREFIX}${JSON.stringify({ v: 1, id, ok: true, result: "x".repeat(9 * 1024 * 1024) })}` + const from = Buffer.from + let maximumString = 0 + t.mock.method(Buffer, "from", (value: any, ...args: any[]) => { + if (typeof value === "string") maximumString = Math.max(maximumString, value.length) + return (from as any)(value, ...args) + }) + frame(huge) + assert.deepEqual(overflows, [id]) + assert.ok(maximumString <= 16 * 1024) + frame("\n🙂".slice(0, 2)) // newline, then a high surrogate held for the next string + frame("🙂\n".slice(1)) + assert.equal(lines.at(-1), "🙂") +}) diff --git a/packages/server/src/native-response.ts b/packages/server/src/native-response.ts new file mode 100644 index 0000000000..5629ece737 --- /dev/null +++ b/packages/server/src/native-response.ts @@ -0,0 +1,119 @@ +export const NATIVE_RESPONSE_PREFIX = "CODENOMAD_NATIVE_RESPONSE:" +export const ATTACHMENT_REQUEST_ID_PREFIX = "attachments-" +export const MAX_ATTACHMENT_RESPONSE_BYTES = 8 * 1024 * 1024 +const HEADER_BYTES = 256 + +// Both native serializers put v/id first. IDs are opaque and echoed unchanged. +export function nativeResponseId(line: string): string | undefined { + const header = line.slice(0, HEADER_BYTES) + if (!header.startsWith(NATIVE_RESPONSE_PREFIX)) return undefined + return /^\{"v":1,"id":"([A-Za-z0-9_-]{1,128})",/.exec(header.slice(NATIVE_RESPONSE_PREFIX.length))?.[1] +} + +export function nativeResponseLimit(id: string): number { + if (!id.startsWith(ATTACHMENT_REQUEST_ID_PREFIX)) return Infinity + // Eight MiB of serialized result plus the exact v1 success envelope and prefix. + return MAX_ATTACHMENT_RESPONSE_BYTES + Buffer.byteLength(`${NATIVE_RESPONSE_PREFIX}${JSON.stringify({ v: 1, id, ok: true, result: null })}`) - 4 +} + +// Classify the small header before copying body bytes, including a single huge chunk. +// A discarded line drains to LF; subsequent lines in the same chunk remain usable. +export function nativeStdinFramer(onLine: (line: string) => void, onOverflow?: (id: string) => void): (chunk: Buffer | string) => void { + const header = Buffer.alloc(HEADER_BYTES) + let headSize = 0, size = 0, limit = Infinity + let classified = false, discarded = false + let id: string | undefined + let pieces: Buffer[] = [] + let tail: Buffer | undefined + let tailSize = 0, lastByte = -1 + const reset = () => { + headSize = size = 0; limit = Infinity + classified = discarded = false; id = undefined; pieces = [] + tail = undefined; tailSize = 0; lastByte = -1 + } + const discard = () => { + discarded = true; pieces = []; tail = undefined + if (id) onOverflow?.(id) + } + const classify = () => { + const text = header.toString("utf8", 0, headSize) + id = nativeResponseId(text) + if (id) { limit = nativeResponseLimit(id); classified = true } + else if (headSize === HEADER_BYTES) { + classified = true + // Only native responses have a body; other stdin commands fit in the header. + discard() + } + } + const consume = (bytes: Buffer) => { + let offset = 0 + while (offset < bytes.length) { + const newline = bytes.indexOf(10, offset) + const end = newline < 0 ? bytes.length : newline + if (!discarded) { + if (!classified) { + const count = Math.min(HEADER_BYTES - headSize, end - offset) + bytes.copy(header, headSize, offset, offset + count) + headSize += count + classify() + } + // One optional CR is framing, outside the result/envelope byte allowance. + if (!discarded) { + const nextSize = size + end - offset + const finalByte = end > offset ? bytes[end - 1] : lastByte + if (nextSize > limit && !(nextSize === limit + 1 && finalByte === 13)) discard() + else { + let position = offset + while (position < end) { + if (!tail || tailSize === tail.length) { + tail = Buffer.allocUnsafe(Math.min(64 * 1024, limit + 1 - size)) + tailSize = 0; pieces.push(tail) + } + const count = Math.min(tail.length - tailSize, end - position) + bytes.copy(tail, tailSize, position, position + count) + tailSize += count; size += count; position += count + } + if (end > offset) lastByte = bytes[end - 1]! + } + } + } + if (newline < 0) break + if (!discarded) { + const trailingCR = lastByte === 13 + if (size - (trailingCR ? 1 : 0) > limit) discard() + else { + const line = Buffer.concat(pieces, size).toString("utf8") + onLine(trailingCR ? line.slice(0, -1) : line) + } + } + reset() + offset = end + 1 + } + } + let highSurrogate = "" + return chunk => { + if (typeof chunk !== "string") { + if (highSurrogate) { consume(Buffer.from(highSurrogate)); highSurrogate = "" } + consume(chunk) + return + } + let offset = 0 + if (highSurrogate && chunk.length) { + const low = chunk.charCodeAt(0) + const paired = low >= 0xdc00 && low <= 0xdfff + consume(Buffer.from(highSurrogate + (paired ? chunk[0] : ""))) + highSurrogate = ""; offset = paired ? 1 : 0 + } + while (offset < chunk.length) { + let end = Math.min(offset + 16 * 1024, chunk.length) + const last = chunk.charCodeAt(end - 1) + if (last >= 0xd800 && last <= 0xdbff) { + if (end === chunk.length) highSurrogate = chunk[end - 1]! + end-- + } + if (end > offset) consume(Buffer.from(chunk.slice(offset, end))) + offset = end + if (highSurrogate) break + } + } +} diff --git a/packages/server/src/opencode/bounded-response-fetch.test.ts b/packages/server/src/opencode/bounded-response-fetch.test.ts new file mode 100644 index 0000000000..a34fef38d0 --- /dev/null +++ b/packages/server/src/opencode/bounded-response-fetch.test.ts @@ -0,0 +1,90 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { getEventListeners } from "node:events" +import { OpenCode } from "@opencode/client" +import { boundedResponseFetch } from "./bounded-response-fetch" +import { boundedMediaFetch } from "./session-media-fetch" +import { readExplicitForm } from "../server/explicit-form-verification" + +function abortAfter(controller: AbortController, depth: number) { + queueMicrotask(() => depth > 1 ? abortAfter(controller, depth - 1) : controller.abort()) +} + +test("every headers/admission microtask window owns and cancels the response exactly once", async () => { + for (const depth of [1, 2, 3, 4, 5, 6]) for (const cleanup of ["held", "rejected"] as const) { + const abort = new AbortController() + let cancelled = 0, calls = 0, requestSignal!: AbortSignal + const body = new ReadableStream({ cancel() { + cancelled++ + return cleanup === "held" ? new Promise(() => {}) : Promise.reject(new Error("synthetic cleanup failure")) + } }) + const fetch = boundedResponseFetch(async (_input, init) => { + calls++; requestSignal = init!.signal!; abortAfter(abort, depth) + return new Response(body) + }, abort.signal, () => {}, 1) + await assert.rejects(fetch("http://owned.invalid")) + await new Promise(resolve => setImmediate(resolve)) + assert.deepEqual({ calls, cancelled, locked: body.locked, listeners: getEventListeners(requestSignal, "abort").length }, + { calls: 1, cancelled: 1, locked: false, listeners: 0 }, `depth=${depth}, cleanup=${cleanup}`) + const current = boundedResponseFetch(async () => new Response("x"), new AbortController().signal, () => {}, 1) + assert.equal(await (await current("http://owned.invalid")).text(), "x") + } +}) + +test("pre-dispatch cancellation and late fetch response preserve ownership without replay", async () => { + const abort = new AbortController() + let calls = 0, cancelled = 0, finish!: (response: Response) => void, requestSignal!: AbortSignal + const body = new ReadableStream({ cancel() { cancelled++; return Promise.reject(new Error("late cleanup")) } }) + const fetch = boundedResponseFetch((_input, init) => { + calls++; requestSignal = init!.signal! + return new Promise(resolve => { finish = resolve }) + }, abort.signal, () => {}, 1) + const pending = fetch("http://owned.invalid"), rejected = assert.rejects(pending) + abort.abort(); await rejected + assert.equal(cancelled, 0) + finish(new Response(body)) + await new Promise(resolve => setImmediate(resolve)) + assert.deepEqual({ calls, cancelled, locked: body.locked, listeners: getEventListeners(requestSignal, "abort").length }, + { calls: 1, cancelled: 1, locked: false, listeners: 0 }) + await assert.rejects(fetch("http://owned.invalid")); assert.equal(calls, 1) +}) + +for (const consumer of ["media", "Form"] as const) { + test(`${consumer} official SDK path owns response through every headers/admission window`, async () => { + for (const depth of [2, 3]) { + const abort = new AbortController() + let cancelled = 0, calls = 0, requestSignal!: AbortSignal + const body = new ReadableStream({ cancel() { cancelled++; return Promise.reject(new Error("synthetic cleanup")) } }) + const fetch: typeof globalThis.fetch = async (_input, init) => { + calls++; requestSignal = init!.signal!; abortAfter(abort, depth) + return new Response(body, { headers: { "content-type": "application/json" } }) + } + if (consumer === "media") { + const client = OpenCode.make({ baseUrl: "http://owned.invalid", fetch: boundedMediaFetch(fetch, abort.signal, () => {}) }) + await assert.rejects(client.session.message.get({ sessionID: "s", messageID: "m" })) + } else { + const connection = { endpoint: { url: "http://owned.invalid" }, fetch, client: OpenCode.make({ baseUrl: "http://owned.invalid", fetch }), + profile: async () => "modern" as const, assertCurrent() {}, invalidate() {} } + await assert.rejects(readExplicitForm({ acquire: async () => connection, current() {}, signal: abort.signal, sessionId: "global", formId: "f", directory: "/owned" })) + } + await new Promise(resolve => setImmediate(resolve)) + assert.deepEqual({ calls, cancelled, locked: body.locked, listeners: getEventListeners(requestSignal, "abort").length }, + { calls: 1, cancelled: 1, locked: false, listeners: 0 }, `depth=${depth}`) + let positiveCalls = 0 + const healthy: typeof globalThis.fetch = async () => { + positiveCalls++ + return Response.json({ data: consumer === "media" ? { id: "m" } : { id: "f", sessionID: "global", title: "Known", fields: [{ key: "answer", type: "string", required: true }], state: { status: "pending" } } }) + } + const signal = new AbortController().signal + if (consumer === "media") { + const client = OpenCode.make({ baseUrl: "http://owned.invalid", fetch: boundedMediaFetch(healthy, signal, () => {}) }) + assert.equal((await client.session.message.get({ sessionID: "s", messageID: "m" })).id, "m") + } else { + const connection = { endpoint: { url: "http://owned.invalid" }, fetch: healthy, client: OpenCode.make({ baseUrl: "http://owned.invalid", fetch: healthy }), + profile: async () => "modern" as const, assertCurrent() {}, invalidate() {} } + assert.equal((await readExplicitForm({ acquire: async () => connection, current() {}, signal, sessionId: "global", formId: "f", directory: "/owned" })).data.state.status, "pending") + } + assert.equal(positiveCalls, 1) + } + }) +} diff --git a/packages/server/src/opencode/bounded-response-fetch.ts b/packages/server/src/opencode/bounded-response-fetch.ts new file mode 100644 index 0000000000..42c3fc8afd --- /dev/null +++ b/packages/server/src/opencode/bounded-response-fetch.ts @@ -0,0 +1,64 @@ +import { waitForAdmission } from "../server/request-admission" + +export class BoundedResponseError extends Error { + readonly code = "response_limit" + constructor() { super("Response too large") } +} + +/** Buffer decoded HTTP bytes before an SDK parser, on an already captured transport. */ +export function boundedResponseFetch(fetch: typeof globalThis.fetch, signal: AbortSignal, current: () => void, limit: number): typeof globalThis.fetch { + return async (input, init) => { + const signals = [signal, ...(init?.signal ? [init.signal] : []), ...(input instanceof Request ? [input.signal] : [])] + const requestSignal = AbortSignal.any(signals) + const check = () => { requestSignal.throwIfAborted(); current() } + check() + let response: Response | undefined + let reader: ReadableStreamDefaultReader | undefined + let cancelled = false + const cancel = () => { + if (!response?.body || cancelled) return + cancelled = true + void (reader ? reader.cancel() : response.body.cancel()).catch(() => {}) + } + try { + const received = await waitForAdmission(fetch(input, { ...init, signal: requestSignal }).then(value => { + // Ownership starts at receipt, before the admission wait can reject. + response = value + if (requestSignal.aborted) cancel() + return value + }), requestSignal) + reader = received.body?.getReader() + requestSignal.addEventListener("abort", cancel, { once: true }) + check() + if (!reader) throw new Error("Response has no body") + const chunks: Uint8Array[] = [] + let size = 0 + while (true) { + const chunk = await waitForAdmission(reader.read(), requestSignal) + check() + if (chunk.done) break + // Count before retaining even one oversized chunk. Content-Length is advisory. + if (chunk.value.byteLength > limit - size) throw new BoundedResponseError() + size += chunk.value.byteLength + chunks.push(chunk.value) + } + check() + const bytes = new Uint8Array(size) + let offset = 0 + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength } + const headers = new Headers(received.headers) + // Native/Undici fetch already decoded the body; retain SDK status and content type. + headers.delete("content-encoding") + headers.delete("content-length") + headers.delete("transfer-encoding") + return new Response(bytes, { status: received.status, statusText: received.statusText, headers }) + } catch (error) { + // Retire this observer independently of the upstream cancellation cleanup. + cancel() + throw error + } finally { + requestSignal.removeEventListener("abort", cancel) + reader?.releaseLock() + } + } +} diff --git a/packages/server/src/opencode/compatibility/contract-fixture.ts b/packages/server/src/opencode/compatibility/contract-fixture.ts index 91c177bde7..a8a3a12241 100644 --- a/packages/server/src/opencode/compatibility/contract-fixture.ts +++ b/packages/server/src/opencode/compatibility/contract-fixture.ts @@ -31,3 +31,49 @@ export const modernContractFixture = { "Session.Message.Compaction.Completed": { properties: { type: {}, metadata: {}, native: {}, summary: {} } }, } }, } + +// Consumed E1 fields from the captured public OpenAPI; enrichment APIs are absent. +export function explicitContractFixture(): any { + const document: any = structuredClone(modernContractFixture) + delete document.paths["/api/session/{sessionID}/environment"] + delete document.paths["/api/location/reload"] + const session = "/api/session/{sessionID}" + for (const [route, methods] of Object.entries({ + "/api/info": ["get"], "/api/location": ["get"], "/api/event": ["get"], + "/api/session": ["get", "post"], [session]: ["get", "delete", "patch"], + [`${session}/message`]: ["get"], [`${session}/message/{messageID}`]: ["get"], + [`${session}/prompt`]: ["post"], [`${session}/shell`]: ["post"], [`${session}/interrupt`]: ["post"], + [`${session}/form/{formID}`]: ["get", "delete"], [`${session}/form/{formID}/reply`]: ["post"], + [`${session}/agent`]: ["post"], [`${session}/model`]: ["post"], + "/api/agent": ["get"], "/api/model": ["get"], "/api/provider": ["get"], "/api/command": ["get"], + })) for (const method of methods) (document.paths[route] ??= {})[method] ??= {} + document.paths[`${session}/interrupt`].post.parameters = [{ name: "resume", in: "query", schema: { type: "string", enum: ["true", "false"] } }] + for (const [route, properties] of [ + ["prompt", { text: {} }], ["shell", { command: {} }], ["form/{formID}/reply", { answer: {} }], + ["agent", { agent: { type: "string" } }], ["model", { model: { $ref: "#/components/schemas/Model.Ref" } }], + ] as const) { + document.paths[`${session}/${route}`].post.requestBody = { content: { "application/json": { schema: { properties } } } } + } + const schemas = document.components.schemas + schemas["Session.Info"] = { properties: { id: {}, location: {} } } + schemas.SessionsResponse = { properties: { data: {}, cursor: {} } } + schemas["Model.Ref"] = { properties: { id: { type: "string" }, providerID: { type: "string" }, variant: { type: "string" } } } + schemas["Location.PublicRef"] = { properties: { directory: { type: "string" } } } + schemas["Skill.Info"] = { properties: { id: { type: "string" }, name: { type: "string" }, description: { type: "string" } } } + schemas["Mcp.Server"] = { properties: { name: { type: "string" }, status: { anyOf: [ + { properties: { status: { type: "string", enum: ["connected"] } } }, + { properties: { status: { type: "string", enum: ["failed"] }, error: { type: "string" } } }, + ] } } } + for (const [route, item] of [["mcp", "Mcp.Server"], ["skill", "Skill.Info"]]) { + document.paths[`/api/${route}`] = { get: { + parameters: [{ name: "location", in: "query", schema: { anyOf: [ + { properties: { directory: { anyOf: [{ type: "string" }, { type: "null" }] } } }, { type: "null" }, + ] } }], + responses: { "200": { content: { "application/json": { schema: { properties: { + location: { $ref: "#/components/schemas/Location.PublicRef" }, + data: { type: "array", items: { $ref: `#/components/schemas/${item}` } }, + } } } } } }, + } } + } + return document +} diff --git a/packages/server/src/opencode/compatibility/negotiate.test.ts b/packages/server/src/opencode/compatibility/negotiate.test.ts index 056c9f0e3e..14b61dcdc3 100644 --- a/packages/server/src/opencode/compatibility/negotiate.test.ts +++ b/packages/server/src/opencode/compatibility/negotiate.test.ts @@ -2,8 +2,9 @@ import assert from "node:assert/strict" import { test } from "node:test" import { createRuntimeFetch } from "./transport" import { rememberRuntime } from "./runtime" -import { legacyContractFixture, modernContractFixture } from "./contract-fixture" +import { explicitContractFixture, legacyContractFixture, modernContractFixture } from "./contract-fixture" import { UnsupportedOpenCodeError } from "../runtime-support" +import { negotiateRuntime } from "./negotiate" test("unknown contracts perform authenticated bounded read negotiation before any mutation", async () => { for (const kind of ["unauthorized", "unrecognized", "oversized"] as const) { @@ -80,3 +81,49 @@ test("shared negotiation has independent subscriber cancellation and never retri assert.equal((await b).status, 204) assert.deepEqual(calls, ["/openapi.json", "/api/session/s"]) }) + +const session = "/api/session/{sessionID}" +const response = (schema: any, route: string) => schema.paths[route].get.responses["200"].content["application/json"].schema.properties +const request = (schema: any, route: string) => schema.paths[route].post.requestBody.content["application/json"].schema.properties +const missingFields: [string, (schema: any) => void][] = [ + ["agent request.agent", schema => { delete request(schema, `${session}/agent`).agent }], + ["agent string", schema => { request(schema, `${session}/agent`).agent.type = "number" }], + ["model request.model", schema => { delete request(schema, `${session}/model`).model }], + ...["id", "providerID", "variant"].map(field => [`model ${field}`, (schema: any) => { delete schema.components.schemas["Model.Ref"].properties[field] }] as [string, (schema: any) => void]), + ["model providerID string", schema => { schema.components.schemas["Model.Ref"].properties.providerID.type = "number" }], + ...["mcp", "skill"].flatMap(route => [ + [`${route} query location`, (schema: any) => { delete schema.paths[`/api/${route}`].get.parameters }], + [`${route} query directory`, (schema: any) => { delete schema.paths[`/api/${route}`].get.parameters[0].schema.anyOf[0].properties.directory }], + [`${route} query directory string`, (schema: any) => { schema.paths[`/api/${route}`].get.parameters[0].schema.anyOf[0].properties.directory = { type: "number" } }], + [`${route} response data`, (schema: any) => { delete response(schema, `/api/${route}`).data }], + [`${route} response array`, (schema: any) => { response(schema, `/api/${route}`).data.type = "object" }], + [`${route} response items`, (schema: any) => { delete response(schema, `/api/${route}`).data.items }], + ] as [string, (schema: any) => void][]), + ["mcp response location", schema => { delete response(schema, "/api/mcp").location }], + ["response location.directory", schema => { delete schema.components.schemas["Location.PublicRef"].properties.directory }], + ["response location.directory string", schema => { schema.components.schemas["Location.PublicRef"].properties.directory.type = "number" }], + ...["id", "name"].map(field => [`skill ${field}`, (schema: any) => { delete schema.components.schemas["Skill.Info"].properties[field] }] as [string, (schema: any) => void]), + ...["name", "status"].map(field => [`mcp ${field}`, (schema: any) => { delete schema.components.schemas["Mcp.Server"].properties[field] }] as [string, (schema: any) => void]), + ["mcp nested status", schema => { delete schema.components.schemas["Mcp.Server"].properties.status.anyOf[0].properties.status }], +] +for (const [route, method] of [[`${session}/agent`, "post"], [`${session}/model`, "post"], ["/api/mcp", "get"], ["/api/skill", "get"]]) { + missingFields.push([`${method} ${route}`, schema => { delete schema.paths[route!][method!] }]) +} +for (const [name, remove] of missingFields) test(`explicit E1 refuses missing consumed contract: ${name}`, async () => { + const schema = explicitContractFixture(); remove(schema) + const calls: string[] = [] + await assert.rejects(negotiateRuntime({ url: "http://127.0.0.1:4321" }, async input => { + calls.push(new URL(String(input)).pathname) + return Response.json(schema) + }, new AbortController().signal, "explicit-e1"), { code: "missing_contract", reason: "canonical_api" }) + assert.deepEqual(calls, ["/openapi.json"]) +}) + +test("explicit E1 admits compatible future schemas without optional enrichment or optional catalogue display fields", async () => { + const schema = explicitContractFixture() + delete schema.components.schemas["Skill.Info"].properties.description + delete response(schema, "/api/skill").location + delete schema.components.schemas["Mcp.Server"].properties.status.anyOf[1].properties.error + assert.equal(await negotiateRuntime({ url: "http://127.0.0.1:4321" }, async () => Response.json(schema), + new AbortController().signal, "explicit-e1"), "modern") +}) diff --git a/packages/server/src/opencode/compatibility/negotiate.ts b/packages/server/src/opencode/compatibility/negotiate.ts index 3f7b9d2bf4..6b3e691bff 100644 --- a/packages/server/src/opencode/compatibility/negotiate.ts +++ b/packages/server/src/opencode/compatibility/negotiate.ts @@ -1,6 +1,11 @@ import { Service, type Endpoint } from "@opencode/client/service" import { runtimeIdentity, type ContractProfile } from "./runtime" -import { UnsupportedOpenCodeError } from "../runtime-support" +import { UnsupportedOpenCodeError, type OpenCodeIncompatibility } from "../runtime-support" + +export class ExplicitContractError extends Error { + readonly code = "missing_contract" + constructor(readonly reason: OpenCodeIncompatibility) { super(`missing_contract: ${reason}`); this.name = "ExplicitContractError" } +} type ObjectValue = Record function object(value: unknown): ObjectValue { @@ -32,11 +37,17 @@ export async function readRuntimeContract(endpoint: Endpoint, fetcher: typeof fe } } catch (error) { await reader.cancel().catch(() => {}); throw error } finally { reader.releaseLock() } - return object(JSON.parse(Buffer.concat(chunks, length).toString("utf8"))) + try { return object(JSON.parse(Buffer.concat(chunks, length).toString("utf8"))) } + catch { throw new ExplicitContractError("canonical_api") } } -export async function negotiateRuntime(endpoint: Endpoint, fetcher: typeof fetch, signal: AbortSignal): Promise> { +export async function negotiateRuntime(endpoint: Endpoint, fetcher: typeof fetch, signal: AbortSignal, + contract: "local" | "explicit-e1" = "local"): Promise> { const document = await readRuntimeContract(endpoint, fetcher, signal) + const refuse = (reason: OpenCodeIncompatibility): never => { + if (contract === "explicit-e1") throw new ExplicitContractError(reason) + throw new UnsupportedOpenCodeError(runtimeIdentity(endpoint)?.version ?? "unknown", reason) + } const paths = object(document.paths) const resolve = (input: unknown) => { const schema = object(input) @@ -57,15 +68,62 @@ export async function negotiateRuntime(endpoint: Endpoint, fetcher: typeof fetch && body(`${session}/permission/{requestID}/reply`, "decision") && "time" in inbox && !("timeCreated" in inbox) // Retired (pre-2.0.4) and unrecognised contracts alike are refused. - if (!modern) throw new UnsupportedOpenCodeError(runtimeIdentity(endpoint)?.version ?? "unknown", "canonical_api") - if (!body(`${session}/environment`, "variables", "put")) { - throw new UnsupportedOpenCodeError(runtimeIdentity(endpoint)?.version ?? "unknown", "session_environment") + if (!modern) refuse("canonical_api") + if (contract === "local" && !body(`${session}/environment`, "variables", "put")) { + refuse("session_environment") } // The pinned client reducer consumes 2.1's replay shape: `native`, never `state`/`recent`. const fields = (name: string) => object(object(document.components?.schemas?.[name]).properties) const text = fields("Session.Message.Assistant.Text"), compaction = fields("Session.Message.Compaction.Completed") if (!("native" in text && !("state" in text) && "metadata" in compaction && !("recent" in compaction))) { - throw new UnsupportedOpenCodeError(runtimeIdentity(endpoint)?.version ?? "unknown", "native_contract") + refuse("native_contract") + } + if (contract === "explicit-e1") { + const properties = (schema: unknown) => object(resolve(schema).properties) + const strings = (schema: unknown, names: string[]) => names.every(name => resolve(properties(schema)[name]).type === "string") + const request = (route: string) => paths[route]?.post?.requestBody?.content?.["application/json"]?.schema + // Selection writes precede prompts; catalogue locations and entries are read + // by metadata and the mention picker. Optional display/enrichment fields stay optional. + const catalog = (route: string, names: string[]) => { + const operation = object(paths[route]?.get) + const parameters = Array.isArray(operation.parameters) ? operation.parameters : [] + const location = resolve(parameters.find((parameter: ObjectValue) => parameter.name === "location" && parameter.in === "query")?.schema) + const selectors = Array.isArray(location.anyOf) ? location.anyOf : [location] + const response = properties(operation.responses?.["200"]?.content?.["application/json"]?.schema) + const data = resolve(response.data) + return selectors.some((schema: unknown) => { + const directory = resolve(properties(schema).directory) + const variants = Array.isArray(directory.anyOf) ? directory.anyOf : [directory] + return variants.some((value: unknown) => resolve(value).type === "string") + }) + && (route !== "/api/mcp" || strings(response.location, ["directory"])) + && data.type === "array" && strings(data.items, names) + } + const mcp = properties(paths["/api/mcp"]?.get?.responses?.["200"]?.content?.["application/json"]?.schema) + const status = resolve(properties(resolve(mcp.data).items).status) + const statuses = Array.isArray(status.anyOf) ? status.anyOf : [status] + const required: [string, string][] = [ + ["/api/info", "get"], ["/api/location", "get"], ["/api/event", "get"], + ["/api/session", "get"], ["/api/session", "post"], [session, "get"], [session, "delete"], + [`${session}/message`, "get"], [`${session}/message/{messageID}`, "get"], + [`${session}/prompt`, "post"], [`${session}/shell`, "post"], [`${session}/interrupt`, "post"], + [`${session}/form/{formID}`, "get"], [`${session}/form/{formID}/reply`, "post"], + ["/api/agent", "get"], ["/api/model", "get"], ["/api/provider", "get"], ["/api/command", "get"], + [`${session}/agent`, "post"], [`${session}/model`, "post"], ["/api/mcp", "get"], ["/api/skill", "get"], + ] + if (required.some(([path, method]) => !has(path, method)) + || !body(`${session}/prompt`, "text") || !body(`${session}/shell`, "command") + || !Array.isArray(paths[`${session}/interrupt`]?.post?.parameters) + || !paths[`${session}/interrupt`].post.parameters.some((parameter: ObjectValue) => parameter.name === "resume" && parameter.in === "query") + || !body(`${session}/form/{formID}/reply`, "answer") + || !strings(request(`${session}/agent`), ["agent"]) + || !strings(properties(request(`${session}/model`)).model, ["id", "providerID", "variant"]) + || !catalog("/api/mcp", ["name"]) || !catalog("/api/skill", ["id", "name"]) + || !statuses.length || !statuses.every((schema: unknown) => strings(schema, ["status"])) + || !("id" in fields("Session.Info") && "location" in fields("Session.Info")) + || !("data" in fields("SessionsResponse") && "cursor" in fields("SessionsResponse"))) { + refuse("canonical_api") + } } const identity = runtimeIdentity(endpoint) if (identity?.contract) { diff --git a/packages/server/src/opencode/compatibility/proxy-locations.ts b/packages/server/src/opencode/compatibility/proxy-locations.ts index 187e60fcaf..b2c91c3ea6 100644 --- a/packages/server/src/opencode/compatibility/proxy-locations.ts +++ b/packages/server/src/opencode/compatibility/proxy-locations.ts @@ -81,6 +81,19 @@ export interface SessionListScope { subpath?: string } +/** Qualified native message-page token; authority remains the owned route session. */ +export function decodeMessageListCursor(cursor: string): { id: string; order: "asc" | "desc"; direction: "previous" | "next" } | null { + if (!cursor || cursor.length > 65_536 || !/^[A-Za-z0-9_-]+$/.test(cursor)) return null + try { + const value: unknown = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8")) + if (!object(value) || Object.keys(value).some(key => !["id", "order", "direction"].includes(key)) + || typeof value.id !== "string" || !value.id + || (value.order !== "asc" && value.order !== "desc") + || (value.direction !== "previous" && value.direction !== "next")) return null + return { id: value.id, order: value.order, direction: value.direction } + } catch { return null } +} + export function decodeSessionListScope(cursor: string): SessionListScope | null { if (!cursor || cursor.length > 65_536 || !/^[A-Za-z0-9_-]+$/.test(cursor)) return null try { diff --git a/packages/server/src/opencode/compatibility/proxy.test.ts b/packages/server/src/opencode/compatibility/proxy.test.ts index 09d72c9185..c75158370c 100644 --- a/packages/server/src/opencode/compatibility/proxy.test.ts +++ b/packages/server/src/opencode/compatibility/proxy.test.ts @@ -65,3 +65,20 @@ test("a transform rewrites only successful JSON responses and releases each requ assert.equal(invalidations, 0) } finally { await app.close(); await upstream.close() } }) + +test("the execution owner can revoke a completed fetch before response publication", async () => { + const app = Fastify() + let releases = 0 + app.get("/fixture", (request, reply) => forwardRuntimeRequest({ + request, reply, url: "http://fixture/api/session/s", body: undefined, headers: {}, + fetch: async () => new Response("stale-private-data"), + assertCurrent: () => { throw new Error("retired") }, + invalidate: () => {}, release: () => { releases++ }, + })) + try { + const response = await app.inject("/fixture") + assert.equal(response.statusCode, 500) + assert(!response.body.includes("stale-private-data")) + assert.equal(releases, 1) + } finally { await app.close() } +}) diff --git a/packages/server/src/opencode/compatibility/proxy.ts b/packages/server/src/opencode/compatibility/proxy.ts index f554eb4015..ba4a456f90 100644 --- a/packages/server/src/opencode/compatibility/proxy.ts +++ b/packages/server/src/opencode/compatibility/proxy.ts @@ -10,6 +10,8 @@ export async function forwardRuntimeRequest(args: { fetch: typeof fetch release?: () => void invalidate: () => void + /** Execution owner fences publication after the fetch's asynchronous completion. */ + assertCurrent?: () => void /** Rewrites a successful JSON response in place before it is relayed whole. */ transform?: (body: unknown) => void }) { @@ -40,6 +42,7 @@ export async function forwardRuntimeRequest(args: { : typeof args.body === "string" ? args.body : Buffer.isBuffer(args.body) ? Uint8Array.from(args.body).buffer : JSON.stringify(args.body) if (body === undefined) headers.delete("content-type") const response = await args.fetch(args.url, { method: args.request.method, headers, body, signal: controller.signal }) + args.assertCurrent?.() unauthorized = response.status === 401 args.reply.code(response.status) // Fetch has decompressed the body. Do not relay its original framing, @@ -57,6 +60,7 @@ export async function forwardRuntimeRequest(args: { return args.reply.code(502).send({ error: "OpenCode response was interrupted" }) } release() + args.assertCurrent?.() let value: unknown try { value = JSON.parse(text) } catch { return args.reply.send(text) } args.transform(value) diff --git a/packages/server/src/opencode/compatibility/transport.test.ts b/packages/server/src/opencode/compatibility/transport.test.ts index f63585da0f..ca2c4fb746 100644 --- a/packages/server/src/opencode/compatibility/transport.test.ts +++ b/packages/server/src/opencode/compatibility/transport.test.ts @@ -87,3 +87,21 @@ test("errors never retry mutations; native error envelopes, abort and origin fen await assert.rejects(fetch(`${endpoint.url}/api/session/s`, { method: "PATCH", signal: controller.signal }), { name: "AbortError" }) await assert.rejects(fetch("http://127.0.0.1:4322/api/session"), /origin mismatch/) }) + +test("preaborted streaming bodies never dispatch; invalid chunks cancel preparation", async () => { + const endpoint = { url: "http://127.0.0.1:4321" } + rememberRuntime(endpoint, { version: "2.2.3", pid: 1, discovery: "info" }) + const fetch = createRuntimeFetch(endpoint, async () => { assert.fail("must not dispatch") }) + const controller = new AbortController() + controller.abort() + await assert.rejects(fetch(new Request(`${endpoint.url}/api/session/s/prompt`, { + method: "POST", signal: controller.signal, body: new ReadableStream(), duplex: "half", + } as RequestInit)), { name: "AbortError" }) + let cancelled = false + await assert.rejects(fetch(new Request(`${endpoint.url}/api/session/s/prompt`, { + method: "POST", body: new ReadableStream({ + start(stream) { stream.enqueue("invalid") }, cancel() { cancelled = true }, + }), duplex: "half", + } as RequestInit)), TypeError) + assert.equal(cancelled, true) +}) diff --git a/packages/server/src/opencode/compatibility/transport.ts b/packages/server/src/opencode/compatibility/transport.ts index dbdd299ef9..39d19b112e 100644 --- a/packages/server/src/opencode/compatibility/transport.ts +++ b/packages/server/src/opencode/compatibility/transport.ts @@ -14,16 +14,18 @@ export function createRuntimeFetch(endpoint: Endpoint, fetcher: typeof fetch = g return createRuntimeTransport(endpoint, fetcher).fetch } -export function createRuntimeTransport(endpoint: Endpoint, fetcher: typeof fetch = globalThis.fetch, lifetime = new AbortController().signal) { +export function createRuntimeTransport(endpoint: Endpoint, fetcher: typeof fetch = globalThis.fetch, lifetime = new AbortController().signal, + contract: "local" | "explicit-e1" = "local") { const identity = runtimeIdentity(endpoint) - let profile = contractProfile(identity) + let profile = contract === "explicit-e1" ? "unknown" as const : contractProfile(identity) let negotiation: Promise<"modern"> | undefined const resolveProfile = async (signal?: AbortSignal) => { signal?.throwIfAborted() lifetime.throwIfAborted() - if (identity) assertSupportedOpenCode(identity.version) + if (identity && contract === "local") assertSupportedOpenCode(identity.version) if (profile !== "unknown") return profile - negotiation ??= negotiateRuntime(endpoint, fetcher, lifetime).then(value => { + negotiation ??= negotiateRuntime(endpoint, fetcher, lifetime, contract).then(value => { + lifetime.throwIfAborted() profile = value return value }).catch(error => { negotiation = undefined; throw error }) @@ -37,19 +39,23 @@ export function createRuntimeTransport(endpoint: Endpoint, fetcher: typeof fetch const headers = new Headers(request.headers) for (const [name, value] of Object.entries(Service.headers(endpoint) ?? {})) headers.set(name, value) // Credentialed native requests must never follow a redirect to another host. - const options: RequestInit = { method: request.method, headers, signal: AbortSignal.any([request.signal, lifetime]), redirect: "error" } + const signal = AbortSignal.any([request.signal, lifetime]) + const options: RequestInit = { method: request.method, headers, signal, redirect: "error" } + const bytes = request.body ? await readBody(request.body, signal) : undefined if (headers.has(LOCATION_CONTEXT_HEADER)) { - const text = request.body ? await request.text() : undefined + const text = bytes ? new TextDecoder().decode(bytes) : undefined let body: unknown = text ? JSON.parse(text) : undefined body = applyLocationContext(url, request.method, body, headers) if (body !== undefined && !object(body)) throw new Error("Invalid OpenCode request body") options.body = body === undefined ? undefined : JSON.stringify(body) headers.delete("content-length") if (options.body === undefined) headers.delete("content-type") - } else if (request.body) { - options.body = await request.arrayBuffer() + } else if (bytes) { + options.body = bytes } + signal.throwIfAborted() const response = await fetcher(url, options) + if (lifetime.aborted) { await response.body?.cancel().catch(() => {}); lifetime.throwIfAborted() } if (!response.ok && !response.headers.get("content-type")?.includes("application/json")) { await response.body?.cancel() return Response.json({ @@ -62,6 +68,30 @@ export function createRuntimeTransport(endpoint: Endpoint, fetcher: typeof fetch return { fetch: adaptedFetch, profile: resolveProfile } } +async function readBody(body: ReadableStream, signal: AbortSignal): Promise { + const reader = body.getReader() + const abort = () => { void reader.cancel(signal.reason).catch(() => {}) } + signal.addEventListener("abort", abort, { once: true }) + const chunks: Uint8Array[] = [] + let length = 0 + try { + signal.throwIfAborted() + while (true) { + const chunk = await reader.read() + signal.throwIfAborted() + if (chunk.done) break + if (!(chunk.value instanceof Uint8Array)) throw new TypeError("OpenCode request body must contain bytes") + chunks.push(chunk.value) + length += chunk.value.byteLength + } + const bytes = new Uint8Array(length) + let offset = 0 + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength } + return bytes.buffer + } catch (error) { abort(); throw error } + finally { signal.removeEventListener("abort", abort); reader.releaseLock() } +} + // A cancelled subscriber must not cancel the connection's negotiation or wait // for another subscriber's request to finish before observing its own abort. function awaitLocal(pending: Promise, signal?: AbortSignal): Promise { diff --git a/packages/server/src/opencode/embedded-asset.ts b/packages/server/src/opencode/embedded-asset.ts new file mode 100644 index 0000000000..c0d8ed36f4 --- /dev/null +++ b/packages/server/src/opencode/embedded-asset.ts @@ -0,0 +1,18 @@ +/** Maximum complete data URI length, independently of transcript deferral. */ +export const ASSET_URI_LIMIT = 8 * 1024 * 1024 + +const passiveImages = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"]) +export const isPassiveImageMime = (mime: string): boolean => passiveImages.has(mime.toLowerCase()) + +/** Validate before decoding; reject noncanonical padding and unused base64 bits. */ +export function isEmbeddedAsset(file: { mime: string; uri: string }): boolean { + if (file.uri.length > ASSET_URI_LIMIT || file.mime.length > 128 || !/^[\w.+-]+\/[\w.+-]+$/.test(file.mime)) return false + const prefix = `data:${file.mime.toLowerCase()};base64,` + if (file.uri.slice(0, prefix.length).toLowerCase() !== prefix) return false + const body = file.uri.slice(prefix.length) + if (!body.length || body.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(body)) return false + const padding = body.endsWith("==") ? 2 : body.endsWith("=") ? 1 : 0 + const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + if (padding && (alphabet.indexOf(body[body.length - padding - 1]) & (padding === 2 ? 15 : 3))) return false + return body.length / 4 * 3 - padding > 0 +} diff --git a/packages/server/src/opencode/form-contract.ts b/packages/server/src/opencode/form-contract.ts new file mode 100644 index 0000000000..50c4deddfc --- /dev/null +++ b/packages/server/src/opencode/form-contract.ts @@ -0,0 +1,40 @@ +import { z } from "zod" + +// The loaded-only RPC and individual native Form reader consume the same fields. +const numeric = z.union([z.number(), z.enum(["Infinity", "-Infinity", "NaN"])]) +const option = z.object({ value: z.string(), label: z.string(), description: z.string().optional() }) +const field = z.object({ + key: z.string(), title: z.string().optional(), description: z.string().optional(), + required: z.boolean().optional(), hidden: z.boolean().optional(), + when: z.array(z.object({ key: z.string(), op: z.enum(["eq", "neq"]), value: z.union([z.string(), numeric, z.boolean()]) })).optional(), +}) +const fieldSchema = z.discriminatedUnion("type", [ + field.extend({ type: z.literal("string"), format: z.enum(["email", "uri", "date", "date-time"]).optional(), + minLength: z.number().optional(), maxLength: z.number().optional(), pattern: z.string().optional(), + placeholder: z.string().optional(), default: z.string().optional(), options: z.array(option).optional(), custom: z.boolean().optional() }), + field.extend({ type: z.literal("number"), minimum: numeric.optional(), maximum: numeric.optional(), default: numeric.optional() }), + field.extend({ type: z.literal("integer"), minimum: numeric.optional(), maximum: numeric.optional(), default: numeric.optional() }), + field.extend({ type: z.literal("boolean"), default: z.boolean().optional() }), + field.extend({ type: z.literal("multiselect"), options: z.array(option), minItems: z.number().optional(), + maxItems: z.number().optional(), custom: z.boolean().optional(), default: z.array(z.string()).optional() }), + field.extend({ type: z.literal("external"), url: z.string() }), +]) +export const formInfoSchema = z.object({ + id: z.string(), sessionID: z.string(), title: z.string(), metadata: z.record(z.unknown()).optional(), + fields: z.array(fieldSchema).min(1), +}) +const answer = z.record(z.union([z.string(), numeric, z.boolean(), z.array(z.string())])) +export const wireFormSchema = formInfoSchema.extend({ state: z.discriminatedUnion("status", [ + z.object({ status: z.literal("pending") }), + z.object({ status: z.literal("answered"), answer }), + z.object({ status: z.literal("cancelled"), message: z.string().optional() }), +]) }).superRefine((form, context) => { + for (const field of form.fields) for (const key of ["minLength", "maxLength", "minItems", "maxItems"] as const) { + const value = key in field ? (field as unknown as Record)[key] : undefined + if (value !== undefined && (typeof value !== "number" || !Number.isInteger(value) || value < 0)) context.addIssue({ code: "custom", message: "Invalid Form count" }) + } +}) + +/** Only this projection crosses the verified reader boundary; answers remain transient. */ +export const verifiedFormSchema = formInfoSchema.extend({ state: z.object({ status: z.enum(["pending", "answered", "cancelled"]) }) }) +export type VerifiedForm = z.infer diff --git a/packages/server/src/opencode/form-verification-policy.ts b/packages/server/src/opencode/form-verification-policy.ts new file mode 100644 index 0000000000..7c74547633 --- /dev/null +++ b/packages/server/src/opencode/form-verification-policy.ts @@ -0,0 +1,2 @@ +export const FORM_VERIFICATION_LIMIT = 4 * 1024 * 1024 +export const FORM_VERIFICATION_TIMEOUT_MS = 10_000 diff --git a/packages/server/src/opencode/image-settings.test.ts b/packages/server/src/opencode/image-settings.test.ts index 8c62697e93..02775fb89e 100644 --- a/packages/server/src/opencode/image-settings.test.ts +++ b/packages/server/src/opencode/image-settings.test.ts @@ -65,6 +65,7 @@ test("global image settings edit JSONC in place and report project overrides", a plugin: { list: async () => ({ data: [] }) } }, } const manager: any = { + requireWorkspaceCapability: () => new AbortController().signal, get: () => ({}), getSharedServiceConnection: async () => connection, getServiceDirectoryForPath: async (_id: string, directory: string) => directory === project ? directory : undefined, ownsLocation: async () => true, getWorktreeIdentityForPath: async () => "owned", @@ -242,6 +243,7 @@ test("a caller's signal cancels the native configuration reads behind image sett plugin: { list: (_input: unknown, options?: { signal?: AbortSignal }) => held(options) } } } const manager: any = { get: () => ({}), getSharedServiceConnection: async () => connection, + requireWorkspaceCapability: () => new AbortController().signal, getServiceDirectoryForPath: async (_id: string, directory: string) => directory, ownsLocation: async () => true, getWorktreeIdentityForPath: async () => "owned", getServicePathStyle: () => process.platform === "win32" ? "win32" : "posix", diff --git a/packages/server/src/opencode/image-settings.ts b/packages/server/src/opencode/image-settings.ts index bc7bcc336e..853c730180 100644 --- a/packages/server/src/opencode/image-settings.ts +++ b/packages/server/src/opencode/image-settings.ts @@ -58,9 +58,14 @@ function decidingProject(winner: Entry | undefined, documents: ConfigDocuments) * when the selected Location's own project block decides it, `media_blob` is also written there. */ export class ImageSettings { constructor(private readonly configuration: Pick, - private readonly manager: Pick) {} + private readonly manager: Pick) {} private async context(workspaceId: string, location: PluginControlLocation, signal?: AbortSignal) { + try { this.manager.requireWorkspaceCapability(workspaceId, "executionSettings") } + catch (error) { + if (error instanceof Error && "statusCode" in error && error.statusCode === 404) throw new PluginControlsError("Workspace not found", "not-found") + throw error + } const connection = await this.manager.getSharedServiceConnection(workspaceId) if (!connection) throw new PluginControlsError("OpenCode is unavailable", "unavailable") // Document acquisition proves directory ownership before any native request. diff --git a/packages/server/src/opencode/integrations/attachments.ts b/packages/server/src/opencode/integrations/attachments.ts index 6328e505ca..ad73f46aee 100644 --- a/packages/server/src/opencode/integrations/attachments.ts +++ b/packages/server/src/opencode/integrations/attachments.ts @@ -22,7 +22,7 @@ export class IntegrationAttachmentError extends Error { export interface IntegrationAttachmentsDeps { controls: Pick - workspaceManager: Pick & Partial> + workspaceManager: Pick & Partial> catalog: Pick now?: () => number timeoutMs?: number @@ -40,6 +40,7 @@ export class IntegrationAttachments { constructor(private readonly deps: IntegrationAttachmentsDeps) {} async installHost(workspaceId: string, integrationId: string, location: PluginControlLocation, signal?: AbortSignal) { + this.requireHostControls(workspaceId) // Refuse before catalog.read(), which can persist a refresh. A mirrored offer never authorizes installation. if (this.deps.workspaceManager.getServiceWslDistro?.(workspaceId)) throw new IntegrationAttachmentError("unsupported") if ((this.deps.hostPlatform ?? process.platform) === "linux") { @@ -123,6 +124,7 @@ export class IntegrationAttachments { private async run(workspaceId: string, integrationId: string, location: PluginControlLocation, outer: AbortSignal | undefined, operation: (context: Context) => Promise, readOnlyCatalog = false): Promise { + this.requireHostControls(workspaceId) if (!/^[a-z][a-z0-9-]{0,31}$/.test(integrationId) || location.workspaceID !== undefined || !location.directory || location.directory.length > 32_768 || /\p{Cc}/u.test(location.directory)) throw new IntegrationAttachmentError("invalid") const timeout = AbortSignal.timeout(this.deps.timeoutMs ?? INTEGRATION_ATTACHMENT_TIMEOUT_MS) @@ -153,6 +155,7 @@ export class IntegrationAttachments { } private async authorize(context: Context) { + this.requireHostControls(context.workspaceId) context.signal.throwIfAborted() context.connection.assertCurrent() if (context.location.workspaceID !== undefined || !await this.deps.workspaceManager.ownsLocation( @@ -162,6 +165,11 @@ export class IntegrationAttachments { context.connection.assertCurrent() } + private requireHostControls(workspaceId: string) { + try { this.deps.workspaceManager.requireWorkspaceCapability(workspaceId, "executionSettings") } + catch { throw new IntegrationAttachmentError("forbidden") } + } + private async session(context: Context, sessionID: string) { await this.authorize(context) context.signal.throwIfAborted() diff --git a/packages/server/src/opencode/integrations/install.ts b/packages/server/src/opencode/integrations/install.ts index 912199379c..870d623494 100644 --- a/packages/server/src/opencode/integrations/install.ts +++ b/packages/server/src/opencode/integrations/install.ts @@ -18,7 +18,7 @@ export class IntegrationInstallError extends Error { export interface IntegrationInstallerDeps { controls: Pick - workspaceManager: Pick + workspaceManager: Pick catalog: Pick sources: Pick } @@ -35,6 +35,7 @@ export class IntegrationInstaller { if (!/^[a-z][a-z0-9-]{0,31}$/.test(integrationId) || (scope !== "global" && scope !== "project") || location.workspaceID !== undefined || !location.directory) throw new IntegrationInstallError("invalid") try { + this.requireHostControls(workspaceId) const connection = await this.deps.workspaceManager.getSharedServiceConnection(workspaceId) if (!connection) throw new IntegrationInstallError("unavailable") // The snapshot read checks Location ownership before any catalog-derived answer. @@ -60,6 +61,7 @@ export class IntegrationInstaller { } private async authorize(workspaceId: string, location: PluginControlLocation, connection: ServiceConnection, signal?: AbortSignal) { + this.requireHostControls(workspaceId) signal?.throwIfAborted() connection.assertCurrent() if (!await this.deps.workspaceManager.ownsLocation(workspaceId, location, connection.client, signal)) { @@ -68,6 +70,11 @@ export class IntegrationInstaller { signal?.throwIfAborted() connection.assertCurrent() } + + private requireHostControls(workspaceId: string) { + try { this.deps.workspaceManager.requireWorkspaceCapability(workspaceId, "executionSettings") } + catch { throw new IntegrationInstallError("forbidden") } + } } function installError(error: unknown): IntegrationInstallError { diff --git a/packages/server/src/opencode/integrations/integrations.ts b/packages/server/src/opencode/integrations/integrations.ts index 24aeca807e..ca192247ed 100644 --- a/packages/server/src/opencode/integrations/integrations.ts +++ b/packages/server/src/opencode/integrations/integrations.ts @@ -11,7 +11,7 @@ import { readIntegrationStatuses, type IntegrationStatusRead } from "./status" export interface IntegrationsReaderDeps { controls: Pick - workspaceManager: Pick + workspaceManager: Pick catalog: Pick timeoutMs?: number } @@ -25,6 +25,12 @@ export class IntegrationsReader { constructor(private readonly deps: IntegrationsReaderDeps) {} async read(workspaceId: string, location: PluginControlLocation, signal?: AbortSignal): Promise { + // prototype-1236: a read of the plugin inventory and the integrations' own status RPC, explicit servers included. + try { this.deps.workspaceManager.requireWorkspaceCapability(workspaceId, "plugins") } + catch (error) { + if (error instanceof Error && "statusCode" in error && error.statusCode === 404) throw new PluginControlsError("Workspace not found", "not-found") + throw error + } const connection = await this.deps.workspaceManager.getSharedServiceConnection(workspaceId) if (!connection) throw new PluginControlsError("OpenCode service is unavailable", "unavailable") const [snapshot, catalog] = await Promise.all([this.deps.controls.read(workspaceId, location, signal), this.deps.catalog.read()]) diff --git a/packages/server/src/opencode/missions/native-human-answer.test.ts b/packages/server/src/opencode/missions/native-human-answer.test.ts index 2412846a96..4d42a8c0ed 100644 --- a/packages/server/src/opencode/missions/native-human-answer.test.ts +++ b/packages/server/src/opencode/missions/native-human-answer.test.ts @@ -113,6 +113,7 @@ async function fixture(asker: "ses_child" | "ses_root" = "ses_child", questions: }, profile: async () => "modern", invalidate: () => {} } const workspace = { id: "workspace", path: directory } const manager = { get: () => workspace, getSharedServiceConnection: async () => connection, + requireWorkspaceCapability: () => new AbortController().signal, ownsLocation: async () => true, getServiceWslDistro: () => undefined, getSharedServiceEndpoint: async () => connection.endpoint, getSharedServiceClient: async () => connection.client, getServiceDirectory: () => directory, getInstanceAuthorizationHeader: () => "Basic fixture", diff --git a/packages/server/src/opencode/missions/native-recurrence-current.test.ts b/packages/server/src/opencode/missions/native-recurrence-current.test.ts index cc744e58ff..5f920f60bc 100644 --- a/packages/server/src/opencode/missions/native-recurrence-current.test.ts +++ b/packages/server/src/opencode/missions/native-recurrence-current.test.ts @@ -166,6 +166,7 @@ for (const revisions of [72, 144]) test(`current display stays byte bounded for permission: { request: { list: async () => ({ location: owned, data: [] }) } } } app = Fastify({ logger: false }) registerMissionRecurrenceCurrent(app, { workspaceManager: { get: () => workspace, getServiceLocation: () => owned, + requireWorkspaceCapability: () => new AbortController().signal, getSharedServiceConnection: async () => ({ client: api, assertCurrent() {} }), ownsLocation: async () => true, getWorktreeIdentityForPath: async () => f.root }, worktreeDeletionFence: new WorktreeDeletionFence() } as never) const url = "/api/workspaces/workspace/missions/recurrence/schedule/current" diff --git a/packages/server/src/opencode/native-schedule-settings-activation.test.ts b/packages/server/src/opencode/native-schedule-settings-activation.test.ts index 589c299e5f..4b50441eb0 100644 --- a/packages/server/src/opencode/native-schedule-settings-activation.test.ts +++ b/packages/server/src/opencode/native-schedule-settings-activation.test.ts @@ -24,6 +24,7 @@ async function fixture(run: (value: any) => Promise) { const connection: any = { endpoint: { url: "http://127.0.0.1:1234" }, assertCurrent() { if (!current) throw Error("replaced") }, fetch: async () => Response.json(nativeScheduleContractFixture()), client: { config: { get: entries }, plugin: { list: async () => ({ data: [] }) } } } const manager: any = { get: () => ({}), getSharedServiceConnection: async () => connection, + requireWorkspaceCapability: () => new AbortController().signal, getServiceDirectoryForPath: async (_id: string, directory: string) => directory === project ? directory : undefined, ownsLocation: async () => true, getWorktreeIdentityForPath: async () => "owned", getServicePathStyle: () => process.platform === "win32" ? "win32" : "posix", diff --git a/packages/server/src/opencode/plugin-control-document-wsl.test.ts b/packages/server/src/opencode/plugin-control-document-wsl.test.ts index 1ff10bfce7..8062a6b6d6 100644 --- a/packages/server/src/opencode/plugin-control-document-wsl.test.ts +++ b/packages/server/src/opencode/plugin-control-document-wsl.test.ts @@ -213,6 +213,7 @@ describe("WSL plugin control documents", () => { plugin: { list: async () => ({ data: [] }) }, } } const controls = new PluginControls({ workspaceManager: { + requireWorkspaceCapability: () => new AbortController().signal, get: () => ({}), getSharedServiceConnection: async () => connection, getServiceDirectoryForPath: async (_id: string, directory: string) => directory === project ? project : undefined, ownsLocation: async () => true, getWorktreeIdentityForPath: async () => "fixture", diff --git a/packages/server/src/opencode/plugin-controls.test.ts b/packages/server/src/opencode/plugin-controls.test.ts index 65426e6153..4151f0437b 100644 --- a/packages/server/src/opencode/plugin-controls.test.ts +++ b/packages/server/src/opencode/plugin-controls.test.ts @@ -739,6 +739,7 @@ function fakeManager(options: { return { calls, get: (id: string) => id === "workspace" ? { id } : undefined, + requireWorkspaceCapability: () => new AbortController().signal, getSharedServiceConnection: async () => ({ client, assertCurrent: () => { diff --git a/packages/server/src/opencode/plugin-controls.ts b/packages/server/src/opencode/plugin-controls.ts index f2070eff6d..5457798d66 100644 --- a/packages/server/src/opencode/plugin-controls.ts +++ b/packages/server/src/opencode/plugin-controls.ts @@ -42,6 +42,7 @@ export type NativeConfigDocuments = { location: PluginControlLocation; entries: type PluginControlsWorkspaceManager = Pick +> & Partial> interface PluginControlsMutationFence { enter(identities: string[]): (() => void) | undefined @@ -104,7 +105,7 @@ export class PluginControls { }) {} async read(workspaceId: string, location: PluginControlLocation, signal?: AbortSignal): Promise { - const context = await this.readContext(workspaceId, location, signal) + const context = await this.readContext(workspaceId, location, signal, false, false) const snapshot = buildSnapshot(context) const documents = configDocuments(context).documents await Promise.all(context.targets.map(async target => { @@ -318,7 +319,13 @@ export class PluginControls { }) } - private async readContext(workspaceId: string, input: PluginControlLocation, signal?: AbortSignal, strictDocuments = false): Promise { + private async readContext(workspaceId: string, input: PluginControlLocation, signal?: AbortSignal, strictDocuments = false, write = true): Promise { + // prototype-1236: the plugin inventory is readable on an explicit server; config document IO stays local-only. + try { this.options.workspaceManager.requireWorkspaceCapability(workspaceId, write ? "executionSettings" : "plugins") } + catch (error) { + if (error instanceof Error && "statusCode" in error && error.statusCode === 404) throw new PluginControlsError("Workspace not found", "not-found") + throw error + } if (!this.options.workspaceManager.get(workspaceId)) { throw new PluginControlsError("Workspace not found", "not-found") } @@ -366,6 +373,12 @@ export class PluginControls { if (!validAbsolutePath(paths, location.directory)) { throw new PluginControlsError("OpenCode location directory is invalid", "invalid") } + // An explicit server has no native config write API: no writable targets, so every switch is read-only. + if (this.options.workspaceManager.isExplicitWorkspace?.(workspaceId)) { + if (write) throw new PluginControlsError("OpenCode configuration scope is unavailable", "unavailable") + assertCurrentConnection(connection) + return { connection, entries, runtime, location, paths, style, globalDirectory, targets: [], fileSystem: hostPluginControlDocumentFileSystem } + } const distro = this.options.workspaceManager.getServiceWslDistro(workspaceId) const fileSystem = distro ? createWslPluginControlDocumentFileSystem(distro) diff --git a/packages/server/src/opencode/plugin-sources.test.ts b/packages/server/src/opencode/plugin-sources.test.ts index 577769b313..b41c880d72 100644 --- a/packages/server/src/opencode/plugin-sources.test.ts +++ b/packages/server/src/opencode/plugin-sources.test.ts @@ -40,6 +40,7 @@ async function fixture(options: { sameScopes?: boolean; catalog?: IntegrationCat }, } const manager: any = { + requireWorkspaceCapability: () => new AbortController().signal, get: (id: string) => id === "w" || id === "w2" ? {} : undefined, getSharedServiceConnection: async () => connection, getServiceDirectoryForPath: async (_id: string, directory: string) => directory === project ? directory : undefined, @@ -144,25 +145,38 @@ describe("plugin source mutations", () => { } finally { await f.cleanup() } }) - it("refuses an add whose OpenCode reads stall, releases the queue, and never writes it later", async () => { - const f = await fixture() - try { - await writeFile(f.globalFile, "{}") - // This fake client ignores the abort signal: the grace period still releases the queue. - const sources = new PluginSources({ documents: f.controls, logger: { info() {} } as any, addTimeoutMs: 500, abortGraceMs: 50 }) - let release!: () => void - f.state.gate = new Promise(resolve => { release = resolve }) - const stalled = sources.add("w", { location: f.location, scope: "global", spec: "stalled-plugin" }) - // Let the queued turn start its daemon reads before later reads stop stalling. - await new Promise(resolve => setTimeout(resolve, 10)) - f.state.gate = undefined - const next = sources.add("w2", { location: f.location, scope: "global", spec: "next-plugin" }) - await assert.rejects(stalled, code("timeout", "unavailable")) - await next - release() - await new Promise(resolve => setTimeout(resolve, 50)) - assert.deepEqual(parse(await readFile(f.globalFile, "utf8")).plugins, ["next-plugin"], "the abandoned add never writes") - } finally { await f.cleanup() } + it("refuses an add whose OpenCode reads stall, releases the queue, and never writes it later", async t => { + t.mock.timers.enable({ apis: ["setTimeout"] }) + const location = { directory: "/fixture" }, writes: string[] = [] + let entered!: () => void, release!: () => void, reads = 0 + const started = new Promise(resolve => { entered = resolve }) + const held = new Promise(resolve => { release = resolve }) + const documents: Pick = { + read: async () => { + // The first native read ignores abort. Its grace must release the same queue. + if (++reads === 1) { entered(); await held } + return { location, runtime: [], configured: { rules: [], sources: [] }, controls: [], targets: [] } + }, + readConfigDocuments: async () => ({ location, entries: [], documents: [] }), + editConfigDocument: async (_id, _location, _scope, edit) => { + const document = { requestedPath: "/fixture/opencode.jsonc", writePath: "/fixture/opencode.jsonc", + exists: true, mode: 0o600, text: "{}", byteOrderMark: false, plugins: [] } + writes.push(...parse(await edit(document, { entries: [], path: document.writePath, location })).plugins) + }, + } + const sources = new PluginSources({ documents, logger: { info() {} } as any, addTimeoutMs: 50, abortGraceMs: 20 }) + const stalled = sources.add("w", { location, scope: "global", spec: "stalled-plugin" }) + const refused = assert.rejects(stalled, code("timeout", "unavailable")) + await started + const next = sources.add("w2", { location, scope: "global", spec: "next-plugin" }) + t.mock.timers.tick(50) + t.mock.timers.tick(20) + await refused + await next + release() + // Drain the abandoned turn's promise chain, without a filesystem/time assumption. + await new Promise(resolve => setImmediate(resolve)) + assert.deepEqual(writes, ["next-plugin"], "the abandoned add never writes") }) it("re-checks an aborted signal under the lock before the document commit", async () => { diff --git a/packages/server/src/opencode/plugin-sources.ts b/packages/server/src/opencode/plugin-sources.ts index b64f3c158e..3385b201b5 100644 --- a/packages/server/src/opencode/plugin-sources.ts +++ b/packages/server/src/opencode/plugin-sources.ts @@ -79,9 +79,10 @@ export class PluginSources { private async addSerialized(workspaceId: string, request: PluginSourceAddRequest, signal: AbortSignal): Promise { const { spec, scope } = request - const [snapshot, raw, catalog] = await Promise.all([ + // prototype-1236: the config documents carry write admission; read them before the (readable) inventory. + const raw = await this.options.documents.readConfigDocuments(workspaceId, request.location, signal) + const [snapshot, catalog] = await Promise.all([ this.options.documents.read(workspaceId, request.location, signal), - this.options.documents.readConfigDocuments(workspaceId, request.location, signal), this.options.catalog?.read().then(view => view.catalog), ]) signal.throwIfAborted() diff --git a/packages/server/src/opencode/servers/attachment-reservations.test.ts b/packages/server/src/opencode/servers/attachment-reservations.test.ts new file mode 100644 index 0000000000..02b9b96b90 --- /dev/null +++ b/packages/server/src/opencode/servers/attachment-reservations.test.ts @@ -0,0 +1,63 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { randomUUID } from "node:crypto" +import { OpenCodeServerConnections } from "./connections" +import { OpenCodeServerRegistry } from "./registry" +import { OpenCodeServerCredentials } from "./credentials" + +function fixture() { + let profiles: any[] = [{ kind: "explicit", id: "A", label: "A", origin: "http://127.0.0.1:1" }] + const registry = new OpenCodeServerRegistry(() => profiles, next => { profiles = next }) + const credentials = new OpenCodeServerCredentials({ profileKey: "test", configIdentity: "test" }, registry) + const forbidden = () => { throw new Error("native IO forbidden") } + const owner = new OpenCodeServerConnections({ registry, credentials, local: { acquire: forbidden, existing: forbidden, invalidate: forbidden } }) + return { owner, registry, credentials } +} + +test("reservation receipts cover pre-publication, publication, disconnect, release and attach/detach ABA without IO", async t => { + const { owner } = fixture(); t.after(() => owner.dispose()) + const empty = owner.attachmentReservations("A") + assert.equal(empty.status, "complete") + assert.deepEqual(empty.reservations, []) + const lease = owner.retainProject({ serverId: "A", directory: "Z:\\Case\\Opaque/ " }) + assert.equal(owner.attachmentReceiptCurrent(empty.receipt), false) + const pending = owner.attachmentReservations("A") + assert.equal(pending.inFlight, true) + assert.equal(pending.reservations[0]!.directory, "Z:\\Case\\Opaque/ ") + const instanceId = randomUUID() + lease.published(instanceId) + assert.equal(owner.attachmentReceiptCurrent(pending.receipt), false) + const published = owner.attachmentReservations("A") + assert.equal(published.reservations[0]!.state, "published") + assert.equal(published.reservations[0]!.instanceId, instanceId) + ;(published.reservations[0] as any).directory = "/forged" + assert.equal(owner.attachmentReservations("A").reservations[0]!.directory, "Z:\\Case\\Opaque/ ") + owner.disconnect("A") + assert.equal(owner.attachmentReceiptCurrent(published.receipt), false) + assert.equal(owner.attachmentReservations("A").reservations.length, 1) + lease.release(); lease.release() + const zero = owner.attachmentReservations("A") + assert.equal(zero.reservations.length, 0) + const second = owner.retainProject({ serverId: "A", directory: "/same" }); second.release() + assert.equal(owner.attachmentReceiptCurrent(zero.receipt), false) + assert.notEqual(owner.attachmentReservations("A").receipt, zero.receipt) +}) + +test("reservation snapshots are bounded and closed/replaced owners cannot validate an old receipt", async t => { + const { owner, registry } = fixture(); t.after(() => owner.dispose()) + const old = owner.attachmentReservations("A") + registry.replace([{ kind: "explicit", id: "A", label: "changed", origin: "http://127.0.0.1:1" }]) + assert.equal(owner.attachmentReceiptCurrent(old.receipt), false) + const leases = Array.from({ length: 513 }, () => owner.retainProject({ serverId: "A", directory: "/same" })) + const bounded = owner.attachmentReservations("A") + assert.equal(bounded.status, "unknown") + assert.equal(bounded.reservations.length, 512) + assert.equal(new Set(bounded.reservations.map(value => value.reservationId)).size, 512) + for (const lease of leases) lease.release() + const fresh = owner.attachmentReservations("A") + assert.equal(fresh.status, "complete") + assert.equal(owner.attachmentReceiptCurrent(fresh.receipt), true) + await owner.dispose() + assert.equal(owner.attachmentReceiptCurrent(fresh.receipt), false) + assert.equal(owner.attachmentReservations("A").status, "unknown") +}) diff --git a/packages/server/src/opencode/servers/attachment-types.ts b/packages/server/src/opencode/servers/attachment-types.ts new file mode 100644 index 0000000000..6ca41e2e3a --- /dev/null +++ b/packages/server/src/opencode/servers/attachment-types.ts @@ -0,0 +1,15 @@ +/** Transient metadata. Directories on explicit servers retain their exact spelling. */ +export interface ServerAttachmentReservation { + reservationId: string + serverId: string + directory: string + instanceId?: string + state: "reserved" | "published" +} + +export interface ServerAttachmentReservations { + receipt: string + status: "complete" | "unknown" + reservations: readonly ServerAttachmentReservation[] + inFlight: boolean +} diff --git a/packages/server/src/opencode/servers/capabilities.ts b/packages/server/src/opencode/servers/capabilities.ts new file mode 100644 index 0000000000..873981b35b --- /dev/null +++ b/packages/server/src/opencode/servers/capabilities.ts @@ -0,0 +1,47 @@ +import type { OpenCodeServerId, OpenCodeServerProfile, ServerConnectionGeneration } from "./types" + +export const SERVER_CAPABILITY_NAMES = [ + "sessions", "chat", "media", "permissions", "questions", "events", "pendingRecovery", + "conversationDiffs", "files", "git", "worktrees", "terminal", "backgroundShells", + "missions", "automation", "sessionPruning", "design", "sessionEnvironment", "serviceManagement", + "historyEnrichment", "integratedImages", "executionSettings", + // prototype-1236: execution settings an explicit server serves natively (auto-accept, published quotas, plugin inventory). + "yolo", "providerUsage", "plugins", +] as const +export type ServerCapability = typeof SERVER_CAPABILITY_NAMES[number] +export type ServerCapabilityReason = "contractUnverified" | "contractVerified" | "liveOnly" | "deferred" | "localOnly" +export interface ServerCapabilityStatus { + state: "available" | "limited" | "unavailable" | "unknown" + reason: { code: ServerCapabilityReason } + evidence: "unverified" | "nativeContract" | "e1Policy" +} +export interface ServerCapabilities { + serverId: OpenCodeServerId + generation: ServerConnectionGeneration + features: Record +} + +export class WorkspaceCapabilityError extends Error { + readonly code = "explicit_capability_unavailable" + constructor(readonly capability: ServerCapability, readonly reason: { code: ServerCapabilityReason }) { + super("explicit_capability_unavailable") + this.name = "WorkspaceCapabilityError" + } +} + +/** Product policy gate. Call with owner-held authority, never a published descriptor. */ +export function requireServerCapability(capability: ServerCapability, status: ServerCapabilityStatus, local = false): void { + if (status.state === "available" || (local && status.state === "unknown")) return + throw new WorkspaceCapabilityError(capability, { code: status.reason.code }) +} + +/** E1 explicit policy template; admission must qualify native contracts before availability. */ +export function initialServerCapabilities(profile: OpenCodeServerProfile, generation: ServerConnectionGeneration): ServerCapabilities { + const native = new Set(["sessions", "chat", "media", "permissions", "questions", "events"]) + const features = Object.fromEntries(SERVER_CAPABILITY_NAMES.map(name => [name, + profile.kind === "local-shared" || native.has(name) ? { state: "unknown", reason: { code: "contractUnverified" }, evidence: "unverified" } + : name === "pendingRecovery" ? { state: "limited", reason: { code: "liveOnly" }, evidence: "e1Policy" } + : { state: "unavailable", reason: { code: name === "sessionEnvironment" || name === "serviceManagement" ? "localOnly" : "deferred" }, evidence: "e1Policy" }, + ])) as Record + return { serverId: profile.id, generation, features } +} diff --git a/packages/server/src/opencode/servers/connections.test.ts b/packages/server/src/opencode/servers/connections.test.ts new file mode 100644 index 0000000000..a637977abf --- /dev/null +++ b/packages/server/src/opencode/servers/connections.test.ts @@ -0,0 +1,383 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { createServer, type ServerResponse } from "node:http" +import { once } from "node:events" +import { mkdtempSync, readFileSync, rmSync } from "node:fs" +import path from "node:path" +import pino from "pino" +import { OpenCodeServerConnections } from "./connections" +import { OpenCodeServerCredentials } from "./credentials" +import { OpenCodeServerRegistry } from "./registry" +import { explicitContractFixture as contract } from "../compatibility/contract-fixture" +import { OpenCodeSharedService } from "../../workspaces/opencode-service" +import { SettingsService } from "../../settings/service" +import { resolveConfigLocation } from "../../config/location" +import { WorkspaceManager } from "../../workspaces/manager" +import { BinaryResolver } from "../../settings/binaries" +import { EventBus } from "../../events/bus" +import type { OpenCodeServerProfile } from "./types" + +function deferred() { + let resolve!: (value: T) => void + const promise = new Promise(done => { resolve = done }) + return { promise, resolve } +} + +async function upstream(label = "A") { + const calls: string[] = [], auth: (string | undefined)[] = [] + const arrived = deferred(), closed = deferred() + let holdContract = false, holdRequest = false, holdStream = false, schema = contract(), held: ServerResponse | undefined + let contractStatus = 200, rawContract: string | undefined + const server = createServer((request, response) => { + calls.push(`${request.method} ${request.url}`) + auth.push(request.headers.authorization) + response.setHeader("content-type", "application/json") + if (holdStream && request.url !== "/openapi.json") { + held = response + response.on("close", () => closed.resolve()) + response.write("first\n") + return + } + if (request.url === "/openapi.json") { + response.statusCode = contractStatus + if (holdContract) { held = response; arrived.resolve(); return } + response.end(rawContract ?? JSON.stringify(schema)); return + } + if (holdRequest) { held = response; response.on("close", () => closed.resolve()); arrived.resolve(); return } + if (request.url === "/api/info") response.end(JSON.stringify({ version: "99.0.0" })) + else response.end(JSON.stringify({ data: { id: "same-session", title: label } })) + }) + server.listen(0, "127.0.0.1") + await once(server, "listening") + const origin = `http://127.0.0.1:${(server.address() as { port: number }).port}` + return { origin, calls, auth, arrived: arrived.promise, closed: closed.promise, + blockContract() { holdContract = true }, blockRequest() { holdRequest = true }, + blockStream() { holdStream = true }, + schema(value: any) { schema = value }, finish() { held?.end(JSON.stringify(schema)) }, + contractResponse(status: number, raw?: string) { contractStatus = status; rawContract = raw }, + async close() { server.closeAllConnections(); await new Promise(resolve => server.close(() => resolve())) }, + } +} + +async function fixture(origins: string[], localOrigin = origins[0]!) { + let profiles: OpenCodeServerProfile[] = origins.map((origin, index) => ({ kind: "explicit", id: `s${index}`, label: `Server ${index}`, origin })) + const registry = new OpenCodeServerRegistry(() => profiles, next => { profiles = next }) + const credentials = new OpenCodeServerCredentials({ profileKey: "test", configIdentity: "config" }, registry) + for (const profile of profiles) await credentials.set(profile.id, JSON.stringify({ username: "test-user", password: "test-secret" })) + const local = new OpenCodeSharedService() + await local.endpoint({ kind: "lifecycle", identity: "fixture", lifecycle: { + discover: async () => ({ url: localOrigin }), ensure: async () => { throw new Error("No start allowed") }, + } }) + const owner = new OpenCodeServerConnections({ registry, credentials, local: { + acquire: () => local.acquire(), existing: () => local.existingConnection(), invalidate: () => local.invalidate(), + } }) + return { owner, credentials, registry, profiles, async close() { await owner.dispose(); await local.shutdown() } } +} + +test("A blocked at admission leaves B and local usable; IDs and clients stay scoped; same target shares reservation and promise", async t => { + const a = await upstream("A"), b = await upstream("B"), c = await upstream("Local") + const f = await fixture([a.origin, b.origin], c.origin) + t.after(async () => { await f.close(); await a.close(); await b.close(); await c.close() }) + a.blockContract() + const first = f.owner.connect("s0"), second = f.owner.acquireForServer("s0", "project") + assert.equal(first, second) + await a.arrived + const B = await f.owner.connect("s1"), local = await f.owner.acquireForServer("local-shared") + assert.equal((await B.client.session.get({ sessionID: "same-session" })).title, "B") + assert.equal((await local.client.session.get({ sessionID: "same-session" })).title, "Local") + a.finish() + const A = await first + assert.notEqual(A.client, B.client) + assert.notEqual(A.client, local.client) + assert.equal((await A.client.session.get({ sessionID: "same-session" })).title, "A") + assert.equal(a.calls.filter(call => call === "GET /openapi.json").length, 1) + assert.equal(a.auth[0], `Basic ${Buffer.from("test-user:test-secret").toString("base64")}`) +}) + +// prototype-1236 (R15): one connection per server, reused by every project, tab, window and folder browse. +test("every project and browse on one server shares a single connection, negotiated once", async t => { + const a = await upstream("A"), local = await upstream("Local") + const f = await fixture([a.origin], local.origin) + t.after(async () => { await f.close(); await a.close(); await local.close() }) + const leases = ["/one", "/two", "/two"].map(directory => f.owner.retainProject({ serverId: "s0", directory })) + const [first, ...others] = await Promise.all([...leases.map(lease => lease.acquire()), f.owner.connect("s0"), + f.owner.acquireForWorkspace({ serverId: "s0", directory: "/one" })]) + for (const connection of others) assert.equal(connection, first) + assert.equal(f.owner.existingForServer("s0"), first) + assert.equal(f.owner.activeExplicitTargets, 1) + assert.equal(a.calls.filter(call => call === "GET /openapi.json").length, 1) + leases[0]!.release() + assert.equal(await leases[1]!.acquire(), first, "closing one project keeps its siblings on the same connection") + for (const lease of leases) lease.release() +}) + +test("admitted-source observer snapshots existing slots, excludes reservations/probes/failures and retains offline targets", async t => { + const u = await upstream(), f = await fixture(Array(5).fill(u.origin)) + t.after(async () => { await f.close(); await u.close() }) + const snapshots: string[][] = [] + const off = f.owner.observeAdmitted(ids => snapshots.push([...ids])) + assert.deepEqual(snapshots.slice(), [[]]) + await f.owner.probe("s0") + assert.deepEqual(snapshots.slice(), [[]]) + await f.owner.connect("s0") + const late: string[][] = [] + const stopLate = f.owner.observeAdmitted(ids => late.push([...ids])) + assert.deepEqual(late, [["s0"]]) + f.owner.invalidateServer("s0") + assert.deepEqual(snapshots.at(-1), ["s0"]) + await f.owner.acquireForServer("s0") + for (const id of ["s1", "s2", "s3"]) await f.owner.connect(id) + await assert.rejects(f.owner.connect("s4"), { code: "quota" }) + assert.ok(snapshots.every(ids => !ids.includes("s4"))) + f.owner.disconnect("s0") + assert.deepEqual(snapshots.at(-1), ["s1", "s2", "s3"]) + off(); stopLate() +}) + +test("five concurrent restorations cap at four; last multi-window reference releases; disconnected tabs require Connect", async t => { + const u = await upstream(), f = await fixture(Array(5).fill(u.origin)) + t.after(async () => { await f.close(); await u.close() }) + const leases = f.profiles.map(profile => f.owner.retainProject({ serverId: profile.id, directory: "/same" })) + const extraWindow = f.owner.retainProject({ serverId: "s0", directory: "/same" }) + const results = await Promise.allSettled(leases.map(lease => lease.acquire())) + assert.deepEqual(results.map(result => result.status), ["fulfilled", "fulfilled", "fulfilled", "fulfilled", "rejected"]) + assert.equal((results[4] as PromiseRejectedResult).reason.code, "quota") + assert.equal(f.owner.activeExplicitTargets, 4) + leases[0]!.release() + assert.equal(f.owner.activeExplicitTargets, 4) + extraWindow.release() + assert.equal(f.owner.activeExplicitTargets, 3) + await leases[4]!.acquire() + assert.equal(f.owner.activeExplicitTargets, 4) + f.owner.disconnect("s1") + await assert.rejects(leases[1]!.acquire(), { code: "disconnected" }) + await assert.rejects(f.owner.acquireForWorkspace({ serverId: "s1", directory: "/same" }), { code: "disconnected" }) + await f.owner.connect("s1") + assert.equal(await leases[1]!.acquire(), f.owner.existingForServer("s1")) + for (const lease of leases) lease.release() + assert.equal(f.owner.activeExplicitTargets, 0) +}) + +test("initial failure frees reservation, admitted offline/retry and rotation retain it; Connect pin expires on first last-close", async t => { + const u = await upstream(), f = await fixture(Array(5).fill(u.origin)) + t.after(async () => { await f.close(); await u.close() }) + const missing = contract(); delete missing.components.schemas["Session.Message.Assistant.Text"] + u.schema(missing) + await assert.rejects(f.owner.connect("s0"), /native_contract/) + assert.equal(f.owner.activeExplicitTargets, 0) + u.schema(contract()) + const first = await f.owner.connect("s0") + assert.equal(f.owner.activeExplicitTargets, 1) + f.owner.invalidateServer("s0") + assert.equal(f.owner.activeExplicitTargets, 1) + u.schema(missing) + await assert.rejects(f.owner.acquireForServer("s0"), /native_contract/) + assert.equal(f.owner.activeExplicitTargets, 1) + u.schema(contract()) + const retry = await f.owner.acquireForServer("s0") + assert.notEqual(retry, first) + first.invalidate() // A retired caller cannot invalidate the replacement. + retry.assertCurrent() + await f.credentials.set("s0", JSON.stringify({ username: "rotated", password: "new" })) + assert.equal(f.owner.activeExplicitTargets, 1) + assert.throws(retry.assertCurrent, /stale_connection/) + await f.owner.acquireForServer("s0") + const lease = f.owner.retainProject({ serverId: "s0", directory: "/same" }) + lease.release(); lease.release() + assert.equal(f.owner.activeExplicitTargets, 0) + await f.owner.connect("s4") + f.owner.disconnect("s4") + assert.equal(f.owner.activeExplicitTargets, 0) +}) + +for (const action of ["rotate", "forget", "disconnect", "remove", "retarget", "shutdown"] as const) { + test(`${action} aborts in-flight HTTP and denies held fetch/client/profile wrappers`, async t => { + const u = await upstream(), f = await fixture([u.origin]) + t.after(async () => { await f.close(); await u.close() }) + const connection = await f.owner.connect("s0") + const fetch = connection.fetch, client = connection.client, profile = connection.profile + u.blockRequest() + const inflight = fetch(`${u.origin}/api/session/same-session`) + const rejected = assert.rejects(inflight) + await u.arrived + if (action === "rotate") await f.credentials.set("s0", JSON.stringify({ username: "new", password: "new" })) + if (action === "forget") await f.credentials.clear("s0") + if (action === "disconnect") f.owner.disconnect("s0") + if (action === "remove") f.registry.replace([]) + if (action === "retarget") f.registry.replace([{ ...f.profiles[0]!, origin: "http://127.0.0.1:1" }]) + if (action === "shutdown") await f.owner.dispose() + await rejected + await u.closed + const count = u.calls.length + await assert.rejects(fetch(`${u.origin}/api/session/same-session`)) + await assert.rejects(client.session.get({ sessionID: "same-session" })) + await assert.rejects(client.event.subscribe()[Symbol.asyncIterator]().next()) + await assert.rejects(profile()) + u.finish() // A late server completion cannot resurrect a revoked generation. + assert.equal(u.calls.length, count) + if (action === "remove" || action === "retarget") { + f.registry.replace(f.profiles) + assert.equal(await f.credentials.readForConnection("s0"), null) + } + assert.doesNotMatch(JSON.stringify(connection.endpoint), /test-secret|test-user/) + }) +} + +test("disconnect during admission fences late completion and immediately makes room for fifth target", async t => { + const a = await upstream(), b = await upstream(), f = await fixture([a.origin, b.origin, b.origin, b.origin, b.origin]) + t.after(async () => { await f.close(); await a.close(); await b.close() }) + a.blockContract() + const pending = f.owner.connect("s0"), rejected = assert.rejects(pending) + await a.arrived + await Promise.all(["s1", "s2", "s3"].map(id => f.owner.connect(id))) + await assert.rejects(f.owner.connect("s4"), { code: "quota" }) + f.owner.disconnect("s0") + const fifth = await f.owner.connect("s4") + a.finish() + await rejected + fifth.assertCurrent() + assert.equal(f.owner.existingForServer("s0"), undefined) +}) + +test("revocation aborts already returned streaming bodies", async t => { + const u = await upstream(), f = await fixture([u.origin]) + t.after(async () => { await f.close(); await u.close() }) + const old = await f.owner.connect("s0") + u.blockStream() + const response = await old.fetch(`${u.origin}/api/event`), reader = response.body!.getReader() + assert.equal(new TextDecoder().decode((await reader.read()).value), "first\n") + const waiting = reader.read(), rejected = assert.rejects(waiting) + await f.credentials.set("s0", JSON.stringify({ username: "next", password: "next" })) + await rejected + await u.closed +}) + +for (const action of ["rotate", "forget", "disconnect", "remove", "retarget", "shutdown", "request-abort"] as const) { + for (const location of [false, true]) test(`${action} cancels open ${location ? "location JSON" : "binary"} body preparation without producer completion`, async t => { + const u = await upstream(), f = await fixture([u.origin]) + t.after(async () => { await f.close(); await u.close() }) + const connection = await f.owner.connect("s0"), abort = new AbortController() + let cancelled = false + const request = new Request(`${u.origin}/api/session/same-session/prompt`, { + method: "POST", signal: abort.signal, + headers: location ? { "x-codenomad-location": JSON.stringify({ directory: "/same" }) } : {}, + body: new ReadableStream({ cancel() { cancelled = true } }), duplex: "half", + } as RequestInit) + const count = u.calls.length, sending = connection.fetch(request) + const rejected = assert.rejects(sending) + await new Promise(resolve => setImmediate(resolve)) + if (action === "rotate") await f.credentials.set("s0", JSON.stringify({ username: "next", password: "next" })) + if (action === "forget") await f.credentials.clear("s0") + if (action === "disconnect") f.owner.disconnect("s0") + if (action === "remove") f.registry.replace([]) + if (action === "retarget") f.registry.replace([{ ...f.profiles[0]!, origin: "http://127.0.0.1:1" }]) + if (action === "shutdown") await f.owner.dispose() + if (action === "request-abort") abort.abort() + assert.equal(await Promise.race([rejected.then(() => true), new Promise(resolve => setTimeout(() => resolve(false), 150))]), true, + "fetch must reject while producer remains open") + await new Promise(resolve => setImmediate(resolve)) + assert.equal(cancelled, true, "body reader must cancel its source") + assert.equal(u.calls.length, count, "prepared mutation must never dispatch or replay") + if (["disconnect", "remove", "retarget", "shutdown"].includes(action)) assert.equal(f.owner.activeExplicitTargets, 0) + }) +} + +test("retarget and server-ID reuse clear credentials before publication; old wrappers cannot disconnect a replacement", async t => { + const a = await upstream(), b = await upstream(), f = await fixture([a.origin]) + t.after(async () => { await f.close(); await a.close(); await b.close() }) + const old = await f.owner.connect("s0") + f.registry.replace([{ ...f.profiles[0]!, origin: b.origin }]) + assert.deepEqual(await f.credentials.status("s0"), { hasCredentials: false, needsCredentials: true }) + await f.credentials.set("s0", JSON.stringify({ username: "B", password: "B" })) + const current = await f.owner.connect("s0") + await assert.rejects(old.fetch(`${a.origin}/api/info`)) + old.invalidate() + current.assertCurrent() + assert.equal(f.owner.existingForServer("s0"), current) + f.registry.replace([]) + f.registry.replace(f.profiles) + assert.equal(await f.credentials.readForConnection("s0"), null) + await assert.rejects(f.owner.connect("s0"), { code: "needs_credentials" }) +}) + +test("missing required E1 routes, bodies or replay schemas reject before functional traffic", async t => { + const u = await upstream(), f = await fixture([u.origin]) + t.after(async () => { await f.close(); await u.close() }) + for (const remove of [ + (schema: any) => { delete schema.paths["/api/event"] }, + (schema: any) => { delete schema.paths["/api/session/{sessionID}/form/{formID}/reply"].post.requestBody }, + (schema: any) => { delete schema.components.schemas["Session.Info"] }, + (schema: any) => { delete schema.components.schemas["Session.Message.Assistant.Text"] }, + ]) { + const schema = contract(); remove(schema); u.schema(schema) + await assert.rejects(f.owner.connect("s0"), { code: "missing_contract" }) + assert.equal(f.owner.activeExplicitTargets, 0) + } + assert.deepEqual(u.calls, Array(4).fill("GET /openapi.json")) +}) + +test("bounded probes share one separate lane and create neither slots nor SSE; future contract needs no env/plugin/image enrichment", async t => { + const a = await upstream(), b = await upstream(), f = await fixture([a.origin, b.origin]) + t.after(async () => { await f.close(); await a.close(); await b.close() }) + a.blockContract() + const abort = new AbortController(), pending = f.owner.probe("s0", abort.signal), rejected = assert.rejects(pending) + await a.arrived + await assert.rejects(f.owner.probe("s1"), { code: "probe_busy" }) + assert.equal(f.owner.activeExplicitTargets, 0) + abort.abort() + await rejected + await f.owner.probe("s1") + assert.equal(f.owner.activeExplicitTargets, 0) + const connection = await f.owner.connect("s1") + const response = await connection.fetch(`${b.origin}/api/info`) + assert.equal((await response.json()).version, "99.0.0") + assert.ok([...a.calls, ...b.calls].every(call => /^GET (\/openapi.json|\/api\/info)$/.test(call))) + assert.equal(f.owner.existingForServer("unknown"), undefined) + await assert.rejects(f.owner.acquireForServer("unknown", "project"), { code: "unknown_server" }) +}) + +test("authentication and malformed-contract diagnostics are fixed codes without response or credential contents", async t => { + const u = await upstream(), f = await fixture([u.origin]) + t.after(async () => { await f.close(); await u.close() }) + u.contractResponse(401, "test-secret is echoed by a broken upstream") + await assert.rejects(f.owner.connect("s0"), { code: "auth", message: "auth" }) + // prototype-1236: a 401 forgets the rejected credential until a new link or password. + await new Promise(resolve => setImmediate(resolve)) + await assert.rejects(f.owner.connect("s0"), { code: "needs_credentials" }) + await f.credentials.set("s0", JSON.stringify({ username: "test-user", password: "test-secret" })) + u.contractResponse(200, "test-secret is malformed JSON") + await assert.rejects(f.owner.connect("s0"), { code: "missing_contract", message: "missing_contract: canonical_api" }) + assert.equal(f.owner.activeExplicitTargets, 0) +}) + +test("SettingsService shares registry, credentials and connection owner across window callers; summaries are live and shutdown clears memory", async t => { + const u = await upstream(), root = mkdtempSync(path.join(process.cwd(), ".tmp-connections-")) + const settings = new SettingsService(resolveConfigLocation(path.join(root, "config.yaml")), undefined, pino({ level: "silent" })) + const local = { acquire: async () => { throw new Error("Local must not be used") }, existing: () => undefined, invalidate() {} } + const manager = new WorkspaceManager({ rootDir: root, settings, binaryResolver: new BinaryResolver(settings), + eventBus: new EventBus(), logger: pino({ level: "silent" }) }) + t.after(async () => { await manager.shutdown(); await u.close(); rmSync(root, { recursive: true, force: true }) }) + settings.getOpenCodeServerRegistry().replace([{ kind: "explicit", id: "s0", label: "A", origin: u.origin }]) + assert.equal(settings.getOpenCodeServerRegistry(), settings.getOpenCodeServerRegistry()) + assert.equal(settings.getOpenCodeServerCredentials(), settings.getOpenCodeServerCredentials()) + const owner = manager.getServerConnections() + assert.equal(owner, settings.getOpenCodeServerConnections(local)) + await settings.getOpenCodeServerCredentials().set("s0", JSON.stringify({ username: "sentinel", password: "sentinel" })) + assert.deepEqual((await settings.getOpenCodeServerSummaries())[1], { + kind: "explicit", id: "s0", label: "A", origin: u.origin, hasCredentials: true, needsCredentials: false, + }) + const connection = await owner.connect("s0") + await manager.shutdown() + await assert.rejects(connection.fetch(`${u.origin}/api/info`)) + await assert.rejects(settings.getOpenCodeServerCredentials().readForConnection("s0"), { code: "closed" }) + const restarted = new SettingsService(resolveConfigLocation(path.join(root, "config.yaml")), undefined, pino({ level: "silent" })) + assert.equal((await restarted.getOpenCodeServerSummaries())[1]?.kind, "explicit") + // prototype-1236 (R17): a manual password is kept across launches, in the private backend file only. + assert.deepEqual(await restarted.getOpenCodeServerCredentials().status("s0"), { hasCredentials: true, needsCredentials: false }) + const config = readFileSync(path.join(root, "config.yaml"), "utf8") + assert.equal(config.includes("sentinel"), false) + assert.equal(readFileSync(path.join(root, "opencode-server-pairings.json"), "utf8").includes("sentinel"), true) + await restarted.getOpenCodeServerCredentials().rejected("s0") + assert.equal(readFileSync(path.join(root, "opencode-server-pairings.json"), "utf8").includes("sentinel"), false, "a 401 forgets it") + await restarted.disposeOpenCodeServers() +}) diff --git a/packages/server/src/opencode/servers/connections.ts b/packages/server/src/opencode/servers/connections.ts new file mode 100644 index 0000000000..0af2685769 --- /dev/null +++ b/packages/server/src/opencode/servers/connections.ts @@ -0,0 +1,348 @@ +import { OpenCode } from "@opencode/client" +import type { ServiceConnection } from "../../workspaces/opencode-service" +import { createRuntimeTransport } from "../compatibility/transport" +import type { OpenCodeServerCredentials } from "./credentials" +import type { OpenCodeServerRegistry } from "./registry" +import { createExplicitTransport } from "./transport" +import { LOCAL_SHARED_SERVER_ID, SERVER_CONNECTION_LIMITS, type ProjectExecutionBinding } from "./types" +import { parseProbeCandidate, probeExplicitCandidate, ServerProbeError, type ProbeCandidate, type ServerProbeResult } from "./probe" +import type { ResolveAddresses } from "./endpoint" +import { waitForAdmission } from "../../server/request-admission" +import { randomUUID } from "node:crypto" +import type { ServerAttachmentReservation, ServerAttachmentReservations } from "./attachment-types" + +type Failure = "unknown_server" | "needs_credentials" | "invalid_credentials" | "auth" | "quota" | "disconnected" | "closed" | "stale_connection" | "probe_busy" +export class ServerConnectionError extends Error { + constructor(readonly code: Failure) { super(code); this.name = "ServerConnectionError" } +} +export interface ServerConnection extends ServiceConnection { + serverId: string + generation: number + signal: AbortSignal +} +type Slot = { + origin: string; admitted: boolean + controller?: AbortController; pending?: Promise; connection?: ServerConnection +} +export interface ServerProjectLease { + acquire(): Promise + published(instanceId: string): void + release(): void +} +type AdmissionObserver = (serverIds: readonly string[], credentialsChanged?: string) => void + +/** Backend-wide owner. Local lifecycle is delegated; explicit traffic only uses the protected dialer. */ +export class OpenCodeServerConnections { + #slots = new Map() + #projects = new Map>() + #disconnected = new Set() + #generation = 0 + #closed = false + #probe?: { serverId?: string; origin?: string; controller: AbortController } + #unsubscribers: (() => void)[] + #admissionObservers = new Set() + #attachmentReceipt = randomUUID() + #attachmentReservations = new Map() + + constructor(private readonly options: { + registry: OpenCodeServerRegistry + credentials: OpenCodeServerCredentials + local: { acquire(): Promise; existing(): ServiceConnection | undefined; invalidate(): void } + resolveAddresses?: ResolveAddresses + }) { + this.#unsubscribers = [ + options.credentials.onChange(id => { + if (id === undefined) { + for (const key of this.#slots.keys()) { this.invalidateServer(key); this.publishAdmission(key) } + } else { this.invalidateServer(id); this.publishAdmission(id) } + if (id === undefined || this.#probe?.serverId === id) this.#probe?.controller.abort() + }), + options.registry.beforeChange(next => { + this.attachmentsChanged() + for (const [id, slot] of this.#slots) { + const profile = next.find(value => value.id === id) + if (profile?.kind !== "explicit" || profile.origin !== slot.origin) this.disconnect(id) + } + if (this.#probe?.serverId) { + const profile = next.find(value => value.id === this.#probe!.serverId) + if (profile?.kind !== "explicit" || profile.origin !== this.#probe.origin) this.#probe.controller.abort() + } + }), + ] + } + + get activeExplicitTargets(): number { return this.#slots.size } + + /** Reservations include occurrences held before workspace publication and disconnected leases. */ + attachmentReservations(serverId: string): ServerAttachmentReservations { + const reservations = [...this.#attachmentReservations.values()].filter(value => value.serverId === serverId) + return { + receipt: this.#attachmentReceipt, + status: this.#closed || reservations.length > 512 ? "unknown" : "complete", + reservations: reservations.slice(0, 512).map(value => ({ ...value })), + inFlight: Boolean(this.#slots.get(serverId)?.pending) || reservations.some(value => value.state === "reserved"), + } + } + + attachmentReceiptCurrent(receipt: string): boolean { + return !this.#closed && receipt === this.#attachmentReceipt + } + + private attachmentsChanged(): void { this.#attachmentReceipt = randomUUID() } + + /** Snapshot only: no admission, discovery, profile negotiation or lifecycle effects. */ + administrativeState(serverId: string, origin?: string): "connected" | "connecting" | "admitted_offline" | "disconnected" | "unknown" { + if (this.#closed) return "unknown" + if (serverId === LOCAL_SHARED_SERVER_ID) return this.options.local.existing() ? "connected" : "unknown" + const profile = this.options.registry.get(serverId) + if (profile?.kind !== "explicit" || (origin !== undefined && profile.origin !== origin)) return "unknown" + const slot = this.#slots.get(serverId) + if (slot && slot.origin !== profile.origin) return "unknown" + if (slot?.connection && !slot.connection.signal.aborted) return "connected" + if (slot?.pending && !slot.controller?.signal.aborted) return "connecting" + if (slot?.admitted) return "admitted_offline" + if (this.#disconnected.has(serverId)) return "disconnected" + return "unknown" + } + + /** Register before the synchronous snapshot, so admission cannot fall between them. */ + observeAdmitted(observer: AdmissionObserver): () => void { + this.#admissionObservers.add(observer) + observer(this.admitted()) + return () => { this.#admissionObservers.delete(observer) } + } + + private admitted(): string[] { + return [...this.#slots].filter(([, slot]) => slot.admitted).map(([id]) => id) + } + + private publishAdmission(credentialsChanged?: string): void { + const ids = this.admitted() + for (const observer of this.#admissionObservers) observer(ids, credentialsChanged) + } + + /** Connect is an explicit in-memory pin. Reading an already disconnected tab cannot call it implicitly. */ + connect(serverId: string): Promise { + this.#disconnected.delete(serverId) + return this.acquireForServer(serverId, "connect") + } + + acquireForWorkspace(binding: ProjectExecutionBinding): Promise { + return this.acquireForServer(binding.serverId, "read") + } + + /** Project occurrence leases span windows; each release is idempotent. */ + retainProject(binding: ProjectExecutionBinding): ServerProjectLease { + this.assertOpen() + this.profile(binding.serverId) + const id = binding.serverId, token = Symbol() + const projects = this.#projects.get(id) ?? new Set() + projects.add(token) + this.#projects.set(id, projects) + this.#attachmentReservations.set(token, { reservationId: randomUUID(), serverId: id, directory: binding.directory, state: "reserved" }) + this.attachmentsChanged() + let released = false + return { + acquire: () => released ? Promise.reject(new ServerConnectionError("disconnected")) : this.acquireForServer(id, "project"), + published: instanceId => { + const reservation = this.#attachmentReservations.get(token) + if (released || !reservation || reservation.instanceId === instanceId) return + this.#attachmentReservations.set(token, { ...reservation, instanceId, state: "published" }) + this.attachmentsChanged() + }, + release: () => { + if (released) return + released = true + this.#attachmentReservations.delete(token) + this.attachmentsChanged() + projects.delete(token) + if (!projects.size) { + this.#projects.delete(id) + this.releaseSlot(id) + } + }, + } + } + + /** Reservation is synchronous, before the first await; only fresh project intent or Connect may admit. */ + acquireForServer(serverId: string, intent: "read" | "project" | "connect" = "read"): Promise { + try { + this.assertOpen() + if (serverId === LOCAL_SHARED_SERVER_ID) return this.options.local.acquire() + const profile = this.profile(serverId) + if (profile.kind !== "explicit") throw new ServerConnectionError("unknown_server") + if (this.#disconnected.has(serverId)) throw new ServerConnectionError("disconnected") + let slot = this.#slots.get(serverId) + if (slot && slot.origin !== profile.origin) { this.disconnect(serverId); throw new ServerConnectionError("disconnected") } + if (!slot) { + if (intent === "read") throw new ServerConnectionError("disconnected") + if (this.#slots.size >= SERVER_CONNECTION_LIMITS.explicitActiveTargets) throw new ServerConnectionError("quota") + slot = { origin: profile.origin, admitted: false } + this.#slots.set(serverId, slot) + this.attachmentsChanged() + } + if (slot.connection) return Promise.resolve(slot.connection) + if (slot.pending) return slot.pending + const current = slot, controller = new AbortController(), generation = ++this.#generation + this.attachmentsChanged() + current.controller = controller + const assertCurrent = () => { + if (this.#closed || controller.signal.aborted || this.#slots.get(serverId) !== current || current.controller !== controller) { + throw new ServerConnectionError("stale_connection") + } + const metadata = this.options.registry.get(serverId) + if (metadata?.kind !== "explicit" || metadata.origin !== current.origin) { + this.disconnect(serverId) + throw new ServerConnectionError("stale_connection") + } + } + const pending = this.create(serverId, current.origin, generation, controller.signal, assertCurrent).then(connection => { + assertCurrent() + current.admitted = true + current.connection = connection + this.attachmentsChanged() + this.publishAdmission() + return connection + }).catch(error => { + if (this.#slots.get(serverId) === current && current.controller === controller) { + controller.abort() + if (!current.admitted) this.#slots.delete(serverId) + this.attachmentsChanged() + } + throw error + }).finally(() => { if (current.pending === pending) { current.pending = undefined; this.attachmentsChanged() } }) + current.pending = pending + return pending + } catch (error) { return Promise.reject(error) } + } + + existingForServer(serverId: string): ServiceConnection | undefined { + if (serverId === LOCAL_SHARED_SERVER_ID) return this.options.local.existing() + const connection = this.#slots.get(serverId)?.connection + connection?.assertCurrent() + return connection + } + + /** Offline and credential rotation keep an admitted slot, but revoke every captured wrapper. */ + invalidateServer(serverId: string): void { + this.attachmentsChanged() + if (serverId === LOCAL_SHARED_SERVER_ID) { this.options.local.invalidate(); return } + const slot = this.#slots.get(serverId) + if (!slot) return + slot.controller?.abort() + slot.controller = undefined + slot.connection = undefined + slot.pending = undefined + if (!slot.admitted) this.#slots.delete(serverId) + } + + disconnect(serverId: string): void { + this.attachmentsChanged() + if (serverId === LOCAL_SHARED_SERVER_ID) { this.options.local.invalidate(); return } + if (this.#probe?.serverId === serverId) this.#probe.controller.abort() + this.#disconnected.add(serverId) + this.releaseSlot(serverId) + } + + /** Single read-only bounded lane, separate from active reservations and event subscriptions. */ + probe(serverId: string, signal?: AbortSignal): Promise { + return this.runProbe(async () => { + const profile = this.profile(serverId) + if (profile.kind !== "explicit") throw new ServerConnectionError("unknown_server") + if (this.#probe) this.#probe.origin = profile.origin + const value = await this.options.credentials.readForConnection(serverId) + if (value === null) throw new ServerProbeError("needs_credentials", "credentials") + try { return parseProbeCandidate({ origin: profile.origin, credentials: JSON.parse(value) }) } + catch { throw new ServerProbeError("invalid_credentials", "credentials") } + }, signal, serverId) + } + + probeCandidate(candidate: ProbeCandidate, signal?: AbortSignal): Promise { + return this.runProbe(async () => parseProbeCandidate(candidate), signal) + } + + private async runProbe(candidate: () => Promise, signal?: AbortSignal, serverId?: string): Promise { + this.assertOpen() + if (this.#probe) throw new ServerConnectionError("probe_busy") + const controller = new AbortController() + this.#probe = { serverId, controller } + const deadline = performance.now() + SERVER_CONNECTION_LIMITS.probeTimeoutMs + const timer = setTimeout(() => controller.abort(new ServerProbeError("timeout", "operation")), SERVER_CONNECTION_LIMITS.probeTimeoutMs) + const lifetime = AbortSignal.any([controller.signal, ...(signal ? [signal] : [])]) + const current = () => { + lifetime.throwIfAborted() + if (performance.now() >= deadline) throw new ServerProbeError("timeout", "operation") + this.assertOpen() + } + try { + return await waitForAdmission((async () => { + current() + const value = await candidate() + current() + const result = await probeExplicitCandidate(value, lifetime, current, this.options.resolveAddresses) + current() + return result + })(), lifetime) + } finally { clearTimeout(timer); controller.abort(); if (this.#probe?.controller === controller) this.#probe = undefined } + } + + async dispose(): Promise { + this.#closed = true + this.attachmentsChanged() + this.#probe?.controller.abort() + for (const id of this.#slots.keys()) this.releaseSlot(id) + this.#admissionObservers.clear() + this.#projects.clear() + this.#attachmentReservations.clear() + this.#disconnected.clear() + for (const unsubscribe of this.#unsubscribers) unsubscribe() + await this.options.credentials.dispose() + } + + private async create(serverId: string, origin: string, generation: number, signal: AbortSignal, assertCurrent: () => void): Promise { + const value = await this.options.credentials.readForConnection(serverId) + assertCurrent() + if (value === null) throw new ServerConnectionError("needs_credentials") + let credentials: { username: string; password: string } + try { + credentials = JSON.parse(value) + if (!credentials || typeof credentials.username !== "string" || typeof credentials.password !== "string" || credentials.username.includes(":")) throw new Error() + } catch { throw new ServerConnectionError("invalid_credentials") } + const protectedTransport = createExplicitTransport({ origin, credentials, signal }) + const endpoint = { url: origin } + const dispatch: typeof fetch = async (input, init) => { + assertCurrent() + const response = await protectedTransport.fetch(input, init) + try { + assertCurrent() + if (response.status === 401) void this.options.credentials.rejected(serverId) // prototype-1236: re-pair + if (response.status === 401 || response.status === 403) throw new ServerConnectionError("auth") + return response + } + catch (error) { await response.body?.cancel().catch(() => {}); throw error } + } + const transport = createRuntimeTransport(endpoint, dispatch, signal, "explicit-e1") + const fetch: typeof globalThis.fetch = async (input, init) => { assertCurrent(); return transport.fetch(input, init) } + const connection: ServerConnection = { + serverId, generation, signal, endpoint, fetch, assertCurrent, + invalidate: () => { if (!signal.aborted) this.invalidateServer(serverId) }, + profile: async localSignal => { assertCurrent(); const result = await transport.profile(localSignal); assertCurrent(); return result }, + client: OpenCode.make({ baseUrl: origin, fetch }), + } + await connection.profile() + return connection + } + + private profile(id: string) { + const profile = this.options.registry.get(id) + if (!profile) throw new ServerConnectionError("unknown_server") + return profile + } + private assertOpen(): void { if (this.#closed) throw new ServerConnectionError("closed") } + private releaseSlot(id: string): void { + this.attachmentsChanged() + this.#slots.get(id)?.controller?.abort() + this.#slots.delete(id) + this.publishAdmission() + } +} diff --git a/packages/server/src/opencode/servers/credentials.test.ts b/packages/server/src/opencode/servers/credentials.test.ts new file mode 100644 index 0000000000..d8bb095486 --- /dev/null +++ b/packages/server/src/opencode/servers/credentials.test.ts @@ -0,0 +1,138 @@ +import assert from "node:assert/strict" +import test from "node:test" +import fs from "node:fs" +import path from "node:path" +import { execFileSync } from "node:child_process" +import pino from "pino" +import { OpenCodeServerCredentials } from "./credentials" +import { OpenCodeServerRegistry } from "./registry" +import { sanitizeConfigDoc } from "../../settings/public-config" +import { SettingsService } from "../../settings/service" +import { resolveConfigLocation } from "../../config/location" +import type { EventBus } from "../../events/bus" + +const scope = { profileKey: "stable", configIdentity: "config-a" } +const username = "username-sentinel-never-persist" +const password = "password-sentinel-never-persist" +const secret = JSON.stringify({ username, password }) +const authorization = Buffer.from(`${username}:${password}`).toString("base64") +const profile = { kind: "explicit", id: "target", label: "Target", origin: "https://example.test" } as const + +function fixture() { + let metadata: unknown = [profile] + const registry = new OpenCodeServerRegistry(() => metadata, next => { metadata = next }) + const create = (ownerScope = scope) => new OpenCodeServerCredentials(ownerScope, registry) + return { registry, create, metadata: () => metadata } +} + +test("memory rotation and clearing never publish metadata; every fresh owner requires entry", async () => { + const f = fixture(), owner = f.create() + assert.deepEqual(await owner.status("target"), { hasCredentials: false, needsCredentials: true }) + assert.equal(await owner.set("target", secret), undefined) + assert.equal(await owner.readForConnection("target"), secret) + assert.deepEqual(await owner.status("target"), { hasCredentials: true, needsCredentials: false }) + for (const scopeValue of [scope, { ...scope, profileKey: "dev" }, { ...scope, configIdentity: "other" }]) { + assert.deepEqual(await f.create(scopeValue).status("target"), { hasCredentials: false, needsCredentials: true }) + } + await Promise.all([owner.set("target", "one"), owner.set("target", "two")]) + assert.equal(await owner.readForConnection("target"), "two") + assert.deepEqual(f.metadata(), [profile]) + assert.deepEqual(JSON.parse(JSON.stringify(owner)), {}) + await Promise.all([owner.set("target", "three"), owner.clear("target")]) + assert.equal(await owner.readForConnection("target"), null) + await owner.clear("target") + await owner.dispose() + for (const action of [() => owner.set("target", secret), () => owner.readForConnection("target"), + () => owner.status("target"), () => owner.clear("target")]) await assert.rejects(action(), { code: "closed" }) +}) + +test("server and origin changes isolate credentials; forget remains safe after metadata removal", async () => { + const f = fixture(), owner = f.create() + f.registry.replace([profile, { ...profile, id: "other" }]) + await owner.set("target", secret) + assert.equal(await owner.readForConnection("other"), null) + f.registry.replace([{ ...profile, origin: "https://other.test" }]) + assert.equal(await owner.readForConnection("target"), null) + f.registry.replace([profile]) + assert.equal(await owner.readForConnection("target"), null) + await owner.set("target", secret) + f.registry.replace([]) + await owner.clear("target") + f.registry.replace([profile]) + assert.equal(await owner.readForConnection("target"), null) + await owner.set("target", secret) + f.registry.replace([]) + await assert.rejects(owner.readForConnection("target"), { code: "unknown_server" }) + f.registry.replace([profile]) + assert.equal(await owner.readForConnection("target"), null) +}) + +test("validation and metadata errors use fixed codes and preserve the active value", async () => { + const f = fixture(), owner = f.create() + await owner.set("target", secret) + for (const value of ["", "x".repeat(16 * 1024 + 1), null, {}, 1]) { + await assert.rejects(owner.set("target", value as string), { code: "invalid_credentials", message: "invalid_credentials" }) + } + assert.equal(await owner.readForConnection("target"), secret) + for (const id of ["local-shared", "missing"]) await assert.rejects(owner.set(id, secret), { code: "unknown_server" }) + const broken = new OpenCodeServerCredentials(scope, new OpenCodeServerRegistry(() => { throw new Error(secret) }, () => {})) + await assert.rejects(broken.set("target", secret), { code: "metadata_unavailable", message: "metadata_unavailable" }) +}) + +test("real config, backups, logs, API/event/browser projections exclude username, password and Authorization", async () => { + const root = fs.mkdtempSync(path.join(process.cwd(), ".tmp-credentials-")) + const events: unknown[] = [] + const destination = pino.destination({ dest: path.join(root, "backend.log"), sync: true }) + const logger = pino(destination) + try { + const location = resolveConfigLocation(path.join(root, "config.yaml")) + const settings = new SettingsService(location, + { publish: (event: unknown) => events.push(event) } as unknown as EventBus, logger) + const registry = settings.getOpenCodeServerRegistry() + registry.replace([profile]) + const owner = new OpenCodeServerCredentials(scope, registry) + const before = fs.readFileSync(location.configYamlPath, "utf8") + await owner.set("target", secret) + await owner.set("target", authorization) + await owner.set("target", secret) + assert.equal(fs.readFileSync(location.configYamlPath, "utf8"), before) + const restartedSettings = new SettingsService(location, undefined, logger) + const restartedOwner = new OpenCodeServerCredentials(scope, restartedSettings.getOpenCodeServerRegistry()) + assert.equal((await restartedOwner.status("target")).needsCredentials, true) + await restartedOwner.dispose() + const restarted = execFileSync(process.execPath, ["--import", "tsx", "--input-type=module", "-e", ` + import pino from 'pino'; + import { SettingsService } from './packages/server/src/settings/service.ts'; + import { resolveConfigLocation } from './packages/server/src/config/location.ts'; + import { OpenCodeServerCredentials } from './packages/server/src/opencode/servers/credentials.ts'; + const settings = new SettingsService(resolveConfigLocation(process.argv[1]), undefined, pino({level:'silent'})); + const owner = new OpenCodeServerCredentials(${JSON.stringify(scope)}, settings.getOpenCodeServerRegistry()); + console.log(JSON.stringify(await owner.status('target'))); + `, location.configYamlPath], { encoding: "utf8", windowsHide: true }) + assert.deepEqual(JSON.parse(restarted), { hasCredentials: false, needsCredentials: true }) + fs.copyFileSync(location.configYamlPath, path.join(root, "config.yaml.backup")) + settings.mergePatchOwner("config", "server", { logLevel: "WARN" }) + registry.replace([{ ...profile, label: "Changed" }]) + assert.equal(await owner.readForConnection("target"), secret) + const api = sanitizeConfigDoc(settings.getDoc("config")) + logger.info(await owner.status("target"), "credential status") + const assertSafe = (value: string) => { + for (const sentinel of [username, password, authorization]) assert.ok(!value.includes(sentinel)) + assert.doesNotMatch(value, /credentialRef|credentialMode|credentialStoreStatus/) + } + assertSafe(JSON.stringify({ events, api, browser: structuredClone(api), owner })) + const scan = (directory: string) => { + for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { + const file = path.join(directory, entry.name) + if (entry.isDirectory()) scan(file) + else assertSafe(fs.readFileSync(file, "utf8")) + } + } + scan(root) + await owner.clear("target") + await owner.dispose() + } finally { + destination.end() + fs.rmSync(root, { recursive: true, force: true }) + } +}) diff --git a/packages/server/src/opencode/servers/credentials.ts b/packages/server/src/opencode/servers/credentials.ts new file mode 100644 index 0000000000..0511edd865 --- /dev/null +++ b/packages/server/src/opencode/servers/credentials.ts @@ -0,0 +1,124 @@ +import type { OpenCodeServerRegistry } from "./registry" +import type { PairingTokenStore } from "./pairing-store" + +export interface CredentialScope { profileKey: string; configIdentity: string } +type Failure = "unknown_server" | "invalid_credentials" | "metadata_unavailable" | "closed" +export class CredentialOperationError extends Error { + constructor(readonly code: Failure) { super(code); this.name = "CredentialOperationError" } +} + +/** One private owner per backend profile/config. Only backend transport code may read secrets. */ +export class OpenCodeServerCredentials { + #scope: CredentialScope + #registry: OpenCodeServerRegistry + #memory = new Map() + #closed = false + #listeners = new Set<(serverId?: string) => void>() + #unsubscribe: () => void + + #paired?: PairingTokenStore + + constructor(scope: CredentialScope, registry: OpenCodeServerRegistry, paired?: PairingTokenStore) { + this.#scope = { ...scope } + this.#registry = registry + this.#paired = paired + this.#unsubscribe = registry.beforeChange(next => { + for (const previous of registry.list()) { + const id = previous.id, profile = next.find(value => value.id === id) + if (previous?.kind !== "explicit" || profile?.kind !== "explicit" || previous.origin !== profile.origin) { + this.#paired?.delete(id) + if (this.#memory.delete(id)) this.notify(id) + } + } + }) + } + + onChange(listener: (serverId?: string) => void): () => void { + this.#listeners.add(listener) + return () => { this.#listeners.delete(listener) } + } + + private notify(id?: string): void { for (const listener of this.#listeners) listener(id) } + + private key(serverId: string): string { + if (this.#closed) throw new CredentialOperationError("closed") + let profile + try { profile = this.#registry.get(serverId) } + catch { throw new CredentialOperationError("metadata_unavailable") } + if (profile?.kind !== "explicit") { + if (this.#memory.delete(serverId)) this.notify(serverId) + throw new CredentialOperationError("unknown_server") + } + const key = JSON.stringify([this.#scope.profileKey, this.#scope.configIdentity, serverId, profile.origin]) + if (this.#memory.get(serverId)?.key !== key && this.#memory.delete(serverId)) this.notify(serverId) + return key + } + + /** Secret-bearing backend seam. Never mount as a route or event payload. */ + async readForConnection(serverId: string): Promise { + const key = this.key(serverId) + const value = this.#memory.get(serverId)?.value + if (value !== undefined) return value + return this.#paired?.read(serverId, key) ?? null + } + + async status(serverId: string) { + const hasCredentials = (await this.readForConnection(serverId)) !== null + return { hasCredentials, needsCredentials: !hasCredentials } + } + + /** Metadata-only status; never materializes a secret or mutates the private Map. */ + hasCredentials(serverId: string): boolean { + if (this.#closed) return false + const profile = this.#registry.get(serverId) + if (profile?.kind !== "explicit") return false + const key = JSON.stringify([this.#scope.profileKey, this.#scope.configIdentity, serverId, profile.origin]) + return this.#memory.get(serverId)?.key === key || Boolean(this.#paired?.has(serverId, key)) + } + + /** prototype-1236: an `opencode pair` token, kept across launches until expiry or 401. */ + async setPaired(serverId: string, token: string): Promise { + const key = this.key(serverId) + if (!this.#paired || typeof token !== "string" || !token.length || Buffer.byteLength(token, "utf8") > 16 * 1024) { + throw new CredentialOperationError("invalid_credentials") + } + this.#memory.delete(serverId) + this.#paired.set(serverId, key, token) + this.notify(serverId) + } + + /** A rejected credential (401) leaves the server waiting for a new link or password. */ + async rejected(serverId: string): Promise { + if (this.#closed) return + this.#paired?.delete(serverId) + if (this.#memory.delete(serverId)) this.notify(serverId) + } + + async set(serverId: string, value: string): Promise { + const key = this.key(serverId) + if (typeof value !== "string" || !value.length || Buffer.byteLength(value, "utf8") > 16 * 1024) { + throw new CredentialOperationError("invalid_credentials") + } + // prototype-1236 (R17): a manual password is kept across launches like a paired token; + // memory remains only for a backend without a private store. + if (this.#paired) { this.#memory.delete(serverId); this.#paired.setCredential(serverId, key, value) } + else this.#memory.set(serverId, { key, value }) + this.notify(serverId) + } + + /** Also usable after metadata removal; deletion/forget callers clear before reusing an ID. */ + async clear(serverId: string): Promise { + if (this.#closed) throw new CredentialOperationError("closed") + this.#memory.delete(serverId) + this.#paired?.delete(serverId) + this.notify(serverId) + } + + async dispose(): Promise { + this.#closed = true + this.#memory.clear() + this.notify() + this.#listeners.clear() + this.#unsubscribe() + } +} diff --git a/packages/server/src/opencode/servers/endpoint.test.ts b/packages/server/src/opencode/servers/endpoint.test.ts new file mode 100644 index 0000000000..465781cf26 --- /dev/null +++ b/packages/server/src/opencode/servers/endpoint.test.ts @@ -0,0 +1,45 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import { admitAddress, normalizeExplicitOrigin, resolveExplicitAddress } from "./endpoint" +import { assertLoopbackServiceUrl } from "../../workspaces/service-state" + +test("root origin normalization rejects URL hazards before normalization", () => { + assert.equal(normalizeExplicitOrigin("HTTPS://Example.COM:443/"), "https://example.com") + for (const value of ["ftp://localhost", "https://a/b", "https://a/..", "https://a/%2e", "https://a?", "https://a#", "https://a?x", "https://a#x", "https://u:p@a", "https://@a", "https://a\\b", " https://a", "https://*"]) { + assert.throws(() => normalizeExplicitOrigin(value), value) + } +}) + +test("IP classification covers private, loopback, mapped and forbidden ranges", () => { + for (const address of ["127.0.0.1", "127.2.3.4", "::1", "::ffff:127.0.0.1", "::ffff:7f00:1"]) { + assert.equal(admitAddress(address).loopback, true, address) + } + for (const address of ["10.0.0.1", "172.16.2.1", "192.168.1.1", "fd12::1", "fc00::1", "2606:4700::1111", "::ffff:192.168.1.1"]) { + assert.equal(admitAddress(address).loopback, false, address) + assert.doesNotThrow(() => normalizeExplicitOrigin(`https://${address.includes(":") ? `[${address}]` : address}`)) + assert.throws(() => normalizeExplicitOrigin(`http://${address.includes(":") ? `[${address}]` : address}`)) + } + for (const address of ["0.0.0.0", "0.1.2.3", "224.0.0.1", "255.255.255.255", "169.254.169.254", "100.100.100.200", "168.63.129.16", "::", "ff02::1", "fe80::1", "fec0::1", "fd00:ec2::254", "::ffff:169.254.169.254", "::ffff:a9fe:a9fe", "2002:7f00:1::", "64:ff9b::a9fe:a9fe"]) { + assert.throws(() => admitAddress(address), address) + } + assert.throws(() => normalizeExplicitOrigin("http://remote.example")) + assert.equal(normalizeExplicitOrigin("http://localhost:123/"), "http://localhost:123") + assert.throws(() => normalizeExplicitOrigin("http://0")) + assert.throws(() => normalizeExplicitOrigin("https://2852039166")) +}) + +test("DNS validates all answers and rechecks every dispatch", async () => { + let calls = 0 + const resolve = async () => [{ address: ++calls === 1 ? "192.168.1.1" : "169.254.169.254", family: 4 }] + assert.equal((await resolveExplicitAddress("https://test.example", resolve)).address, "192.168.1.1") + await assert.rejects(resolveExplicitAddress("https://test.example", resolve), { code: "forbidden_address" }) + await assert.rejects(resolveExplicitAddress("https://test.example", async () => [{ address: "127.0.0.1", family: 4 }, { address: "fe80::1", family: 6 }])) + await assert.rejects(resolveExplicitAddress("http://localhost", async () => [{ address: "10.0.0.1", family: 4 }]), { code: "https_required" }) + await assert.rejects(resolveExplicitAddress("https://test.example", async () => []), { code: "dns" }) +}) + +test("shared service loopback guard remains independent", () => { + assert.equal(assertLoopbackServiceUrl("http://0.0.0.0:12").hostname, "127.0.0.1") + for (const value of ["http://localhost", "http://127.0.0.1", "http://[::1]"]) assert.doesNotThrow(() => assertLoopbackServiceUrl(value)) + for (const value of ["https://example.com", "https://10.0.0.1", "https://192.168.0.1"]) assert.throws(() => assertLoopbackServiceUrl(value)) +}) diff --git a/packages/server/src/opencode/servers/endpoint.ts b/packages/server/src/opencode/servers/endpoint.ts new file mode 100644 index 0000000000..bc5c8215f9 --- /dev/null +++ b/packages/server/src/opencode/servers/endpoint.ts @@ -0,0 +1,21 @@ +import { lookup } from "node:dns/promises" +import { isIP } from "node:net" + +import { admitAddress, ExplicitEndpointError, normalizeExplicitOrigin } from "./origin" +export { admitAddress, ExplicitEndpointError, normalizeExplicitOrigin, type EndpointErrorCode } from "./origin" + +export type ResolveAddresses = (hostname: string) => Promise +export const resolveAddresses: ResolveAddresses = hostname => lookup(hostname, { all: true, verbatim: true }) + +/** Validate every answer and return the exact address the dialer must use. */ +export async function resolveExplicitAddress(origin: string, resolve: ResolveAddresses = resolveAddresses) { + const url = new URL(normalizeExplicitOrigin(origin)) + const hostname = url.hostname.replace(/^\[|\]$/g, "") + let answers: readonly { address: string; family: number }[] + try { answers = isIP(hostname) ? [{ address: hostname, family: isIP(hostname) }] : await resolve(hostname) } + catch { throw new ExplicitEndpointError("dns") } + if (!answers.length) throw new ExplicitEndpointError("dns") + const admitted = answers.map(answer => admitAddress(answer.address)) + if (url.protocol === "http:" && admitted.some(answer => !answer.loopback)) throw new ExplicitEndpointError("https_required") + return admitted[0]! +} diff --git a/packages/server/src/opencode/servers/folders.test.ts b/packages/server/src/opencode/servers/folders.test.ts new file mode 100644 index 0000000000..acacfb5af8 --- /dev/null +++ b/packages/server/src/opencode/servers/folders.test.ts @@ -0,0 +1,81 @@ +// prototype-1236: folder browsing on an explicit OpenCode server (R14). +import assert from "node:assert/strict" +import test from "node:test" +import Fastify from "fastify" +import { listServerFolders, parseServerFolderPath } from "./folders" +import { registerOpenCodeFolderRoutes } from "../../server/routes/opencode-folders" +import { ServerConnectionError } from "./connections" + +const native = (directory: string, data: Array<{ path: string; type: "file" | "directory" }>) => { + const calls: unknown[] = [] + return { calls, list: async (input?: unknown) => { calls.push(input); return { location: { directory }, data } } } +} + +test("lists only folders of an absolute path, named from native relative entries, with its parent", async () => { + const server = native("/home/me", [ + { path: "../../srv/app", type: "directory" }, { path: "../../srv/notes.txt", type: "file" }, + { path: "../../srv/.git", type: "directory" }, { path: "../../srv/app", type: "directory" }, + ]) + const answer = await listServerFolders(server.list, "/srv/") + assert.deepEqual(server.calls, [{ path: "/srv/" }]) + assert.deepEqual(answer.entries.map(entry => [entry.name, entry.path, entry.absolutePath]), [["app", "/srv/app", "/srv/app"], [".git", "/srv/.git", "/srv/.git"]]) + assert.deepEqual(answer.metadata, { scope: "unrestricted", currentPath: "/srv", parentPath: "/", rootPath: "/", + homePath: "/home/me", displayPath: "/srv", pathKind: "absolute" }) +}) + +test("opens the default location without a path, and stops at the root", async () => { + const home = native("/home/me", [{ path: "work", type: "directory" }]) + const opened = await listServerFolders(home.list, undefined) + assert.deepEqual(home.calls, [undefined]) + assert.equal(opened.metadata.currentPath, "/home/me") + assert.equal(opened.entries[0]?.path, "/home/me/work") + const root = await listServerFolders(native("/home/me", []).list, "/") + assert.equal(root.metadata.parentPath, undefined) + const drive = await listServerFolders(native("C:\\Users\\me", [{ path: "..\\..\\Projects", type: "directory" }]).list, "C:\\") + assert.equal(drive.metadata.parentPath, undefined) + assert.equal(drive.metadata.rootPath, "C:\\") + assert.equal(drive.entries[0]?.path, "C:\\Projects") +}) + +test("a server refusing a path outside its location is asked for that folder as a location", async () => { + const calls: unknown[] = [] + const list = async (input?: any) => { + calls.push(input) + if (input?.path) throw new Error("outside location") + return { location: { directory: input.location.directory }, data: [{ path: "api", type: "directory" as const }] } + } + const answer = await listServerFolders(list, "/srv") + assert.deepEqual(calls, [{ path: "/srv" }, { location: { directory: "/srv" } }]) + assert.equal(answer.entries[0]?.path, "/srv/api") +}) + +test("only absolute bounded paths are accepted", () => { + assert.equal(parseServerFolderPath(undefined), undefined) + assert.equal(parseServerFolderPath(""), undefined) + assert.equal(parseServerFolderPath("/srv"), "/srv") + assert.equal(parseServerFolderPath("D:/work"), "D:/work") + for (const value of ["relative", "../up", "~/home", "/a\0b", "x".repeat(5_000)]) assert.throws(() => parseServerFolderPath(value)) +}) + +test("the route lists through the server's shared connection and maps refusals to fixed codes", async t => { + const app = Fastify() + t.after(() => app.close()) + const connected: string[] = [] + const server = native("/home/me", [{ path: "app", type: "directory" }]) + registerOpenCodeFolderRoutes(app, { connections: () => ({ + connect: async (id: string) => { + connected.push(id) + if (id === "gone") throw new ServerConnectionError("unknown_server") + if (id === "offline") throw new ServerConnectionError("disconnected") + return { client: { file: { list: server.list } } } + }, + }) as never }) + const ok = await app.inject({ method: "GET", url: "/api/opencode-folders?serverId=oc-1&path=/home/me" }) + assert.equal(ok.statusCode, 200) + assert.deepEqual(ok.json().entries.map((entry: any) => entry.path), ["/home/me/app"]) + assert.equal((await app.inject({ method: "GET", url: "/api/opencode-folders?serverId=oc-1&path=relative" })).statusCode, 400) + assert.equal((await app.inject({ method: "GET", url: "/api/opencode-folders?serverId=local-shared" })).statusCode, 400) + assert.equal((await app.inject({ method: "GET", url: "/api/opencode-folders?serverId=gone" })).statusCode, 404) + assert.equal((await app.inject({ method: "GET", url: "/api/opencode-folders?serverId=offline" })).statusCode, 503) + assert.deepEqual(connected, ["oc-1", "gone", "offline"]) +}) diff --git a/packages/server/src/opencode/servers/folders.ts b/packages/server/src/opencode/servers/folders.ts new file mode 100644 index 0000000000..5a94a9e734 --- /dev/null +++ b/packages/server/src/opencode/servers/folders.ts @@ -0,0 +1,82 @@ +// prototype-1236: folder browsing on an explicit OpenCode server, through its single shared connection. +import type { FileSystemEntry, FileSystemListResponse } from "../../api-types" + +/** Native `file.list`: entries are relative to the location answered (the server's default one). */ +type NativeList = (input?: { path?: string; location?: { directory: string } }, options?: { signal?: AbortSignal }) => Promise<{ + location: { directory: string } + data: ReadonlyArray<{ path: string; type: "file" | "directory" }> +}> + +const ABSOLUTE = /^(?:\/|[A-Za-z]:[\\/])/ +const MAX_PATH = 4_096 +const MAX_ENTRIES = 2_000 + +export class ServerFolderPathError extends Error { + constructor() { super("invalid_path"); this.name = "ServerFolderPathError" } +} + +/** An absolute folder on the server, or undefined for its default location. */ +export function parseServerFolderPath(value: unknown): string | undefined { + if (value === undefined || value === "") return undefined + if (typeof value !== "string" || value.length > MAX_PATH || value.includes("\0") || !ABSOLUTE.test(value)) throw new ServerFolderPathError() + return value +} + +function separatorOf(path: string): "/" | "\\" { + return /^[A-Za-z]:/.test(path) && !path.includes("/") ? "\\" : "/" +} + +function trimTrailing(path: string): string { + const root = /^(?:[A-Za-z]:[\\/]|\/)$/.test(path) + return root ? path : path.replace(/[\\/]+$/, "") +} + +function parentOf(path: string): string | undefined { + const current = trimTrailing(path), separator = separatorOf(current) + const index = Math.max(current.lastIndexOf("/"), current.lastIndexOf("\\")) + if (index < 0 || current === "/" || /^[A-Za-z]:[\\/]$/.test(current)) return undefined + const parent = current.slice(0, index) + return parent === "" ? "/" : /^[A-Za-z]:$/.test(parent) ? `${parent}${separator}` : parent +} + +function rootOf(path: string): string { + const drive = path.match(/^([A-Za-z]:)[\\/]/) + return drive ? `${drive[1]}${separatorOf(path)}` : "/" +} + +function join(base: string, name: string): string { + const separator = separatorOf(base) + return /[\\/]$/.test(base) ? `${base}${name}` : `${base}${separator}${name}` +} + +/** Lists only folders, in the listing shape the folder browser already reads. */ +export async function listServerFolders(list: NativeList, path: string | undefined, signal?: AbortSignal): Promise { + // An absolute path is read from the default location; a server refusing paths outside it + // is asked for that folder as its own location instead. + let answer: Awaited> + try { answer = await list(path === undefined ? undefined : { path }, { signal }) } + catch (error) { + if (path === undefined || signal?.aborted) throw error + answer = await list({ location: { directory: path } }, { signal }) + } + const home = answer.location.directory + const current = trimTrailing(path ?? home) + const seen = new Set() + const entries: FileSystemEntry[] = [] + for (const entry of answer.data) { + if (entry.type !== "directory" || entries.length >= MAX_ENTRIES) continue + const name = entry.path.split(/[\\/]/).filter(Boolean).at(-1) + if (!name || name === "." || name === ".." || seen.has(name)) continue + seen.add(name) + const absolute = join(current, name) + entries.push({ name, path: absolute, absolutePath: absolute, type: "directory" }) + } + const parentPath = parentOf(current) + return { + entries, + metadata: { + scope: "unrestricted", currentPath: current, ...(parentPath ? { parentPath } : {}), + rootPath: rootOf(current), homePath: home, displayPath: current, pathKind: "absolute", + }, + } +} diff --git a/packages/server/src/opencode/servers/origin.ts b/packages/server/src/opencode/servers/origin.ts new file mode 100644 index 0000000000..0f6c7d13a1 --- /dev/null +++ b/packages/server/src/opencode/servers/origin.ts @@ -0,0 +1,63 @@ +import { isIP } from "node:net" + +export type EndpointErrorCode = "invalid_origin" | "forbidden_address" | "https_required" | "dns" | "network" | "tls" | "redirect" | "timeout" | "response_limit" | "probe_path" | "custom_ca_unsupported" + +/** Diagnostics contain only a stable code, never a URL, credential or upstream error. */ +export class ExplicitEndpointError extends Error { + constructor(readonly code: EndpointErrorCode) { super(code); this.name = "ExplicitEndpointError" } +} + +function ipv4(address: string): number[] | undefined { + if (isIP(address) === 4) return address.split(".").map(Number) + if (isIP(address) !== 6) return + const parts = address.split("::") + const left = parts[0] ? parts[0].split(":") : [] + const right = parts[1] ? parts[1].split(":") : [] + const words = [...left, ...Array(8 - left.length - right.length).fill("0"), ...right].map(word => parseInt(word, 16)) + if (words.slice(0, 5).every(word => word === 0) && words[5] === 0xffff) { + return [words[6]! >> 8, words[6]! & 255, words[7]! >> 8, words[7]! & 255] + } +} + +export function admitAddress(input: string): { address: string; family: 4 | 6; loopback: boolean } { + if (!isIP(input)) throw new ExplicitEndpointError("forbidden_address") + const address = isIP(input) === 6 ? new URL(`http://[${input}]/`).hostname.slice(1, -1) : input + const v4 = ipv4(address) + let loopback = false + if (v4) { + const [a, b, c, d] = v4 as [number, number, number, number] + loopback = a === 127 + if (a === 0 || a >= 224 || (a === 169 && b === 254) + || (a === 100 && b >= 64 && b <= 127) + || (a === 168 && b === 63 && c === 129 && d === 16)) throw new ExplicitEndpointError("forbidden_address") + } else { + loopback = address === "::1" + // Global unicast and private ULA only; transition/link-local/site-local ranges fail closed. + const first = parseInt(address.split(":")[0]!, 16) + if (!loopback && !((first >= 0x2000 && first <= 0x3fff) || (first >= 0xfc00 && first <= 0xfdff))) { + throw new ExplicitEndpointError("forbidden_address") + } + if (address === "fd00:ec2::254" || address.startsWith("2002:") || address.startsWith("2001:0:") || address.startsWith("2001::")) throw new ExplicitEndpointError("forbidden_address") + } + return { address, family: isIP(address) as 4 | 6, loopback } +} + +/** Synchronous origin validation shared by registry metadata and network admission. */ +export function normalizeExplicitOrigin(value: string): string { + let url: URL + try { + // Inspect the supplied syntax before WHATWG normalization can erase dot paths or empty delimiters. + if (!/^https?:\/\/[^/?#\\\s]+\/?$/i.test(value)) throw new Error() + url = new URL(value) + if (url.username || url.password || value.includes("@") || url.pathname !== "/" || url.search || url.hash) throw new Error() + } catch { throw new ExplicitEndpointError("invalid_origin") } + const hostname = url.hostname.replace(/^\[|\]$/g, "") + if (isIP(hostname)) { + const admitted = admitAddress(hostname) + if (url.protocol === "http:" && !admitted.loopback) throw new ExplicitEndpointError("https_required") + } else { + if (hostname === "*" || hostname.includes("*") || !hostname) throw new ExplicitEndpointError("invalid_origin") + if (url.protocol === "http:" && hostname !== "localhost") throw new ExplicitEndpointError("https_required") + } + return url.origin +} diff --git a/packages/server/src/opencode/servers/pairing-store.ts b/packages/server/src/opencode/servers/pairing-store.ts new file mode 100644 index 0000000000..e65eabada4 --- /dev/null +++ b/packages/server/src/opencode/servers/pairing-store.ts @@ -0,0 +1,79 @@ +import fs from "node:fs" +import path from "node:path" + +// prototype-1236: an `opencode pair` token or a manually entered password survives restarts +// like a paired CodeNomad server's device cookie: a token until its 30-day expiry or a 401, +// a password until a 401 or removal. Backend-only, mode 0600. Never logged, never returned +// to a browser, never written to the configuration. +const TOKEN_LIFETIME_MS = 30 * 24 * 60 * 60 * 1000 +type TokenEntry = { key: string; token: string; expiresAt: number } +type PasswordEntry = { key: string; credential: string } +type Entry = TokenEntry | PasswordEntry + +function validEntry(entry: unknown): entry is Entry { + if (!entry || typeof entry !== "object") return false + const value = entry as Record + if (typeof value.key !== "string") return false + if (typeof value.token === "string") return typeof value.expiresAt === "number" + return typeof value.credential === "string" +} + +export class PairingTokenStore { + #entries = new Map() + + constructor(private readonly filePath: string, private readonly now: () => number = Date.now) { + try { + const value = JSON.parse(fs.readFileSync(filePath, "utf8")) as { pairings?: Record } + for (const [id, entry] of Object.entries(value.pairings ?? {})) if (validEntry(entry)) this.#entries.set(id, entry) + } catch { /* No pairing yet, or an unreadable file: re-pairing replaces it. */ } + } + + /** The connection credential (`{ username, password }` JSON) for this exact server key. */ + read(serverId: string, key: string): string | null { + const entry = this.#entries.get(serverId) + if (!entry) return null + if (entry.key !== key || ("token" in entry && entry.expiresAt <= this.now())) { this.delete(serverId); return null } + return "token" in entry ? pairedCredential(entry.token) : entry.credential + } + + has(serverId: string, key: string): boolean { + const entry = this.#entries.get(serverId) + return entry?.key === key && (!("token" in entry) || entry.expiresAt > this.now()) + } + + set(serverId: string, key: string, token: string): void { + this.#entries.set(serverId, { key, token, expiresAt: tokenExpiry(token, this.now()) }) + this.persist() + } + + /** A manual `{ username, password }` credential, kept until a 401 or removal. */ + setCredential(serverId: string, key: string, credential: string): void { + this.#entries.set(serverId, { key, credential }) + this.persist() + } + + delete(serverId: string): void { + if (this.#entries.delete(serverId)) this.persist() + } + + private persist(): void { + fs.mkdirSync(path.dirname(this.filePath), { recursive: true }) + const temporary = `${this.filePath}.${process.pid}.tmp` + fs.writeFileSync(temporary, `${JSON.stringify({ pairings: Object.fromEntries(this.#entries) })}\n`, { mode: 0o600 }) + fs.renameSync(temporary, this.filePath) + } +} + +/** OpenCode accepts a paired token wherever its password is accepted, as Basic `opencode:`. */ +function pairedCredential(token: string): string { + return JSON.stringify({ username: "opencode", password: token }) +} + +/** OpenCode tokens are `.`; fall back to its fixed 30-day lifetime. */ +function tokenExpiry(token: string, now: number): number { + const prefix = Number(token.split(".")[0]) + if (!Number.isFinite(prefix) || prefix <= 0) return now + TOKEN_LIFETIME_MS + const ms = prefix < 1e12 ? prefix * 1000 : prefix + // An unrecognized prefix never rejects a token early; the server's 401 decides. + return ms > now ? Math.min(ms, now + TOKEN_LIFETIME_MS) : now + TOKEN_LIFETIME_MS +} diff --git a/packages/server/src/opencode/servers/pairing.ts b/packages/server/src/opencode/servers/pairing.ts new file mode 100644 index 0000000000..40560d6545 --- /dev/null +++ b/packages/server/src/opencode/servers/pairing.ts @@ -0,0 +1,50 @@ +import { boundedResponseFetch } from "../bounded-response-fetch" +import { ExplicitEndpointError, normalizeExplicitOrigin, type ResolveAddresses } from "./endpoint" +import { createExplicitTransport } from "./transport" +import { SERVER_CONNECTION_LIMITS } from "./types" + +// prototype-1236: `opencode pair` / `opencode pair --remote` print `/auth/connect/`. +const CONNECT_PATH = /^\/auth\/connect\/([A-Za-z0-9_-]{1,128})$/ + +export type PairingErrorCode = "invalid_link" | "pairing_expired" | "unreachable" | "https_required" | "forbidden_address" +export class OpenCodePairingError extends Error { + constructor(readonly code: PairingErrorCode) { super(code); this.name = "OpenCodePairingError" } +} + +/** Null when the text is not an OpenCode pairing link; throws when it is one we refuse. */ +export function parseOpenCodePairingLink(input: string): { origin: string; code: string } | null { + let url: URL + try { url = new URL(input.trim()) } catch { return null } + const match = CONNECT_PATH.exec(url.pathname) + if (!match || (url.protocol !== "http:" && url.protocol !== "https:")) return null + if (url.search || url.hash || url.username || url.password) throw new OpenCodePairingError("invalid_link") + try { return { origin: normalizeExplicitOrigin(url.origin), code: match[1]! } } + catch (error) { throw endpointFailure(error) } +} + +/** One GET, JSON only, no redirect followed, through the verified explicit transport. */ +export async function redeemOpenCodePairing(link: { origin: string; code: string }, signal?: AbortSignal, + resolve?: ResolveAddresses): Promise { + const deadline = AbortSignal.any([AbortSignal.timeout(SERVER_CONNECTION_LIMITS.probeTimeoutMs), ...(signal ? [signal] : [])]) + const transport = createExplicitTransport({ origin: link.origin, signal: deadline }, resolve) + let response: Response + try { + response = await boundedResponseFetch(transport.fetch, deadline, () => {}, 64 * 1024)( + new URL(`/auth/connect/${link.code}`, link.origin), { method: "GET", headers: { accept: "application/json" }, signal: deadline }) + } catch (error) { throw endpointFailure(error) } + // A spent or expired code answers 401; never retry it elsewhere. + if (response.status === 401 || response.status === 404) throw new OpenCodePairingError("pairing_expired") + if (!response.ok) throw new OpenCodePairingError("unreachable") + let token: unknown + try { token = (await response.json() as { token?: unknown }).token } catch { throw new OpenCodePairingError("unreachable") } + if (typeof token !== "string" || !token || token.length > 8_192 || /\s/.test(token)) throw new OpenCodePairingError("unreachable") + return token +} + +function endpointFailure(error: unknown): OpenCodePairingError { + if (error instanceof OpenCodePairingError) return error + const code = error instanceof ExplicitEndpointError ? error.code : undefined + if (code === "https_required" || code === "forbidden_address") return new OpenCodePairingError(code) + if (code === "invalid_origin") return new OpenCodePairingError("invalid_link") + return new OpenCodePairingError("unreachable") +} diff --git a/packages/server/src/opencode/servers/probe.test.ts b/packages/server/src/opencode/servers/probe.test.ts new file mode 100644 index 0000000000..713b9b0592 --- /dev/null +++ b/packages/server/src/opencode/servers/probe.test.ts @@ -0,0 +1,219 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { createServer, type ServerResponse } from "node:http" +import { once } from "node:events" +import { gzipSync } from "node:zlib" +import { setTimeout as delay } from "node:timers/promises" +import { OpenCodeServerConnections } from "./connections" +import { OpenCodeServerCredentials } from "./credentials" +import { OpenCodeServerRegistry } from "./registry" +import { explicitContractFixture } from "../compatibility/contract-fixture" +import { boundedResponseFetch } from "../bounded-response-fetch" +import type { ResolveAddresses } from "./endpoint" +import { Agent } from "undici" +import { probeExplicitCandidate } from "./probe" + +async function fixture(t: test.TestContext, handler?: (path: string, response: ServerResponse) => void, resolveAddresses?: ResolveAddresses) { + const calls: string[] = [], headers: (string | undefined)[] = [] + const server = createServer((request, response) => { + calls.push(`${request.method} ${request.url}`); headers.push(request.headers.authorization) + if (handler) return handler(request.url!, response) + response.setHeader("content-type", "application/json") + response.end(JSON.stringify(request.url === "/openapi.json" ? explicitContractFixture() : { version: "99.0.0", pid: 999, urls: ["private"], paths: { tmp: "private" } })) + }) + server.listen(0, "127.0.0.1"); await once(server, "listening") + const origin = `http://127.0.0.1:${(server.address() as { port: number }).port}` + let writes = 0 + const registry = new OpenCodeServerRegistry(() => [], () => { writes++ }) + const credentials = new OpenCodeServerCredentials({ profileKey: "test", configIdentity: "test" }, registry) + const owner = new OpenCodeServerConnections({ registry, credentials, resolveAddresses, local: { + acquire: async () => { throw new Error("local acquire forbidden") }, existing: () => undefined, + invalidate: () => { throw new Error("local invalidation forbidden") }, + } }) + t.after(async () => { await owner.dispose(); server.closeAllConnections(); await new Promise(resolve => server.close(() => resolve())) }) + return { origin, owner, calls, headers, writes: () => writes, credentials } +} + +test("unregistered candidate negotiates and observes version without registry, credentials, slots or subscriptions", async t => { + const f = await fixture(t) + f.credentials.set = async () => { assert.fail("candidate must never store credentials") } + const admitted: string[][] = [] + f.owner.observeAdmitted(ids => admitted.push([...ids])) + const result = await f.owner.probeCandidate({ origin: f.origin, credentials: { username: "candidate-user", password: "candidate-secret" } }) + assert.equal(result.version, "99.0.0") + assert.equal(result.capabilities.chat.state, "available") + assert.equal(result.capabilities.missions.state, "unavailable") + assert.equal(result.diagnostic, null) + assert.ok(Number.isFinite(Date.parse(result.checkedAt))) + assert.deepEqual(f.calls, ["GET /openapi.json", "GET /api/info"]) + assert.ok(f.headers.every(value => value === `Basic ${Buffer.from("candidate-user:candidate-secret").toString("base64")}`)) + assert.deepEqual(admitted, [[]]); assert.equal(f.owner.activeExplicitTargets, 0); assert.equal(f.writes(), 0) + assert.doesNotMatch(JSON.stringify(result), /candidate-user|candidate-secret|private|999/) +}) + +test("candidate and registered probes share one lane; abort frees it before old cleanup", async t => { + let arrived!: () => void + const ready = new Promise(resolve => { arrived = resolve }) + const f = await fixture(t, (_path, response) => { response.write("{"); arrived() }) + const cancel = new AbortController() + const pending = f.owner.probeCandidate({ origin: f.origin }, cancel.signal), rejected = assert.rejects(pending) + await ready + await assert.rejects(f.owner.probe("unknown"), { code: "probe_busy" }) + await assert.rejects(f.owner.probeCandidate({ origin: f.origin }), { code: "probe_busy" }) + cancel.abort(); await rejected + assert.equal(f.owner.activeExplicitTargets, 0) + const again = new AbortController() + const second = f.owner.probeCandidate({ origin: f.origin }, again.signal), secondRejected = assert.rejects(second) + await delay(20) + await assert.rejects(f.owner.probeCandidate({ origin: f.origin }), { code: "probe_busy" }) + again.abort(); await secondRejected +}) + +test("one real five-second budget spans contract headers/body and canonical info", async t => { + let resolutions = 0 + const f = await fixture(t, (path, response) => { + if (path === "/openapi.json") { + const timer = setTimeout(() => response.end(JSON.stringify(explicitContractFixture())), 2_600) + response.on("close", () => clearTimeout(timer)) + } else { response.writeHead(200); response.write('{"version":') } + }, async () => { resolutions++; await delay(900); return [{ address: "127.0.0.1", family: 4 }] }) + const started = performance.now() + await assert.rejects(f.owner.probeCandidate({ origin: f.origin.replace("127.0.0.1", "localhost") }), { code: "timeout" }) + const elapsed = performance.now() - started + assert.ok(elapsed >= 4_900 && elapsed < 6_000, `${elapsed}ms`) + assert.deepEqual(f.calls, ["GET /openapi.json", "GET /api/info"]) + assert.equal(resolutions, 2) + assert.equal(f.owner.activeExplicitTargets, 0) +}) + +for (const status of [200, 401, 500]) for (const extra of [0, 1]) { + test(`decoded probe body ${status}, eight MiB ${extra ? "+1 rejected" : "exact accepted"}`, async t => { + const document = JSON.stringify(explicitContractFixture()) + const bytes = Buffer.from(document + " ".repeat(8 * 1024 * 1024 + extra - Buffer.byteLength(document))) + const f = await fixture(t, (path, response) => { + if (path === "/api/info") { response.setHeader("content-type", "application/json"); response.end('{"version":"99.0.0","pid":1,"urls":[],"paths":{"tmp":"private"}}'); return } + response.writeHead(status, { "content-type": "application/json", "content-encoding": "gzip", "www-authenticate": "private" }) + response.end(gzipSync(bytes)) + }) + if (extra) await assert.rejects(f.owner.probeCandidate({ origin: f.origin }), { code: "response_limit" }) + else if (status === 401) await assert.rejects(f.owner.probeCandidate({ origin: f.origin }), { code: "auth" }) + else if (status === 500) await assert.rejects(f.owner.probeCandidate({ origin: f.origin }), { code: "network" }) + else assert.equal((await f.owner.probeCandidate({ origin: f.origin })).version, "99.0.0") + assert.equal(f.owner.activeExplicitTargets, 0) + }) +} + +test("bounded response cancellation never waits for held/rejected cleanup and releases its reader", async () => { + for (const reject of [false, true]) { + const controller = new AbortController() + let cancelled = 0 + const body = new ReadableStream({ cancel() { cancelled++; return reject ? Promise.reject(new Error("private")) : new Promise(() => {}) } }) + const response = new Response(body) + const fetcher = boundedResponseFetch(async () => response, controller.signal, () => {}, 1) + const pending = fetcher("http://fixture.test"), rejected = assert.rejects(pending) + await delay(1); controller.abort(); await rejected + assert.equal(cancelled, 1); assert.equal(body.locked, false) + } +}) + +test("invalid candidate syntax and credentials fail before DNS; disposal cancels pending DNS and late completion", async t => { + let queries = 0, finish!: () => void + const pendingDNS = new Promise(resolve => { finish = resolve }) + const f = await fixture(t, undefined, async () => { queries++; await pendingDNS; return [{ address: "127.0.0.1", family: 4 }] }) + for (const origin of ["https://user:password@localhost", "https://localhost/sub", "https://localhost?", "https://localhost#", "malformed"]) { + await assert.rejects(f.owner.probeCandidate({ origin }), { code: "invalid_origin" }) + } + await assert.rejects(f.owner.probeCandidate({ origin: f.origin, credentials: { username: "invalid:name", password: "sentinel" } }), { code: "invalid_credentials" }) + assert.equal(queries, 0) + const pending = f.owner.probeCandidate({ origin: f.origin.replace("127.0.0.1", "localhost") }), rejected = assert.rejects(pending) + await delay(1); assert.equal(queries, 1) + await f.owner.dispose(); await rejected + finish(); await delay(1) + assert.equal(f.calls.length, 0); assert.equal(f.writes(), 0) + await assert.rejects(f.owner.probeCandidate({ origin: f.origin }), { code: "closed" }) +}) + +test("canonical-info errors remain bounded before SDK parsing and cannot hide overflow", async t => { + const f = await fixture(t, (path, response) => { + response.setHeader("content-type", "application/json") + if (path === "/openapi.json") response.end(JSON.stringify(explicitContractFixture())) + else { response.writeHead(500, { "content-encoding": "gzip" }); response.end(gzipSync(Buffer.alloc(8 * 1024 * 1024 + 1, 97))) } + }) + await assert.rejects(f.owner.probeCandidate({ origin: f.origin }), { code: "response_limit", phase: "info" }) +}) + +test("bounded-response overflow and late fetch settlement release readers without awaiting cleanup", async () => { + let cancelled = 0 + const body = new ReadableStream({ start(controller) { controller.enqueue(new Uint8Array(2)) }, cancel() { cancelled++; return new Promise(() => {}) } }) + const signal = new AbortController() + await assert.rejects(boundedResponseFetch(async () => new Response(body), signal.signal, () => {}, 1)("http://fixture.test"), { code: "response_limit" }) + assert.equal(cancelled, 1); assert.equal(body.locked, false) + let finish!: (value: Response) => void + const lateBody = new ReadableStream({ cancel() { cancelled++; return Promise.reject(new Error("private")) } }) + const fetcher = boundedResponseFetch(() => new Promise(resolve => { finish = resolve }), signal.signal, () => {}, 1) + const pending = fetcher("http://fixture.test"), rejected = assert.rejects(pending) + signal.abort(); await rejected + finish(new Response(lateBody)); await delay(1) + assert.equal(cancelled, 2); assert.equal(lateBody.locked, false) +}) + +test("held dispatcher cleanup cannot hold the single probe lane or clear its replacement", async t => { + const original = Agent.prototype.destroy + let cleanups = 0 + t.mock.method(Agent.prototype, "destroy", function (this: Agent) { + cleanups++ + original.call(this, null, () => {}) + return new Promise(() => {}) + }) + const f = await fixture(t, (_path, response) => { response.writeHead(302, { location: "https://private.invalid" }); response.end() }) + await assert.rejects(f.owner.probeCandidate({ origin: f.origin }), { code: "redirect" }) + await assert.rejects(f.owner.probeCandidate({ origin: f.origin }), { code: "redirect" }) + assert.equal(f.calls.length, 2); assert.ok(cleanups >= 2) +}) + +test("unavailable/custom info stays explicitly unknown and never echoes upstream identity prose", async t => { + let version = "candidate-secret" + const f = await fixture(t, (path, response) => { + response.setHeader("content-type", "application/json") + response.end(JSON.stringify(path === "/openapi.json" ? explicitContractFixture() : { version, pid: 999, urls: ["private"], paths: { tmp: "private" } })) + }) + const result = await f.owner.probeCandidate({ origin: f.origin, credentials: { username: "candidate-user", password: "candidate-secret" } }) + assert.equal(result.version, null) + assert.deepEqual(result.diagnostic, { code: "info_unavailable", phase: "info" }) + assert.equal(result.capabilities.chat.state, "available") + assert.doesNotMatch(JSON.stringify(result), /candidate-secret|candidate-user|private|999/) + version = "99.0.0" + const numericEcho = await f.owner.probeCandidate({ origin: f.origin, credentials: { username: "candidate-user", password: version } }) + assert.equal(numericEcho.version, null) + assert.doesNotMatch(JSON.stringify(numericEcho), /99\.0\.0/) +}) + +for (const depth of [2, 3]) test(`protected probe owns HTTP response at headers/admission depth ${depth}`, async t => { + let hold = true + const f = await fixture(t, (path, response) => { + response.setHeader("content-type", "application/json") + if (hold) { response.write("{"); return } + response.end(JSON.stringify(path === "/openapi.json" ? explicitContractFixture() : { version: "99.0.0", pid: 1, urls: [], paths: { tmp: "owned" } })) + }) + const abort = new AbortController(), NativeResponse = Response, cancel = ReadableStream.prototype.cancel + let captured: ReadableStream | undefined, cancellations = 0 + const schedule = (remaining: number) => queueMicrotask(() => remaining > 1 ? schedule(remaining - 1) : abort.abort()) + t.mock.method(ReadableStream.prototype, "cancel", function (this: ReadableStream, reason?: unknown) { + if (this === captured) cancellations++ + return cancel.call(this, reason) + }) + // Observe the real protected transport's Response receipt, retaining its native body. + t.mock.method(globalThis, "Response", class extends NativeResponse { + constructor(...args: ConstructorParameters) { + super(...args) + if (!captured && args[0] instanceof ReadableStream) { captured = args[0]; schedule(depth) } + } + }) + await assert.rejects(probeExplicitCandidate({ origin: f.origin }, abort.signal, () => abort.signal.throwIfAborted())) + await new Promise(resolve => setImmediate(resolve)) + assert.equal(cancellations, 1); assert.equal(captured?.locked, false) + assert.deepEqual(f.calls, ["GET /openapi.json"]) + t.mock.restoreAll(); hold = false + assert.equal((await f.owner.probeCandidate({ origin: f.origin })).version, "99.0.0") + assert.equal(f.owner.activeExplicitTargets, 0); assert.equal(f.writes(), 0) +}) diff --git a/packages/server/src/opencode/servers/probe.ts b/packages/server/src/opencode/servers/probe.ts new file mode 100644 index 0000000000..2f047d3e8a --- /dev/null +++ b/packages/server/src/opencode/servers/probe.ts @@ -0,0 +1,85 @@ +import { OpenCode } from "@opencode/client" +import { z } from "zod" +import { boundedResponseFetch, BoundedResponseError } from "../bounded-response-fetch" +import { ExplicitContractError, negotiateRuntime } from "../compatibility/negotiate" +import { initialServerCapabilities, type ServerCapabilities } from "./capabilities" +import { ExplicitEndpointError, normalizeExplicitOrigin, type ResolveAddresses } from "./endpoint" +import { createExplicitTransport } from "./transport" +import { SERVER_CONNECTION_LIMITS } from "./types" + +const candidateSchema = z.object({ + origin: z.string().max(2_048), + credentials: z.object({ username: z.string().max(8_192).refine(value => !value.includes(":")), password: z.string().max(8_192) }).strict().optional(), +}).strict().refine(value => !value.credentials || Buffer.byteLength(JSON.stringify(value.credentials), "utf8") <= 16 * 1024) +export type ProbeCandidate = z.infer +export type ProbePhase = "validation" | "credentials" | "contract" | "info" | "operation" +export type ProbeCode = "invalid_origin" | "invalid_credentials" | "needs_credentials" | "missing_contract" | "auth" + | "forbidden_address" | "https_required" | "dns" | "network" | "tls" | "redirect" | "timeout" | "response_limit" +export class ServerProbeError extends Error { + constructor(readonly code: ProbeCode, readonly phase: ProbePhase, readonly capabilities?: ServerCapabilities["features"]) { super(code); this.name = "ServerProbeError" } +} +export interface ServerProbeResult { + version: string | null + capabilities: ServerCapabilities["features"] + checkedAt: string + diagnostic: { code: "info_unavailable"; phase: "info" } | null +} + +/** Validate before DNS and keep the candidate outside registry/credential owners. */ +export function parseProbeCandidate(value: unknown): ProbeCandidate { + const parsed = candidateSchema.safeParse(value) + if (!parsed.success) throw new ServerProbeError("invalid_credentials", "validation") + return { ...parsed.data, origin: normalizeExplicitOrigin(parsed.data.origin) } +} + +/** Only consumed read-only contracts and canonical info; no functional/location discovery. */ +export async function probeExplicitCandidate(candidate: ProbeCandidate, signal: AbortSignal, current: () => void, + resolve?: ResolveAddresses): Promise { + let phase: ProbePhase = "contract" + let transportFailure: unknown + let capabilities: ServerCapabilities["features"] | undefined + try { + const transport = createExplicitTransport({ ...candidate, signal }, resolve) + const bounded = boundedResponseFetch(transport.fetch, signal, current, SERVER_CONNECTION_LIMITS.probeMaxBytes) + const fetch: typeof globalThis.fetch = async (input, init) => { + transportFailure = undefined + try { + const response = await bounded(input, init) + current() + if (response.status === 401 || response.status === 403) throw new ServerProbeError("auth", phase) + return response + } catch (error) { transportFailure = error; throw error } + } + await negotiateRuntime({ url: candidate.origin }, fetch, signal, "explicit-e1") + current() + capabilities = initialServerCapabilities({ kind: "explicit", id: "candidate", label: "candidate", origin: candidate.origin }, 0).features + for (const value of Object.values(capabilities)) if (value.state === "unknown") { + value.state = "available"; value.reason.code = "contractVerified"; value.evidence = "nativeContract" + } + phase = "info" + let version: string | null = null, diagnostic: ServerProbeResult["diagnostic"] = null + try { + const info = await OpenCode.make({ baseUrl: candidate.origin, fetch }).server.info({ signal }) + current() + // Unstructured/custom identity strings stay unavailable, never echoing upstream prose. + if (typeof info.version === "string" && /^\d{1,8}\.\d{1,8}\.\d{1,8}$/.test(info.version) + && !Object.values(candidate.credentials ?? {}).some(value => value.length > 0 && info.version.includes(value))) version = info.version + else diagnostic = { code: "info_unavailable", phase } + } catch (error) { + current() + // The official client wraps dispatch failures; retain only our own boundary error. + if (transportFailure) throw transportFailure + if (error instanceof ServerProbeError || error instanceof BoundedResponseError || error instanceof ExplicitEndpointError) throw error + diagnostic = { code: "info_unavailable", phase } + } + current() + return { version, capabilities, checkedAt: new Date().toISOString(), diagnostic } + } catch (error) { + if (error instanceof ServerProbeError) throw new ServerProbeError(error.code, error.phase, capabilities) + if (signal.aborted) throw signal.reason + if (error instanceof ExplicitContractError) throw new ServerProbeError("missing_contract", phase) + if (error instanceof BoundedResponseError) throw new ServerProbeError("response_limit", phase, capabilities) + if (error instanceof ExplicitEndpointError) throw new ServerProbeError(error.code === "probe_path" || error.code === "custom_ca_unsupported" ? "network" : error.code, phase, capabilities) + throw new ServerProbeError("network", phase, capabilities) + } +} diff --git a/packages/server/src/opencode/servers/registry.test.ts b/packages/server/src/opencode/servers/registry.test.ts new file mode 100644 index 0000000000..bf76766544 --- /dev/null +++ b/packages/server/src/opencode/servers/registry.test.ts @@ -0,0 +1,104 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { ConfigYamlSchema, OpenCodeServerProfileSchema, OpenCodeServersSchema } from "../../config/schema" +import { OpenCodeServerRegistry, parseProjectExecutionBinding, summarizeOpenCodeServers } from "./registry" +import { initialServerCapabilities, SERVER_CAPABILITY_NAMES } from "./capabilities" +import { SERVER_CONNECTION_LIMITS } from "./types" +import { normalizeExplicitOrigin } from "./endpoint" + +const explicit = { kind: "explicit", id: "target-A", label: "Isolated", origin: "https://example.test" } as const + +test("legacy metadata defaults to local without writing; missing bindings remain repairable and paths opaque", () => { + const registry = new OpenCodeServerRegistry(() => undefined, () => assert.fail("implicit migration must not persist")) + assert.deepEqual(registry.list(), [{ id: "local-shared", kind: "local-shared" }]) + assert.deepEqual(parseProjectExecutionBinding({ directory: "/Workspace/../MixedCase" }), + { serverId: "local-shared", directory: "/Workspace/../MixedCase" }) + const binding = parseProjectExecutionBinding({ serverId: "missing-server", directory: "c:\\MixedCase\\app" }) + assert.equal(binding.directory, "c:\\MixedCase\\app") + assert.equal(registry.get(binding.serverId), undefined) + assert.equal(ConfigYamlSchema.safeParse({}).success, true) + assert.throws(() => new OpenCodeServerRegistry(() => null, () => {}).list()) +}) + +test("registry rejects duplicate IDs, invalid shapes, embedded credentials and non-root/insecure origins before writing", () => { + let stored: unknown + let writes = 0 + const registry = new OpenCodeServerRegistry(() => stored, value => { stored = value; writes++ }) + registry.replace([explicit]) + assert.equal(registry.get("target-A")?.kind, "explicit") + assert.equal(registry.list()[0]?.kind, "local-shared") + for (const value of [null, {}, [explicit, explicit], [{ ...explicit, id: "local-shared" }], + [{ ...explicit, kind: "local-shared" }], [{ ...explicit, password: "sentinel" }], + [{ ...explicit, credentialMode: "file" }], [{ ...explicit, id: "../bad" }], + ...["http://example.test", "https://user:secret@example.test", "https://example.test/path", "https://example.test?secret=x", + "https://example.test/#secret", "file:///root", "invalid"].map(origin => [{ ...explicit, origin }]), + ]) assert.throws(() => registry.replace(value)) + assert.equal(writes, 1) + assert.equal(OpenCodeServersSchema.safeParse([{ ...explicit, origin: "http://127.0.0.1:4096" }]).success, true) + assert.equal(OpenCodeServersSchema.safeParse([{ ...explicit, origin: "http://[::1]:4096" }]).success, true) + assert.throws(() => parseProjectExecutionBinding({ serverId: null, directory: "/app" })) + assert.throws(() => parseProjectExecutionBinding({ directory: "bad\0path" })) +}) + +test("development metadata discards credential modes/references while preserving server identity", () => { + for (const credentialMode of ["keychain", "memory"]) { + const legacy = { ...explicit, credentialMode, credentialRef: "private-reference" } + assert.deepEqual(OpenCodeServerProfileSchema.parse(legacy), explicit) + const registry = new OpenCodeServerRegistry(() => [legacy], () => assert.fail("read must not persist")) + assert.deepEqual(registry.get(explicit.id), explicit) + } +}) + +test("admitted normalized origins round-trip through the registry including mapped loopback", () => { + const mapped = normalizeExplicitOrigin("http://[::ffff:127.0.0.1]:1234") + assert.equal(mapped, "http://[::ffff:7f00:1]:1234") + assert.equal(OpenCodeServerProfileSchema.safeParse({ kind: "explicit", id: "mapped", label: "Mapped", origin: mapped }).success, true) + let stored: unknown + const registry = new OpenCodeServerRegistry(() => stored, value => { stored = value }) + for (const value of ["http://[::ffff:127.0.0.1]:1234", "http://[::ffff:7f02:304]:1234", "http://[::1]:1234", "http://127.2.3.4:1234", "http://localhost:1234", "https://[::ffff:192.168.1.1]:1234"]) { + const origin = normalizeExplicitOrigin(value) + registry.replace([{ ...explicit, origin }]) + const profile = registry.get(explicit.id) + assert.equal(profile?.kind === "explicit" && profile.origin, origin) + } + for (const origin of ["http://[::ffff:c0a8:101]:1234", "http://[::ffff:a9fe:a9fe]:1234", "http://[::ffff:0:0]:1234", "http://remote.example", "https://[::ffff:a9fe:a9fe]:1234", "https://[fe80::1]:1234", "http://[::ffff:127.0.0.1]:1234"]) { + assert.throws(() => registry.replace([{ ...explicit, origin }]), origin) + } +}) + +test("public summaries whitelist fields and skip malformed origins without exposing private references", () => { + const summary = summarizeOpenCodeServers([{ ...explicit, password: "sentinel", nested: { token: "sentinel" } }, + { ...explicit, id: "bad", origin: "https://user:sentinel@example.test" }, explicit]) + assert.equal(summary.length, 2) + assert.deepEqual(summary[1], { kind: "explicit", id: explicit.id, label: explicit.label, origin: explicit.origin, + hasCredentials: false, needsCredentials: true }) + assert.doesNotMatch(JSON.stringify(summary), /sentinel|private-reference|credentialRef|password|nested/) + assert.deepEqual(summarizeOpenCodeServers({ secret: "sentinel" }), [{ id: "local-shared", kind: "local-shared" }]) +}) + +test("closed E1 capabilities distinguish unverified chat, live-only recovery and deferred integrations", () => { + const capabilities = initialServerCapabilities(explicit, 7) + assert.equal(capabilities.serverId, explicit.id) + assert.equal(capabilities.generation, 7) + assert.deepEqual(Object.keys(capabilities.features), [...SERVER_CAPABILITY_NAMES]) + assert.equal(capabilities.features.chat.state, "unknown") + assert.equal(capabilities.features.pendingRecovery.state, "limited") + assert.equal(capabilities.features.pendingRecovery.reason.code, "liveOnly") + for (const name of ["files", "git", "worktrees", "missions", "automation", "terminal", "historyEnrichment"] as const) { + assert.equal(capabilities.features[name].state, "unavailable") + assert.equal(capabilities.features[name].reason.code, "deferred") + } + assert.equal(capabilities.features.sessionEnvironment.reason.code, "localOnly") + assert.equal(initialServerCapabilities({ kind: "local-shared", id: "local-shared" }, 1).features.chat.state, "unknown") + assert.equal(SERVER_CONNECTION_LIMITS.explicitActiveTargets, 4) + assert.equal(SERVER_CONNECTION_LIMITS.reservedLocalTargets, 1) + assert.equal(SERVER_CONNECTION_LIMITS.administrativeProbes, 1) + assert.equal(SERVER_CONNECTION_LIMITS.probeTimeoutMs, 5_000) + assert.equal(SERVER_CONNECTION_LIMITS.probeMaxBytes, 8 * 1024 * 1024) + assert.equal(SERVER_CONNECTION_LIMITS.secondaryBrowserReads, 2) + assert.equal(SERVER_CONNECTION_LIMITS.eventJobs, 2_048) + assert.equal(SERVER_CONNECTION_LIMITS.eventBytes, 32 * 1024 * 1024) + assert.equal(SERVER_CONNECTION_LIMITS.eventJobTimeoutMs, 60_000) + assert.equal(SERVER_CONNECTION_LIMITS.reservedLocalEventJobs, 256) + assert.equal(SERVER_CONNECTION_LIMITS.reservedLocalEventBytes, 4 * 1024 * 1024) +}) diff --git a/packages/server/src/opencode/servers/registry.ts b/packages/server/src/opencode/servers/registry.ts new file mode 100644 index 0000000000..cf94262011 --- /dev/null +++ b/packages/server/src/opencode/servers/registry.ts @@ -0,0 +1,55 @@ +import { OpenCodeServersSchema, ProjectExecutionBindingSchema } from "../../config/schema" +import { LOCAL_SHARED_SERVER_ID, type OpenCodeServerProfile, type OpenCodeServerSummary } from "./types" + +const local: OpenCodeServerProfile = Object.freeze({ kind: "local-shared", id: LOCAL_SHARED_SERVER_ID }) + +/** Metadata only. SettingsService supplies the owning document's private writer. */ +export class OpenCodeServerRegistry { + #beforeChange = new Set<(next: OpenCodeServerProfile[]) => void>() + constructor(private readonly read: () => unknown, private readonly write: (profiles: OpenCodeServerProfile[]) => void) {} + + list(): OpenCodeServerProfile[] { + const value = this.read() + const profiles = OpenCodeServersSchema.parse(value === undefined ? [] : value) + return [local, ...profiles.filter(profile => profile.kind !== "local-shared")] + } + + get(id: string): OpenCodeServerProfile | undefined { + return this.list().find(profile => profile.id === id) + } + + replace(value: unknown): void { + const next = OpenCodeServersSchema.parse(value) + for (const listener of this.#beforeChange) listener(next) + this.write(next) + } + + beforeChange(listener: (next: OpenCodeServerProfile[]) => void): () => void { + this.#beforeChange.add(listener) + return () => { this.#beforeChange.delete(listener) } + } +} + +/** Preserve unknown target IDs for repair; remote directories remain byte-for-byte opaque. */ +export function parseProjectExecutionBinding(value: unknown) { + return ProjectExecutionBindingSchema.parse(value) +} + +/** Whitelist fields even when an on-disk entry contains unexpected secret material. */ +export function summarizeOpenCodeServers(value: unknown): OpenCodeServerSummary[] { + const result: OpenCodeServerSummary[] = [{ kind: "local-shared", id: LOCAL_SHARED_SERVER_ID }] + if (!Array.isArray(value)) return result + const ids = new Set([LOCAL_SHARED_SERVER_ID]) + for (const entry of value) { + if (!entry || typeof entry !== "object" || entry.kind !== "explicit") continue + const { id, kind, label, origin } = entry + const parsed = OpenCodeServersSchema.safeParse([{ id, kind, label, origin }]) + if (!parsed.success || ids.has(id)) continue + const profile = parsed.data[0]! + if (profile.kind !== "explicit") continue + ids.add(id) + result.push({ id: profile.id, kind: profile.kind, label: profile.label, origin: profile.origin, + hasCredentials: false, needsCredentials: true }) + } + return result +} diff --git a/packages/server/src/opencode/servers/remote-workspace.ts b/packages/server/src/opencode/servers/remote-workspace.ts new file mode 100644 index 0000000000..fa42c83d62 --- /dev/null +++ b/packages/server/src/opencode/servers/remote-workspace.ts @@ -0,0 +1,209 @@ +// prototype-1236: read-only Files and Changes of a project on an explicit OpenCode server. +// Every read goes through the project's single server connection, never the host disk or Git. +import type { FileSystemEntry, WorkspaceFileResponse, WorktreeGitDiffResponse, WorktreeGitStatusEntry } from "../../api-types" +import type { ServiceConnection } from "../../workspaces/opencode-service" + +export const REMOTE_FILE_READ_LIMIT = 5 * 1024 * 1024 +const JSON_LIMIT = 32 * 1024 * 1024 +const MAX_ENTRIES = 5_000 +const MAX_PATH = 4_096 +// Whole-file context: one hunk reconstructs both sides exactly. +const FULL_CONTEXT = 1_000_000 + +export class RemoteWorkspaceError extends Error { + constructor(readonly code: "invalid_path" | "not_found" | "too_large" | "unavailable" | "ambiguous" | "not_repository", readonly status: number) { + super(code) + this.name = "RemoteWorkspaceError" + } +} + +type Reader = Pick + +/** A path relative to the opened folder: "." or slash-separated segments, never absolute nor `..`. */ +export function remoteRelativePath(value: unknown): string { + if (value === undefined || value === "") return "." + if (typeof value !== "string" || value.length > MAX_PATH || value.includes("\0")) throw new RemoteWorkspaceError("invalid_path", 400) + const normalized = value.replace(/\\/g, "/") + if (normalized.startsWith("/") || /^[A-Za-z]:/.test(normalized)) throw new RemoteWorkspaceError("invalid_path", 400) + const segments = normalized.split("/").filter(segment => segment !== "" && segment !== ".") + if (segments.some(segment => segment === "..")) throw new RemoteWorkspaceError("invalid_path", 400) + return segments.join("/") || "." +} + +/** Filters what a native listing reports: only relative names inside the folder (Q1, exactness). */ +function insideEntry(path: unknown): string | undefined { + if (typeof path !== "string") return undefined + try { + const relative = remoteRelativePath(path) + return relative === "." ? undefined : relative + } catch { return undefined } +} + +async function readBounded(reader: Reader, path: string, query: Record, limit: number, signal: AbortSignal) { + const url = new URL(path, reader.endpoint.url) + for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value) + reader.assertCurrent() + const response = await reader.fetch(url.toString(), { signal, redirect: "error", headers: { accept: "application/json, application/octet-stream" } }) + reader.assertCurrent() + const body = response.body?.getReader() + const chunks: Uint8Array[] = [] + let size = 0 + try { + while (body) { + const chunk = await body.read() + reader.assertCurrent() + if (chunk.done) break + size += chunk.value.byteLength + if (size > limit) throw new RemoteWorkspaceError("too_large", 413) + chunks.push(chunk.value) + } + } catch (error) { await body?.cancel().catch(() => {}); throw error } + finally { body?.releaseLock() } + if (response.status === 404) throw new RemoteWorkspaceError("not_found", 404) + if (!response.ok) throw new RemoteWorkspaceError("unavailable", 502) + return { bytes: Buffer.concat(chunks, size), type: response.headers.get("content-type") ?? "" } +} + +/** One bounded native JSON read for the exact folder; the answer must name that folder. */ +export async function readJson(reader: Reader, path: string, query: Record, directory: string, signal: AbortSignal) { + const { bytes } = await readBounded(reader, path, { ...query, "location[directory]": directory }, JSON_LIMIT, signal) + let value: any + try { value = JSON.parse(bytes.toString("utf8")) } catch { throw new RemoteWorkspaceError("unavailable", 502) } + // Every answer must be for the exact opened folder. + if (!value || typeof value !== "object" || value.location?.directory !== directory || value.location.workspaceID !== undefined) { + throw new RemoteWorkspaceError("unavailable", 502) + } + return value +} + +function nameOf(path: string) { return path.split("/").at(-1)! } + +function entries(data: unknown, parent?: string): FileSystemEntry[] { + if (!Array.isArray(data)) throw new RemoteWorkspaceError("unavailable", 502) + const seen = new Set(), result: FileSystemEntry[] = [] + for (const entry of data.slice(0, MAX_ENTRIES)) { + const path = insideEntry(entry?.path) + if (!path || (entry.type !== "file" && entry.type !== "directory") || seen.has(path)) continue + if (parent !== undefined && (path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : ".") !== parent) continue + seen.add(path) + result.push({ name: nameOf(path), path, type: entry.type }) + } + return result +} + +export async function listRemoteFiles(reader: Reader, directory: string, relativePath: unknown, signal: AbortSignal): Promise { + const path = remoteRelativePath(relativePath) + const value = await readJson(reader, "/api/fs/list", { path }, directory, signal) + return entries(value.data, path).sort((a, b) => a.name.localeCompare(b.name)) +} + +export async function searchRemoteFiles(reader: Reader, directory: string, query: string, options: { limit?: number; type?: "all" | "file" | "directory" }, signal: AbortSignal) { + const value = await readJson(reader, "/api/fs/find", { + query, limit: String(Math.min(Math.max(options.limit ?? 100, 1), 1_000)), + ...(options.type && options.type !== "all" ? { type: options.type } : {}), + }, directory, signal) + return entries(value.data) +} + +export async function readRemoteFile(reader: Reader, workspaceId: string, directory: string, relativePath: unknown, encoding: "utf-8" | "base64", signal: AbortSignal): Promise { + const path = remoteRelativePath(relativePath) + if (path === ".") throw new RemoteWorkspaceError("invalid_path", 400) + const encoded = path.split("/").map(encodeURIComponent).join("/") + const { bytes } = await readBounded(reader, `/api/fs/read/${encoded}`, { "location[directory]": directory }, REMOTE_FILE_READ_LIMIT, signal) + return { workspaceId, relativePath: path, contents: bytes.toString(encoding === "base64" ? "base64" : "utf8"), encoding } +} + +const slash = (path: string) => path.replace(/\\/g, "/").replace(/\/+$/, "") + +/** The opened folder relative to the Git worktree root ("" or "a/b/"), undefined when it is not inside it. */ +export function locationPrefix(root: string, directory: string): string | undefined { + const r = slash(root), d = slash(directory) + const fold = /^[A-Za-z]:/.test(r) ? (value: string) => value.toLowerCase() : (value: string) => value + if (fold(r) === fold(d)) return "" + if (r === "" ) return d.startsWith("/") && d.length > 1 ? `${d.slice(1)}/` : undefined + return fold(d).startsWith(`${fold(r)}/`) ? `${d.slice(r.length + 1)}/` : undefined +} + +type NativeDiff = { file: string; patch: string; additions: number; deletions: number; status: "added" | "deleted" | "modified"; more?: true } + +async function workingDiff(reader: Reader, directory: string, signal: AbortSignal, context?: number) { + const [vcs, location] = await Promise.all([ + readJson(reader, "/api/vcs", {}, directory, signal), + readBounded(reader, "/api/location", { "location[directory]": directory }, 1024 * 1024, signal) + .then(({ bytes }) => JSON.parse(bytes.toString("utf8"))).catch(error => { throw error instanceof RemoteWorkspaceError ? error : new RemoteWorkspaceError("unavailable", 502) }), + ]) + if (!vcs.data?.provider) throw new RemoteWorkspaceError("not_repository", 409) + const root = location?.directory === directory ? location.project?.directory : undefined + const prefix = typeof root === "string" ? locationPrefix(root, directory) : undefined + // Unknown worktree root: paths cannot be brought back to the folder; never show it as clean. + if (prefix === undefined) throw new RemoteWorkspaceError("ambiguous", 409) + const value = await readJson(reader, "/api/vcs/diff", { mode: "working", ...(context ? { context: String(context) } : {}) }, directory, signal) + if (!Array.isArray(value.data)) throw new RemoteWorkspaceError("unavailable", 502) + const fold = prefix && /^[A-Za-z]:/.test(root!) ? (text: string) => text.toLowerCase() : (text: string) => text + const rows: Array = [] + for (const entry of value.data as NativeDiff[]) { + if (!entry || typeof entry.file !== "string" || !["added", "deleted", "modified"].includes(entry.status)) throw new RemoteWorkspaceError("unavailable", 502) + const file = entry.file.replace(/\\/g, "/") + // An untraversed folder containing the opened one leaves its whole state unknown. + if (entry.more && prefix.startsWith(file.replace(/\/?$/, "/")) && file !== "") throw new RemoteWorkspaceError("ambiguous", 409) + if (!fold(file).startsWith(fold(prefix))) continue + const path = insideEntry(file.slice(prefix.length)) + if (!path) continue + rows.push({ ...entry, path: entry.more ? `${path}/` : path }) + } + return rows +} + +/** Working-copy changes of the opened folder, in the local status shape (one unstaged section). */ +export async function remoteGitStatus(reader: Reader, directory: string, signal: AbortSignal): Promise { + return (await workingDiff(reader, directory, signal)).map(row => ({ + path: row.path, originalPath: null, stagedStatus: null, stagedAdditions: 0, stagedDeletions: 0, + unstagedStatus: row.status, unstagedAdditions: row.additions, unstagedDeletions: row.deletions, + })) +} + +/** Both sides of a whole-file patch; undefined when the patch cannot prove them. */ +export function patchSides(patch: string): { before: string; after: string } | undefined { + const lines = patch.split("\n") + if (lines.at(-1) === "") lines.pop() + const before: string[] = [], after: string[] = [] + let hunks = 0, last: "both" | "before" | "after" | undefined + let noNewline = { before: false, after: false } + let expected: { before: number; after: number } | undefined + for (const line of lines) { + const header = line.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/) + if (header) { + if (++hunks > 1) return undefined + // Full context starts at the first line of each side (0 for an empty side). + if (!["0", "1"].includes(header[1]) || !["0", "1"].includes(header[3])) return undefined + expected = { before: Number(header[2] ?? 1), after: Number(header[4] ?? 1) } + continue + } + if (!hunks) continue + if (line.startsWith("\\")) { + if (last === "both" || last === "before") noNewline.before = true + if (last === "both" || last === "after") noNewline.after = true + continue + } + const text = line.slice(1) + if (line.startsWith(" ")) { before.push(text); after.push(text); last = "both" } + else if (line.startsWith("-")) { before.push(text); last = "before" } + else if (line.startsWith("+")) { after.push(text); last = "after" } + else return undefined + } + if (!hunks || !expected || before.length !== expected.before || after.length !== expected.after) return undefined + const join = (side: string[], open: boolean) => side.length ? side.join("\n") + (open ? "" : "\n") : "" + return { before: join(before, noNewline.before), after: join(after, noNewline.after) } +} + +export async function remoteGitDiff(reader: Reader, directory: string, relativePath: unknown, signal: AbortSignal): Promise { + const path = remoteRelativePath(relativePath) + const row = (await workingDiff(reader, directory, signal, FULL_CONTEXT)).find(entry => entry.path === path) + if (!row) throw new RemoteWorkspaceError("not_found", 404) + const base = { path, originalPath: null, scope: "unstaged" as const } + if (/^Binary files /m.test(row.patch) || /^GIT binary patch/m.test(row.patch)) return { ...base, before: "", after: "", isBinary: true } + // Empty or partial patches (budget, mode-only, untraversed folder) never pass for an unchanged file. + const sides = row.more || !row.patch ? undefined : patchSides(row.patch) + if (!sides) throw new RemoteWorkspaceError("ambiguous", 409) + return { ...base, ...sides } +} diff --git a/packages/server/src/opencode/servers/transport.test.ts b/packages/server/src/opencode/servers/transport.test.ts new file mode 100644 index 0000000000..4f3b2a6e99 --- /dev/null +++ b/packages/server/src/opencode/servers/transport.test.ts @@ -0,0 +1,222 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import { createServer as httpServer, type Server, type RequestListener } from "node:http" +import { createServer as httpsServer } from "node:https" +import { once } from "node:events" +import { mkdtemp, writeFile, rm } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { execFile } from "node:child_process" +import { promisify } from "node:util" +import { setTimeout as delay } from "node:timers/promises" +import { createExplicitTransport } from "./transport" + +async function fixture(server: Server) { + server.listen(0, "127.0.0.1") + await once(server, "listening") + const port = (server.address() as { port: number }).port + return { port, origin: `http://127.0.0.1:${port}`, close: async () => { server.closeAllConnections(); await new Promise(resolve => server.close(() => resolve())) } } +} + +test("pinned DNS, Basic auth and header filtering preserve native requests", async () => { + let calls = 0 + const server = await fixture(httpServer((req, res) => { + assert.equal(req.headers.authorization, `Basic ${Buffer.from("user:synthetic-secret").toString("base64")}`) + for (const key of ["cookie", "forwarded", "x-forwarded-for", "x-hop"]) assert.equal(req.headers[key], undefined) + assert.equal(req.headers.host, `localhost:${server.port}`) + assert.equal(req.headers["x-opencode-directory"], "%2Fworkspace") + assert.equal(req.method, "POST") + assert.equal(req.url, "/api/session/id/prompt?x=1") + let body = "" + req.on("data", data => body += data) + req.on("end", () => { + assert.equal(body, '{"text":"hello"}') + res.writeHead(200, { "set-cookie": "secret=hidden", "www-authenticate": "Basic realm=private", "x-native": "kept", "content-type": "application/json" }) + res.end('{"ok":true}') + }) + })) + try { + const transport = createExplicitTransport({ origin: `http://localhost:${server.port}`, credentials: { username: "user", password: "synthetic-secret" } }, async () => { + calls++ + return [{ address: calls === 1 ? "127.0.0.1" : "169.254.169.254", family: 4 }] + }) + const response = await transport.fetch(`${transport.origin}/api/session/id/prompt?x=1`, { method: "POST", body: '{"text":"hello"}', headers: { + authorization: "Bearer inbound", cookie: "private", forwarded: "host=evil", "x-forwarded-for": "evil", host: "evil", connection: "x-hop", "x-hop": "private", "x-opencode-directory": "%2Fworkspace", + } }) + assert.deepEqual(await response.json(), { ok: true }) + assert.equal(response.headers.get("set-cookie"), null) + assert.equal(response.headers.get("www-authenticate"), null) + assert.equal(response.headers.get("x-native"), "kept") + assert.equal(calls, 1) + await assert.rejects(transport.fetch(`${transport.origin}/api/info`), { code: "forbidden_address" }) + assert.equal(calls, 2) + } finally { await server.close() } +}) + +test("responses strip hop-by-hop headers and Connection-nominated fields for fetch and probes", async () => { + const server = await fixture(httpServer((_req, res) => { + res.writeHead(200, { + trailer: "X-Trailer", te: "trailers", "proxy-connection": "keep-alive", + connection: "keep-alive, X-Hop, x-Other-Hop", "keep-alive": "timeout=5", + "x-hop": "private", "x-other-hop": "private", "x-native": "kept", + }) + res.end("ok") + })) + try { + const transport = createExplicitTransport({ origin: server.origin }) + for (const read of [() => transport.fetch(`${server.origin}/api/info`), () => transport.probe("/api/info")]) { + const response = await read() + assert.equal(response.status, 200) + assert.equal(await response.text(), "ok") + for (const name of ["trailer", "te", "proxy-connection", "connection", "keep-alive", "transfer-encoding", "upgrade", "x-hop", "x-other-hop"]) { + assert.equal(response.headers.get(name), null, name) + } + assert.equal(response.headers.get("x-native"), "kept") + } + } finally { await server.close() } +}) + +test("redirects never dispatch to Location or expose upstream secrets", async () => { + let requests = 0 + const server = await fixture(httpServer((_req, res) => { requests++; res.writeHead(302, { location: "http://user:secret@169.254.169.254/" }); res.end() })) + try { + const transport = createExplicitTransport({ origin: server.origin }) + await assert.rejects(transport.probe("/api/info"), { code: "redirect", message: "redirect" }) + assert.equal(requests, 1) + await assert.rejects(transport.fetch("http://elsewhere.example/api/info"), { code: "invalid_origin" }) + await assert.rejects(transport.probe("/api/session" as never), { code: "probe_path" }) + assert.equal(requests, 1) + } finally { await server.close() } +}) + +test("IPv6 loopback and IPv4-mapped literals use the controlled dispatcher", async () => { + const ipv4 = await fixture(httpServer((_req, res) => res.end("mapped"))) + const ipv6 = httpServer((_req, res) => res.end("ipv6")) + ipv6.listen(0, "::1") + await once(ipv6, "listening") + try { + const port = (ipv6.address() as { port: number }).port + const native = createExplicitTransport({ origin: `http://[::1]:${port}` }) + assert.equal(await (await native.probe("/api/info")).text(), "ipv6") + const mapped = createExplicitTransport({ origin: `http://[::ffff:127.0.0.1]:${ipv4.port}` }) + assert.equal(await (await mapped.probe("/api/info")).text(), "mapped") + } finally { + await ipv4.close() + ipv6.closeAllConnections() + await new Promise(resolve => ipv6.close(() => resolve())) + } +}) + +test("read-only probes bound full body to 8 MiB while regular responses stream", async () => { + const requests: string[] = [] + const server = await fixture(httpServer((req, res) => { + requests.push(`${req.method} ${req.url}`) + res.writeHead(200) + res.end(Buffer.alloc(8 * 1024 * 1024 + 1, 97)) + })) + try { + const transport = createExplicitTransport({ origin: server.origin }) + await assert.rejects(transport.probe("/openapi.json"), { code: "response_limit" }) + const response = await transport.fetch(`${server.origin}/api/event`) + assert.equal((await response.arrayBuffer()).byteLength, 8 * 1024 * 1024 + 1) + assert.deepEqual(requests, ["GET /openapi.json", "GET /api/event"]) + } finally { await server.close() } +}) + +test("ordinary SSE stays streaming beyond probe deadline and cancellation closes it", async () => { + let closed: Promise | undefined + const server = await fixture(httpServer((req, res) => { + closed = once(req.socket, "close") + res.writeHead(200, { "content-type": "text/event-stream" }) + res.write("data: first\n\n") + })) + try { + const transport = createExplicitTransport({ origin: server.origin }) + const response = await transport.fetch(`${server.origin}/api/event`) + const reader = response.body!.getReader() + assert.equal(new TextDecoder().decode((await reader.read()).value), "data: first\n\n") + await delay(5_100) + await reader.cancel() + await closed + } finally { await server.close() } +}) + +test("authentication status survives without challenge/cookie leakage or inherited auth", async () => { + const server = await fixture(httpServer((req, res) => { + assert.equal(req.headers.authorization, undefined) + assert.equal(req.headers.cookie, undefined) + res.writeHead(401, { "www-authenticate": "Basic realm=private", "set-cookie": "session=private", "content-type": "application/json" }) + res.end('{"_tag":"Unauthorized"}') + })) + try { + const transport = createExplicitTransport({ origin: server.origin }) + const response = await transport.fetch(`${server.origin}/api/info`, { headers: { authorization: "Bearer private", cookie: "session=private" } }) + assert.equal(response.status, 401) + assert.equal(response.headers.get("www-authenticate"), null) + assert.equal(response.headers.get("set-cookie"), null) + assert.deepEqual(await response.json(), { _tag: "Unauthorized" }) + } finally { await server.close() } +}) + +test("probe 5s deadline covers DNS, headers and stalled body with cleanup", async () => { + const server = await fixture(httpServer((_req, res) => { res.writeHead(200); res.write("{") })) + try { + const started = Date.now() + const transport = createExplicitTransport({ origin: server.origin }) + const dns = createExplicitTransport({ origin: "https://stalled.example" }, () => new Promise(() => {})) + const headers = await fixture(httpServer(() => {})) + try { + await Promise.all([ + assert.rejects(transport.probe("/api/info"), { code: "timeout" }), + assert.rejects(dns.probe("/api/info"), { code: "timeout" }), + assert.rejects(createExplicitTransport({ origin: headers.origin }).probe("/api/info"), { code: "timeout" }), + ]) + } finally { await headers.close() } + assert.ok(Date.now() - started >= 4_900) + assert.ok(Date.now() - started < 8_000) + } finally { await server.close() } +}) + +// Public synthetic fixture identity; never used outside isolated loopback tests. +const key = `-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgth2e2V4anmz2hOIE +Z0jqcFbjbKt+hpcECO7W7KRStBGhRANCAATD6GhbqP7HMeepEWS+yGNNJ/uxyGKg +0fKjSbqG1B/NOJ5/h/w71ki4pGlXE2MBDmwDxTvftcEFXebkICgs4n5c +-----END PRIVATE KEY-----` +const cert = `-----BEGIN CERTIFICATE----- +MIIBZjCCAQ2gAwIBAgIUc2HhJRjv49wP3w6jX0XqLAdUHogwCgYIKoZIzj0EAwIw +FDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MTEwMTEzMTgwMloXDTM2MTAyOTEz +MTgwMlowFDESMBAGA1UEAwwJbG9jYWxob3N0MFkwEwYHKoZIzj0CAQYIKoZIzj0D +AQcDQgAEw+hoW6j+xzHnqRFkvshjTSf7schioNHyo0m6htQfzTief4f8O9ZIuKRp +VxNjAQ5sA8U737XBBV3m5CAoLOJ+XKM9MDswGgYDVR0RBBMwEYIJbG9jYWxob3N0 +hwR/AAABMB0GA1UdDgQWBBRosow4p9y9ZAHwlzkLs4JCWn6AxzAKBggqhkjOPQQD +AgNHADBEAiA2tlXRHGz3ch82/SsBpGFdg/H2GEpEtWJPYKmuWABHawIgcBCQFAhA +dliK0iZIP2tHh2GgVppvNuAOKmL2DSVXOMY= +-----END CERTIFICATE-----` + +test("TLS verifies trust and hostname; scoped CA has an explicit diagnostic", async () => { + let requests = 0 + const handler: RequestListener = (req, res) => { + requests++ + assert.equal(req.headers.authorization, `Basic ${Buffer.from("user:synthetic-secret").toString("base64")}`) + res.end("trusted") + } + const server = await fixture(httpsServer({ key, cert }, handler)) + const directory = await mkdtemp(join(tmpdir(), "codenomad-explicit-tls-")) + try { + const origin = server.origin.replace("http:", "https:") + await assert.rejects(createExplicitTransport({ origin, credentials: { username: "user", password: "synthetic-secret" } }).probe("/api/info"), { code: "tls", message: "tls" }) + assert.equal(requests, 0) + assert.throws(() => createExplicitTransport({ origin, ca: cert }), { code: "custom_ca_unsupported" }) + const caPath = join(directory, "fixture.pem") + await writeFile(caPath, cert) + // Trust is confined to a child process, exercising the platform CA path without a TLS bypass. + const code = `import assert from 'node:assert/strict'; import { createExplicitTransport } from './packages/server/src/opencode/servers/transport.ts'; + const t=createExplicitTransport({origin:${JSON.stringify(origin)},credentials:{username:'user',password:'synthetic-secret'}}); + assert.equal(await (await t.probe('/api/info')).text(),'trusted'); + const wrong=createExplicitTransport({origin:'https://wrong.example:${server.port}'},async()=>[{address:'127.0.0.1',family:4}]); + await assert.rejects(wrong.probe('/api/info'),{code:'tls'});` + await promisify(execFile)(process.execPath, ["--import", "tsx", "--input-type=module", "-e", code], { env: { ...process.env, NODE_EXTRA_CA_CERTS: caPath }, timeout: 15_000 }) + assert.equal(requests, 1) + } finally { await server.close(); await rm(directory, { recursive: true, force: true }) } +}) diff --git a/packages/server/src/opencode/servers/transport.ts b/packages/server/src/opencode/servers/transport.ts new file mode 100644 index 0000000000..4338f87f02 --- /dev/null +++ b/packages/server/src/opencode/servers/transport.ts @@ -0,0 +1,105 @@ +import { Agent, fetch as undiciFetch } from "undici" +import { ExplicitEndpointError, normalizeExplicitOrigin, resolveExplicitAddress, type ResolveAddresses } from "./endpoint" +import { SERVER_CONNECTION_LIMITS } from "./types" +import { boundedResponseFetch, BoundedResponseError } from "../bounded-response-fetch" + +const requestDenied = /^(authorization|proxy-authorization|cookie|cookie2|host|forwarded|x-forwarded-.*|x-real-ip|connection|keep-alive|proxy-connection|te|trailer|transfer-encoding|upgrade)$/i +const responseDenied = /^(authorization|proxy-authorization|cookie|set-cookie2?|www-authenticate|proxy-authenticate|authentication-info|proxy-authentication-info|server|x-powered-by|connection|keep-alive|proxy-connection|te|trailer|transfer-encoding|upgrade)$/i + +function filterHeaders(input: Headers, denied: RegExp): Headers { + const headers = new Headers(input) + for (const name of (input.get("connection") ?? "").split(",")) if (name.trim()) headers.delete(name.trim()) + for (const name of [...headers.keys()]) if (denied.test(name)) headers.delete(name) + return headers +} + +function diagnostic(error: unknown, signal: AbortSignal): ExplicitEndpointError { + if (error instanceof ExplicitEndpointError) return error + if (error instanceof BoundedResponseError) return new ExplicitEndpointError("response_limit") + if (signal.aborted) return new ExplicitEndpointError("timeout") + const code = (error as { cause?: { code?: string }; code?: string })?.cause?.code ?? (error as { code?: string })?.code ?? "" + return new ExplicitEndpointError(/CERT|TLS|SSL|SELF_SIGNED|UNABLE_TO_VERIFY/.test(code) ? "tls" : "network") +} + +function abortable(promise: Promise, signal: AbortSignal): Promise { + return new Promise((resolve, reject) => { + const abort = () => reject(new ExplicitEndpointError("timeout")) + if (signal.aborted) { abort(); return } + signal.addEventListener("abort", abort, { once: true }) + promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort)) + }) +} + +/** Internal backend seam. All explicit HTTP dispatches, including probes, use this fetch. */ +export function createExplicitTransport(options: { + origin: string + credentials?: { username: string; password: string } + signal?: AbortSignal + ca?: string +}, resolve?: ResolveAddresses) { + const origin = normalizeExplicitOrigin(options.origin) + if (options.ca !== undefined) throw new ExplicitEndpointError("custom_ca_unsupported") + // Copy secret inputs; subsequent caller mutation cannot retarget credentials. + const credentials = options.credentials ? { ...options.credentials } : undefined + if (credentials?.username.includes(":")) throw new ExplicitEndpointError("invalid_origin") + const lifetime = options.signal ?? new AbortController().signal + const fetch: typeof globalThis.fetch = async (input, init) => { + let agent: Agent | undefined + let signal = lifetime + try { + const request = new Request(input, init) + const url = new URL(request.url) + if (url.origin !== origin || url.username || url.password || url.hash) throw new ExplicitEndpointError("invalid_origin") + signal = AbortSignal.any([lifetime, request.signal]) + signal.throwIfAborted() + const address = await abortable(resolveExplicitAddress(origin, resolve), signal) + signal.throwIfAborted() + agent = new Agent({ connect: { + rejectUnauthorized: true, + // No second DNS query: TLS still verifies the original hostname and sends its SNI. + lookup: (_hostname, options, callback) => { + if (options.all) callback(null, [{ address: address.address, family: address.family }] as never) + else callback(null, address.address, address.family) + }, + } }) + const headers = filterHeaders(request.headers, requestDenied) + if (credentials) headers.set("authorization", `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString("base64")}`) + const response = await undiciFetch(url, { + method: request.method, headers: Object.fromEntries(headers), + body: request.body as never, duplex: "half", signal, redirect: "manual", dispatcher: agent, + }) + signal.throwIfAborted() + if (response.status >= 300 && response.status < 400 && response.status !== 304) { + void response.body?.cancel().catch(() => {}) + throw new ExplicitEndpointError("redirect") + } + const responseHeaders = filterHeaders(new Headers([...response.headers]), responseDenied) + const owner = agent + if (!response.body) { void owner.destroy().catch(() => {}); return new Response(null, { status: response.status, headers: responseHeaders }) } + const reader = response.body.getReader() + let cleaned = false + const cleanup = () => { if (cleaned) return; cleaned = true; reader.releaseLock(); void owner.destroy().catch(() => {}) } + const body = new ReadableStream({ + async pull(controller) { + try { + const chunk = await reader.read() + signal.throwIfAborted() + if (chunk.done) { controller.close(); cleanup() } + else controller.enqueue(chunk.value) + } catch (error) { controller.error(diagnostic(error, signal)); cleanup() } + }, + cancel() { void reader.cancel().catch(() => {}); cleanup() }, + }) + return new Response(body, { status: response.status, headers: responseHeaders }) + } catch (error) { void agent?.destroy().catch(() => {}); throw diagnostic(error, signal) } + } + + /** Fixed read-only discovery paths. Deadline includes DNS, headers, body and cancellation. */ + async function probe(path: "/api/info" | "/openapi.json", signal?: AbortSignal): Promise { + if (path !== "/api/info" && path !== "/openapi.json") throw new ExplicitEndpointError("probe_path") + const deadline = AbortSignal.any([lifetime, AbortSignal.timeout(SERVER_CONNECTION_LIMITS.probeTimeoutMs), ...(signal ? [signal] : [])]) + try { return await boundedResponseFetch(fetch, deadline, () => {}, SERVER_CONNECTION_LIMITS.probeMaxBytes)(new URL(path, origin), { signal: deadline, method: "GET" }) } + catch (error) { throw diagnostic(error, deadline) } + } + return { origin, fetch, probe } +} diff --git a/packages/server/src/opencode/servers/types.ts b/packages/server/src/opencode/servers/types.ts new file mode 100644 index 0000000000..11abccc267 --- /dev/null +++ b/packages/server/src/opencode/servers/types.ts @@ -0,0 +1,34 @@ +import type { z } from "zod" +import type { OpenCodeServerProfileSchema, ProjectExecutionBindingSchema } from "../../config/schema" + +export const LOCAL_SHARED_SERVER_ID = "local-shared" as const +export type OpenCodeServerId = string +export type OpenCodeServerProfile = z.infer +export type ProjectExecutionBinding = z.infer +export type OpenCodeServerSummary = + | { kind: "local-shared"; id: typeof LOCAL_SHARED_SERVER_ID } + | { kind: "explicit"; id: OpenCodeServerId; label: string; origin: string; + hasCredentials: boolean; needsCredentials: boolean } + +export const SERVER_CONNECTION_LIMITS = Object.freeze({ + explicitActiveTargets: 4, reservedLocalTargets: 1, + administrativeProbes: 1, probeTimeoutMs: 5_000, probeMaxBytes: 8 * 1024 * 1024, + secondaryBrowserReads: 2, eventJobs: 2_048, eventBytes: 32 * 1024 * 1024, + eventJobTimeoutMs: 60_000, reservedLocalEventJobs: 256, reservedLocalEventBytes: 4 * 1024 * 1024, +}) + +/** Connection-engine contract; durable bindings contain only serverId + directory. + * Reserve atomically per target, sharing admission/SSE across projects and windows. + * Failed initial admission releases its reservation; admitted offline/rotating targets retain it. + * Restore in existing queue order; excess targets remain reconnectable (quota), without eviction. + * Last project occurrence closing across windows releases the slot and cancels reads/SSE/retry. + * Connect without projects retains a slot until Disconnect/shutdown or an attach/last-close cycle. + * Disconnect cancels/fences/releases, preserving tabs/drafts; only explicit Connect resumes them. + * Connect/Disconnect are host-only, preserve native sessions and never stop OpenCode. + * Their intent stays in memory; opportunistic tab reads never reconnect a disconnected target. + * Administrative probes use their separate bounded lane, without slots, SSE or retries; + * form close or URL/auth changes cancel them. Paired clients use already admitted projects. + * Event admission reserves the local share, divides the remainder fairly among explicit + * sources, and signals bounded resync/diagnostics on saturation. + */ +export type ServerConnectionGeneration = number diff --git a/packages/server/src/opencode/service-usage.test.ts b/packages/server/src/opencode/service-usage.test.ts index 2395f1c1af..7b4bdd3d2d 100644 --- a/packages/server/src/opencode/service-usage.test.ts +++ b/packages/server/src/opencode/service-usage.test.ts @@ -21,6 +21,7 @@ function fixture() { session: { stats: async (input: any) => { calls.push(input); if (defer) await new Promise(resolve => { defer = resolve }); return stats(input.from, input.to) } }, } } const manager: any = { get: () => present ? record : undefined, getSharedServiceConnection: async () => connection, + requireWorkspaceCapability: () => new AbortController().signal, getServiceWslDistro: () => distro, getServicePathStyle: () => "posix" } return { service: new ServiceUsage(manager), calls, manager, connection, record, root: (value: string) => { root = value }, distro: (value: string) => { distro = value }, stale: () => { current = false }, close: () => { present = false }, diff --git a/packages/server/src/opencode/service-usage.ts b/packages/server/src/opencode/service-usage.ts index 492deb7bb0..9118d0775b 100644 --- a/packages/server/src/opencode/service-usage.ts +++ b/packages/server/src/opencode/service-usage.ts @@ -6,7 +6,7 @@ import type { ServiceConnection } from "../workspaces/opencode-service" import type { SettingsService } from "../settings/service" import { ServiceUsageCache } from "./service-usage-cache" -type Manager = Pick +type Manager = Pick export type UsageQuery = { from: number; to: number; timezone: string; restorePeriod?: boolean } // Deliberately service-wide, as authorized for the Usage Preferences surface. @@ -29,6 +29,11 @@ export class ServiceUsage { if (settings) this.cache = new ServiceUsageCache(settings) } private async context(workspaceId: string) { + try { this.manager.requireWorkspaceCapability(workspaceId, "executionSettings") } + catch (error) { + if (error instanceof Error && "statusCode" in error && error.statusCode === 404) throw new PluginControlsError("Workspace not found", "not-found") + throw error + } if (this.closing.signal.aborted) throw new PluginControlsError("Stats service closed", "unavailable") const record = this.manager.get(workspaceId) if (!record) throw new PluginControlsError("Workspace not found", "not-found") diff --git a/packages/server/src/opencode/session-media-contract.ts b/packages/server/src/opencode/session-media-contract.ts index 2add7d85ae..121fc2852c 100644 --- a/packages/server/src/opencode/session-media-contract.ts +++ b/packages/server/src/opencode/session-media-contract.ts @@ -6,7 +6,25 @@ export const DEFERRED_MEDIA_HEADER = "x-codenomad-media" export const DEFERRED_MEDIA_VALUE = "deferred" +/** Serialized message or whole decompressed media HTTP envelope, before parsing. */ +export const MESSAGE_LIMIT = 16 * 1024 * 1024 + /** `/api/workspaces//session-media/////` */ export function isSessionMediaPath(value: string): boolean { return /^\/api\/workspaces\/[^/?#]+\/session-media\/[^/?#]+\/[^/?#]+\/\d{1,6}\/\d{1,6}\/[a-f0-9]{64}$/.test(value) } + +/** Exact canonical native reference; encoded separators and alternate spellings fail closed. */ +export function parseSessionMediaPath(value: string): { workspaceId: string; sessionId: string; messageId: string; part: number; index: number; digest: string } | undefined { + if (value.length > 4096) return undefined + const match = /^\/api\/workspaces\/([^/?#]+)\/session-media\/([^/?#]+)\/([^/?#]+)\/(0|[1-9]\d{0,5})\/(0|[1-9]\d{0,5})\/([a-f0-9]{64})$/.exec(value) + if (!match) return undefined + try { + const ids = match.slice(1, 4).map(segment => { + const id = decodeURIComponent(segment) + if (!id || id === "." || id === ".." || /[\/%\\?#\x00-\x20\x7f]/.test(id) || encodeURIComponent(id) !== segment) throw new Error("Invalid media reference") + return id + }) + return { workspaceId: ids[0], sessionId: ids[1], messageId: ids[2], part: Number(match[4]), index: Number(match[5]), digest: match[6] } + } catch { return undefined } +} diff --git a/packages/server/src/opencode/session-media-fetch.test.ts b/packages/server/src/opencode/session-media-fetch.test.ts new file mode 100644 index 0000000000..edf65b0658 --- /dev/null +++ b/packages/server/src/opencode/session-media-fetch.test.ts @@ -0,0 +1,151 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { OpenCode } from "@opencode/client" +import { boundedMediaFetch } from "./session-media-fetch" +import { MESSAGE_LIMIT } from "./session-media-contract" +import { getEventListeners } from "node:events" + +function body(size: number, error = false) { + const base = JSON.stringify(error ? { _tag: "SessionNotFoundError", sessionID: "s", message: "fixture", pad: "" } : { data: { id: "m" }, pad: "" }) + return new TextEncoder().encode(base.slice(0, -2) + " ".repeat(size - base.length) + '"}') +} + +for (const status of [200, 404]) { + for (const size of [MESSAGE_LIMIT - 1, MESSAGE_LIMIT, MESSAGE_LIMIT + 1]) test(`official SDK ${status}/${size}: limit before parser, headers are advisory`, async t => { + const bytes = body(size, status === 404) + let cancelled = 0, parsed = 0 + const source = new ReadableStream({ start(controller) { controller.enqueue(bytes); controller.close() }, cancel() { cancelled++ } }, { highWaterMark: 0 }) + // Observe the actual SDK's parser rather than replacing its guard or decoder. + const text = Response.prototype.text + t.mock.method(Response.prototype, "text", function (this: Response) { parsed++; return text.call(this) }) + const fetch = boundedMediaFetch(async () => new Response(source, { status, headers: { "content-type": "application/json", "content-length": "1" } }), new AbortController().signal, () => {}) + const client = OpenCode.make({ baseUrl: "http://media.invalid", fetch }) + if (size > MESSAGE_LIMIT || status !== 200) await assert.rejects(client.session.message.get({ sessionID: "s", messageID: "m" })) + else assert.equal((await client.session.message.get({ sessionID: "s", messageID: "m" })).id, "m") + assert.equal(parsed, size > MESSAGE_LIMIT ? 0 : 1) + // A closed one-chunk stream is already settled; cancellation is proven below on live streams. + assert.equal(cancelled, 0) + }) +} + +test("overflowing individual chunk and cumulative chunks are cancelled before returning any Response to the SDK", async () => { + for (const sizes of [[MESSAGE_LIMIT + 1], [MESSAGE_LIMIT, 1], [MESSAGE_LIMIT / 2, MESSAGE_LIMIT / 2, 1]]) { + let cancelled = 0, reads = 0 + const stream = new ReadableStream({ pull(controller) { controller.enqueue(new Uint8Array(sizes[reads++])); }, cancel() { cancelled++ } }, { highWaterMark: 0 }) + const fetch = boundedMediaFetch(async () => new Response(stream), new AbortController().signal, () => {}) + await assert.rejects(fetch("http://media.invalid"), /too large/) + assert.equal(reads, sizes.length) + assert.equal(cancelled, 1) + assert.equal(stream.locked, false) + } +}) + +test("below/exact limit chunked bodies preserve status, statusText and needed headers without stale encoding/length", async () => { + for (const size of [MESSAGE_LIMIT - 1, MESSAGE_LIMIT]) { + let reads = 0 + const stream = new ReadableStream({ pull(controller) { + if (reads++ === 0) controller.enqueue(new Uint8Array(size - 1)) + else { controller.enqueue(Uint8Array.of(42)); controller.close() } + } }) + const fetch = boundedMediaFetch(async () => new Response(stream, { status: 404, statusText: "Fixture", headers: { + "content-type": "application/json", "x-fixture": "kept", "content-length": "1", "content-encoding": "gzip", "transfer-encoding": "chunked", + } }), new AbortController().signal, () => {}) + const response = await fetch("http://media.invalid") + assert.equal(response.status, 404); assert.equal(response.statusText, "Fixture") + assert.equal(response.headers.get("content-type"), "application/json") + assert.equal(response.headers.get("x-fixture"), "kept") + for (const header of ["content-length", "content-encoding", "transfer-encoding"]) assert.equal(response.headers.get(header), null) + const bytes = new Uint8Array(await response.arrayBuffer()) + assert.equal(bytes.byteLength, size); assert.equal(bytes.at(-1), 42) + } +}) + +test("pre-dispatch abort invokes no fetch; abort during a stalled body cancels and releases it", async () => { + const controller = new AbortController() + let requests = 0 + const never = boundedMediaFetch(async () => { requests++; return new Response() }, controller.signal, () => {}) + controller.abort() + await assert.rejects(never("http://media.invalid"), { name: "AbortError" }) + assert.equal(requests, 0) + for (const fromRequest of [false, true]) { + const abort = new AbortController() + let entered!: () => void, cancelled = 0 + const reading = new Promise(resolve => { entered = resolve }) + const stream = new ReadableStream({ pull() { entered() }, cancel() { cancelled++ } }, { highWaterMark: 0 }) + const fetch = boundedMediaFetch(async () => new Response(stream), fromRequest ? new AbortController().signal : abort.signal, () => {}) + const pending = fetch(new Request("http://media.invalid", fromRequest ? { signal: abort.signal } : undefined)) + const rejected = assert.rejects(pending, { name: "AbortError" }) + await reading + abort.abort() + await rejected + assert.equal(cancelled, 1); assert.equal(stream.locked, false) + } +}) + +test("retired authority after headers cancels upstream; absent body cannot reach SDK parsing", async () => { + let current = true, cancelled = 0 + const stream = new ReadableStream({ cancel() { cancelled++ } }) + const fetch = boundedMediaFetch(async () => { current = false; return new Response(stream) }, new AbortController().signal, () => { if (!current) throw new Error("retired") }) + await assert.rejects(fetch("http://media.invalid"), /retired/) + assert.equal(cancelled, 1); assert.equal(stream.locked, false) + const empty = boundedMediaFetch(async () => new Response(null, { status: 204 }), new AbortController().signal, () => {}) + await assert.rejects(empty("http://media.invalid"), /no body/) +}) + +test("official wire keeps captured base prefix, encoded directory header and per-request options", async () => { + let requests = 0 + const directory = encodeURIComponent("/opaque Case/🦊") + const fetch = boundedMediaFetch(async (input, init) => { + requests++ + assert.equal(String(input), "http://media.invalid/prefix/api/session/%C3%A9t%C3%A9") + assert.equal(init?.method, "GET") + assert.equal(new Headers(init?.headers).get("x-opencode-directory"), directory) + assert.equal(new Headers(init?.headers).get("x-fixture"), "captured") + assert.equal(init?.signal?.aborted, false) + return Response.json({ data: { id: "été" } }) + }, new AbortController().signal, () => {}) + const client = OpenCode.make({ baseUrl: "http://media.invalid/prefix", fetch, headers: { "x-opencode-directory": directory } }) + assert.equal((await client.session.get({ sessionID: "été" }, { headers: { "x-fixture": "captured" } })).id, "été") + assert.equal(requests, 1) +}) + +test("the ceiling counts UTF-8 bytes rather than string characters", async () => { + const text = "🦊".repeat(MESSAGE_LIMIT / 4 + 1) + assert(text.length < MESSAGE_LIMIT) + const fetch = boundedMediaFetch(async () => new Response(text), new AbortController().signal, () => {}) + await assert.rejects(fetch("http://media.invalid"), /too large/) +}) + +for (const reason of ["overflow", "abort"]) for (const rejectCleanup of [false, true]) { + test(`${reason}: observer releases reader and listeners before held cancellation ${rejectCleanup ? "rejects" : "resolves"}`, async () => { + const abort = new AbortController() + let entered!: () => void, cancelled!: () => void, finish!: () => void + const reading = new Promise(resolve => { entered = resolve }) + const cancelling = new Promise(resolve => { cancelled = resolve }) + const cleanup = new Promise((resolve, reject) => { finish = () => rejectCleanup ? reject(new Error("Late cleanup failure")) : resolve() }) + let cancelCalls = 0, settled = false, requestSignal!: AbortSignal + const stream = new ReadableStream({ + pull(controller) { + entered() + if (reason === "overflow") controller.enqueue(new Uint8Array(MESSAGE_LIMIT + 1)) + }, + cancel() { cancelCalls++; cancelled(); return cleanup }, + }, { highWaterMark: 0 }) + const fetch = boundedMediaFetch(async (_input, init) => { + requestSignal = init!.signal! + return new Response(stream, { headers: { "content-type": "application/json" } }) + }, abort.signal, () => {}) + const client = OpenCode.make({ baseUrl: "http://media.invalid", fetch }) + const result = assert.rejects(client.session.message.get({ sessionID: "s", messageID: "m" })).then(() => { settled = true }) + await reading + if (reason === "abort") abort.abort() + await cancelling + await new Promise(resolve => setImmediate(resolve)) + try { + assert.deepEqual({ settled, locked: stream.locked, listeners: getEventListeners(requestSignal, "abort").length, cancelCalls }, + { settled: true, locked: false, listeners: 0, cancelCalls: 1 }) + } finally { finish(); await result } + // Let a late rejection surface naturally if the cancellation promise was left unobserved. + await new Promise(resolve => setImmediate(resolve)) + }) +} diff --git a/packages/server/src/opencode/session-media-fetch.ts b/packages/server/src/opencode/session-media-fetch.ts new file mode 100644 index 0000000000..956251094d --- /dev/null +++ b/packages/server/src/opencode/session-media-fetch.ts @@ -0,0 +1,7 @@ +import { MESSAGE_LIMIT } from "./session-media-contract" +import { boundedResponseFetch } from "./bounded-response-fetch" + +/** Media-only seam around an already captured transport. Fetch supplies decoded bytes. */ +export function boundedMediaFetch(fetch: typeof globalThis.fetch, signal: AbortSignal, current: () => void): typeof globalThis.fetch { + return boundedResponseFetch(fetch, signal, current, MESSAGE_LIMIT) +} diff --git a/packages/server/src/opencode/session-media.ts b/packages/server/src/opencode/session-media.ts index cfcd3166bb..460426a73c 100644 --- a/packages/server/src/opencode/session-media.ts +++ b/packages/server/src/opencode/session-media.ts @@ -1,5 +1,6 @@ import { createHash } from "node:crypto" import { DEFERRED_MEDIA_HEADER, DEFERRED_MEDIA_VALUE } from "./session-media-contract" +import { isEmbeddedAsset } from "./embedded-asset" export { DEFERRED_MEDIA_HEADER } from "./session-media-contract" /** Data URIs up to this length stay inline. */ @@ -15,12 +16,11 @@ export function mediaDigest(uri: string): string { return createHash("sha256").update(uri).digest("hex") } -/** An image the renderer shows inline: a base64 data URI of its declared image type. */ +/** Bounded image data, validated before digesting or decoding; permission is separate. */ export function isRenderableToolImage(value: unknown): value is ToolImage { const file = value as Partial | null - if (file?.type !== "file" || typeof file.mime !== "string" || !/^image\/[\w.+-]+$/i.test(file.mime) || typeof file.uri !== "string") return false - const header = `data:${file.mime.toLowerCase()};base64,` - return file.uri.slice(0, header.length).toLowerCase() === header + return file?.type === "file" && typeof file.mime === "string" && typeof file.uri === "string" + && isEmbeddedAsset({ mime: file.mime, uri: file.uri }) && file.mime.toLowerCase().startsWith("image/") } export function sessionMediaPath(target: { workspaceId: string; sessionId: string; messageId: string; part: number; index: number; digest: string }): string { diff --git a/packages/server/src/opencode/session-pruning/assets-contract.ts b/packages/server/src/opencode/session-pruning/assets-contract.ts index a09fc50b49..67786c0531 100644 --- a/packages/server/src/opencode/session-pruning/assets-contract.ts +++ b/packages/server/src/opencode/session-pruning/assets-contract.ts @@ -1,7 +1,8 @@ import { z } from "zod" +import { ASSET_URI_LIMIT, isEmbeddedAsset } from "../embedded-asset" +export { ASSET_URI_LIMIT, isEmbeddedAsset } from "../embedded-asset" const Id = z.string().min(1).max(256) -export const ASSET_URI_LIMIT = 8 * 1024 * 1024 export const assetTargetSchema = z.object({ messageID: Id, part: z.number().int().min(0).max(100000), index: z.number().int().min(0).max(100000), digest: z.string().regex(/^[a-f0-9]{64}$/) }).strict() export const assetsInputSchema = z.object({ sessionID: Id, cursor: z.string().max(4096).optional() }).strict() @@ -12,11 +13,6 @@ export const assetsResultSchema = z.union([blocked, z.object({ status: z.literal }).strict()).max(64), cursor: z.string().max(4096).nullable() }).strict()]) export const assetReadResultSchema = z.union([blocked, z.object({ status: z.literal("asset"), mime: z.string().regex(/^[\w.+-]+\/[\w.+-]+$/).max(128), uri: z.string().max(ASSET_URI_LIMIT) }).strict().refine(isEmbeddedAsset)]) -export function isEmbeddedAsset(file: { mime: string; uri: string }): boolean { - if (file.uri.length > ASSET_URI_LIMIT) return false - const prefix = `data:${file.mime};base64,`, body = file.uri.slice(prefix.length) - return file.uri.startsWith(prefix) && body.length > 0 && body.length % 4 === 0 && /^[A-Za-z0-9+/]*={0,2}$/.test(body) -} export type AssetTarget = z.infer export type AssetsResult = z.infer export type AssetReadResult = z.infer diff --git a/packages/server/src/opencode/session-pruning/assets-store.ts b/packages/server/src/opencode/session-pruning/assets-store.ts index 1737ad656e..51781ea662 100644 --- a/packages/server/src/opencode/session-pruning/assets-store.ts +++ b/packages/server/src/opencode/session-pruning/assets-store.ts @@ -6,8 +6,9 @@ import { ownedSession } from "./navigation-scope" import type { HistoryScope } from "./history-store" import { ASSET_URI_LIMIT, isEmbeddedAsset, type AssetTarget, type AssetsResult, type AssetReadResult } from "./assets-contract" import { mediaBlobBase64, mediaBlobSizes, mediaDataUri, mediaDataUriLength, toolMediaHash } from "./media-blob" +import { MESSAGE_LIMIT } from "../session-media-contract" -export const MESSAGE_LIMIT = 16 * 1024 * 1024 +export { MESSAGE_LIMIT } from "../session-media-contract" export const cursorSchema = z.object({ binding: z.string().length(64), through: z.number().int().min(0), sequence: z.number().int().min(0), offset: z.number().int().min(0).max(100000) }).strict() export const hash = (value: string) => createHash("sha256").update(value).digest("hex") diff --git a/packages/server/src/opencode/subagent-depth-settings.test.ts b/packages/server/src/opencode/subagent-depth-settings.test.ts index 98d3a35780..a4f4ddaa23 100644 --- a/packages/server/src/opencode/subagent-depth-settings.test.ts +++ b/packages/server/src/opencode/subagent-depth-settings.test.ts @@ -46,6 +46,7 @@ test("owned depth editing preserves JSONC, inherited settings and original draft plugin: { list: async () => ({ data: [] }) } }, } const manager: any = { + requireWorkspaceCapability: () => new AbortController().signal, get: () => ({}), getSharedServiceConnection: async () => connection, getServiceDirectoryForPath: async (_id: string, directory: string) => directory === project ? directory : undefined, ownsLocation: async () => owned, getWorktreeIdentityForPath: async () => "owned", @@ -164,6 +165,7 @@ async function nestingFixture(run: (fixture: { } } }, } const manager: any = { + requireWorkspaceCapability: () => new AbortController().signal, get: () => ({}), getSharedServiceConnection: async () => connection, getServiceDirectoryForPath: async (_id: string, directory: string) => directory === project ? directory : undefined, ownsLocation: async () => true, getWorktreeIdentityForPath: async () => "owned", @@ -337,7 +339,7 @@ test("depth origin follows the effective native block, including ancestor, pathl [[global, { type: "document", info: { experimental: { subagent_depth: 0 } } }], null, 0], ] as const) { const settings = new SubagentDepthSettings({ readConfigDocuments: async () => ({ location: { directory: "/project" }, entries, documents: [] }) } as any, - { getServicePathStyle: () => "posix", getSharedServiceConnection: async () => ({ assertCurrent: () => {}, endpoint: { url: "http://127.0.0.1:1234" }, + { requireWorkspaceCapability: () => new AbortController().signal, getServicePathStyle: () => "posix", getSharedServiceConnection: async () => ({ assertCurrent: () => {}, endpoint: { url: "http://127.0.0.1:1234" }, fetch: async () => Response.json(contract({ type: "integer", minimum: 0, default: 1 })) }) } as any) const snapshot = await settings.read("w", { directory: "/project" }) assert.equal(snapshot.origin, expectedOrigin) @@ -367,6 +369,7 @@ test("Inherit removes a block left with only the Global image storage, only when plugin: { list: async () => ({ data: [] }) } }, } const manager: any = { + requireWorkspaceCapability: () => new AbortController().signal, get: () => ({}), getSharedServiceConnection: async () => connection, getServiceDirectoryForPath: async (_id: string, directory: string) => directory === project ? directory : undefined, ownsLocation: async () => true, getWorktreeIdentityForPath: async () => "owned", diff --git a/packages/server/src/opencode/subagent-depth-settings.ts b/packages/server/src/opencode/subagent-depth-settings.ts index 1874957cdd..1991e416b9 100644 --- a/packages/server/src/opencode/subagent-depth-settings.ts +++ b/packages/server/src/opencode/subagent-depth-settings.ts @@ -56,9 +56,14 @@ async function generalRules(connection: ServiceConnection, directory: string) { * General subagent launch subagents; never reloads Locations. */ export class SubagentDepthSettings { constructor(private readonly documents: Pick, - private readonly manager: Pick) {} + private readonly manager: Pick) {} private async context(workspaceId: string, location: PluginControlLocation) { + try { this.manager.requireWorkspaceCapability(workspaceId, "executionSettings") } + catch (error) { + if (error instanceof Error && "statusCode" in error && error.statusCode === 404) throw new PluginControlsError("Workspace not found", "not-found") + throw error + } const connection = await this.manager.getSharedServiceConnection(workspaceId) if (!connection) throw new PluginControlsError("OpenCode is unavailable", "unavailable") // Document acquisition proves directory ownership before the schema request. diff --git a/packages/server/src/opencode/websearch-settings.test.ts b/packages/server/src/opencode/websearch-settings.test.ts index 96d90d54e6..26fc623cc4 100644 --- a/packages/server/src/opencode/websearch-settings.test.ts +++ b/packages/server/src/opencode/websearch-settings.test.ts @@ -25,6 +25,7 @@ test("web settings retain foreign fields and comments; scopes, reset and shared plugin: { list: async () => ({ data: [] }) }, } } const controls = new PluginControls({ workspaceManager: { + requireWorkspaceCapability: () => new AbortController().signal, get: () => ({}), getSharedServiceConnection: async () => connection, getServiceDirectoryForPath: async (_id: string, directory: string) => directory === project ? directory : undefined, ownsLocation: async () => owned, getWorktreeIdentityForPath: async () => "owned", diff --git a/packages/server/src/permissions/auto-accept-capabilities.test.ts b/packages/server/src/permissions/auto-accept-capabilities.test.ts new file mode 100644 index 0000000000..62135817ec --- /dev/null +++ b/packages/server/src/permissions/auto-accept-capabilities.test.ts @@ -0,0 +1,82 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import Fastify from "fastify" +import type { OpenCodeClient } from "@opencode/client" +import { EventBus } from "../events/bus" +import type { Logger } from "../logger" +import { WorkspaceCapabilityError } from "../opencode/servers/capabilities" +import type { SettingsService } from "../settings/service" +import type { WorkspaceManager } from "../workspaces/manager" +import { registerYoloRoutes } from "../server/routes/yolo" +import { AutoAcceptManager } from "./auto-accept-manager" +import { createOpencodeYoloPersistence } from "./opencode-yolo-metadata" + +test("Yolo routes, persistence and automatic events refuse A/B before colliding local state or native calls", async () => { + const effects: string[] = [] + const logger = { warn() {}, error() {}, debug() {}, info() {}, trace() {}, isLevelEnabled: () => false } as unknown as Logger + const bus = new EventBus(logger) + const workspaceManager = { + requireWorkspaceCapability(id: string, capability: string) { + assert.equal(capability, "yolo") + if (id !== "local") throw new WorkspaceCapabilityError("yolo", { code: "deferred" }) + return new AbortController().signal + }, + get: () => ({ path: "/same" }), + getServiceDirectory: () => "/same", + ownsDirectory: async () => true, + } as unknown as WorkspaceManager + let enabled = true + const settings = { + getOwner: () => { effects.push("state.read"); return { sessions: { same: { yoloEnabled: enabled } } } }, + mergePatchOwner: (_kind: string, _owner: string, patch: { sessions: { same: { yoloEnabled: boolean } } }) => { + effects.push("state.write") + enabled = patch.sessions.same.yoloEnabled + }, + } as unknown as SettingsService + const session = { id: "same", location: { directory: "/same" } } + const client = { session: { + list: async () => { effects.push("native.list"); return { data: [session], cursor: {} } }, + get: async () => { effects.push("native.get"); return session }, + } } as unknown as OpenCodeClient + const persistence = createOpencodeYoloPersistence(workspaceManager, settings, async () => { + effects.push("acquire") + return client + }) + const manager = new AutoAcceptManager({ eventBus: bus, logger, persistence, replier: async ({ instanceId }) => { effects.push(`reply.${instanceId}`) } }) + manager.start() + const app = Fastify() + registerYoloRoutes(app, { yoloManager: manager }) + try { + for (const id of ["A", "B"]) { + for (const [method, suffix] of [["GET", ""], ["POST", "/toggle"]] as const) { + const response = await app.inject({ method, url: `/workspaces/${id}/yolo/sessions/same${suffix}` }) + assert.equal(response.statusCode, 403) + assert.deepEqual(response.json(), { error: "explicit_capability_unavailable", code: "explicit_capability_unavailable", capability: "yolo", reason: { code: "deferred" } }) + } + await assert.rejects(persistence.loadSessions(id), WorkspaceCapabilityError) + await assert.rejects(persistence.loadSession!(id, "same"), WorkspaceCapabilityError) + assert.throws(() => persistence.persist(id, "same", true), WorkspaceCapabilityError) + assert.throws(() => manager.toggle(id, "same"), WorkspaceCapabilityError) + bus.publish({ type: "workspace.started", workspace: { id } } as never) + for (const event of [ + { type: "session.created", data: { sessionID: "same" } }, + { type: "permission.asked", data: { id: "same-permission", sessionID: "same" } }, + ]) { + bus.publish({ type: "instance.event", instanceId: id, event } as never) + manager.handleInstanceEvent(id, event) + } + } + await new Promise(resolve => setImmediate(resolve)) + assert.equal(effects.length, 0) + assert.equal((await app.inject("/workspaces/local/yolo/sessions/same")).json().enabled, true) + bus.publish({ type: "instance.event", instanceId: "local", event: { + type: "permission.asked", data: { id: "same-permission", sessionID: "same" }, + } } as never) + await new Promise(resolve => setImmediate(resolve)) + assert.ok(effects.includes("reply.local")) + assert.equal((await app.inject({ method: "POST", url: "/workspaces/local/yolo/sessions/same/toggle" })).json().enabled, false) + } finally { + manager.stop() + await app.close() + } +}) diff --git a/packages/server/src/permissions/auto-accept-manager.ts b/packages/server/src/permissions/auto-accept-manager.ts index 59d109c34e..9d38ed4faa 100644 --- a/packages/server/src/permissions/auto-accept-manager.ts +++ b/packages/server/src/permissions/auto-accept-manager.ts @@ -41,11 +41,17 @@ export interface PersistedAutoAcceptSession extends AutoAcceptSessionInfo { } export interface AutoAcceptPersistence { + requireCapability?(instanceId: string): void loadSessions(instanceId: string): Promise loadSession?(instanceId: string, sessionId: string): Promise persist(instanceId: string, rootSessionId: string, enabled: boolean): Promise + /** prototype-1236: pending permission IDs of one session, read after a reconnect; [] when not applicable. */ + listPendingPermissions?(instanceId: string, sessionId: string): Promise } +/** prototype-1236: bounded reconnect re-read, Yolo sessions only. */ +const MAX_RECOVERED_SESSIONS = 50 + export class AutoAcceptManager { private static readonly MAX_REPLY_ATTEMPTS = 3 private readonly store = new AutoAcceptStore() @@ -68,6 +74,7 @@ export class AutoAcceptManager { if (this.unsubscribe) return const handler = (payload: { instanceId?: string; event?: InstanceStreamPayload }) => { if (!payload || !payload.instanceId || !payload.event) return + if (!this.admitted(payload.instanceId)) return if (this.deps.persistence && !this.hydratedInstances.has(payload.instanceId)) { const queued = this.queuedEvents.get(payload.instanceId) ?? [] queued.push(payload.event) @@ -82,6 +89,7 @@ export class AutoAcceptManager { const onStarted = (event: { workspace?: { id?: string } }) => { const instanceId = event.workspace?.id if (!instanceId) return + if (!this.admitted(instanceId)) return void this.hydrateInstance(instanceId).catch((error) => { this.deps.logger.warn({ instanceId, err: error }, "Failed to hydrate persisted Yolo state") }) @@ -92,12 +100,20 @@ export class AutoAcceptManager { const onError = (event: { workspace?: { id?: string } }) => { if (event?.workspace?.id) this.clearInstance(event.workspace.id) } + const onStatus = (event: { instanceId?: string; status?: string }) => { + if (event?.status !== "connected" || !event.instanceId || !this.admitted(event.instanceId)) return + void this.recoverPending(event.instanceId).catch((error) => { + this.deps.logger.warn({ instanceId: event.instanceId, err: error }, "Failed to re-read Yolo permissions after reconnect") + }) + } this.deps.eventBus.on("instance.event", handler) + this.deps.eventBus.on("instance.eventStatus", onStatus) this.deps.eventBus.on("workspace.started", onStarted) this.deps.eventBus.on("workspace.stopped", onStopped) this.deps.eventBus.on("workspace.error", onError) this.unsubscribe = () => { this.deps.eventBus.off("instance.event", handler) + this.deps.eventBus.off("instance.eventStatus", onStatus) this.deps.eventBus.off("workspace.started", onStarted) this.deps.eventBus.off("workspace.stopped", onStopped) this.deps.eventBus.off("workspace.error", onError) @@ -110,10 +126,26 @@ export class AutoAcceptManager { } isEnabled(instanceId: string, sessionId: string): boolean { + this.requireCapability(instanceId) return this.store.isEnabled(instanceId, sessionId) } + requireCapability(instanceId: string): void { + this.deps.persistence?.requireCapability?.(instanceId) + } + + private admitted(instanceId: string): boolean { + try { + this.requireCapability(instanceId) + return true + } catch { + this.clearInstance(instanceId) + return false + } + } + hydrateInstance(instanceId: string): Promise { + this.requireCapability(instanceId) if (!this.deps.persistence || this.hydratedInstances.has(instanceId)) return Promise.resolve() const existing = this.hydration.get(instanceId) if (existing) return existing @@ -146,6 +178,7 @@ export class AutoAcceptManager { } toggle(instanceId: string, sessionId: string): boolean | Promise { + this.requireCapability(instanceId) if (this.deps.persistence) return this.togglePersisted(instanceId, sessionId) const enabled = this.store.toggle(instanceId, sessionId) this.deps.eventBus.publish({ type: "yolo.stateChanged", instanceId, sessionId, enabled }) @@ -219,6 +252,20 @@ export class AutoAcceptManager { return settled } + /** prototype-1236 (Q2): permissions asked while a live-only stream was down, for Yolo sessions only. */ + async recoverPending(instanceId: string): Promise { + const list = this.deps.persistence?.listPendingPermissions + if (!list) return + await this.hydrateInstance(instanceId) + const generation = this.instanceGeneration.get(instanceId) ?? 0 + const sessions = this.store.sessionIds(instanceId).filter(sessionId => this.store.isEnabled(instanceId, sessionId)).slice(0, MAX_RECOVERED_SESSIONS) + for (const sessionId of sessions) { + const permissionIds = await list.call(this.deps.persistence, instanceId, sessionId) + if ((this.instanceGeneration.get(instanceId) ?? 0) !== generation || !this.admitted(instanceId)) return + for (const permissionId of permissionIds) this.handlePermissionRequest(instanceId, { id: permissionId, sessionID: sessionId }) + } + } + clearInstance(instanceId: string): void { this.instanceGeneration.set(instanceId, (this.instanceGeneration.get(instanceId) ?? 0) + 1) this.hydratedInstances.delete(instanceId) @@ -230,6 +277,7 @@ export class AutoAcceptManager { } handleInstanceEvent(instanceId: string, event: InstanceStreamPayload): void { + if (!this.admitted(instanceId)) return if (!event || typeof event.type !== "string") return if (event.type === "session.created") { @@ -369,6 +417,7 @@ export class AutoAcceptManager { permissionId: string, sessionId: string, ): void { + if (!this.admitted(instanceId)) return const key = permissionId if (this.inFlight.has(key)) return const attempts = this.replyAttempts.get(key) ?? 0 diff --git a/packages/server/src/permissions/auto-accept-store.ts b/packages/server/src/permissions/auto-accept-store.ts index 500b86c44e..1f00ce1ec4 100644 --- a/packages/server/src/permissions/auto-accept-store.ts +++ b/packages/server/src/permissions/auto-accept-store.ts @@ -111,6 +111,10 @@ export class AutoAcceptStore { return resolveFamilyRoot(sessionId, (id) => tree?.get(id)) } + sessionIds(instanceId: string): string[] { + return [...(this.sessions.get(instanceId)?.keys() ?? [])] + } + enabledRoots(instanceId: string): string[] { return [...(this.enabled.get(instanceId) ?? [])] } diff --git a/packages/server/src/permissions/opencode-replier.test.ts b/packages/server/src/permissions/opencode-replier.test.ts index cda5a4cd4a..194088885d 100644 --- a/packages/server/src/permissions/opencode-replier.test.ts +++ b/packages/server/src/permissions/opencode-replier.test.ts @@ -4,6 +4,8 @@ import type { OpenCodeClient } from "@opencode/client" import type { WorkspaceManager } from "../workspaces/manager" import { createOpencodePermissionReplier } from "./opencode-replier" +import { WorkspaceCapabilityError } from "../opencode/servers/capabilities" +import type { PermissionReceipts } from "./receipts" describe("createOpencodePermissionReplier", () => { it("does not reply across logical workspace ownership", async () => { @@ -13,8 +15,9 @@ describe("createOpencodePermissionReplier", () => { permission: { reply: async (input: Record) => { calls.push(input) } }, } as unknown as OpenCodeClient const workspaceManager = { + requireWorkspaceCapability: () => new AbortController().signal, get: () => ({ path: "/repo" }), - getSharedServiceClient: async () => client, + getSharedServiceConnection: async () => ({ client }), ownsLocation: async () => false, } as unknown as WorkspaceManager const replier = createOpencodePermissionReplier({ workspaceManager }) @@ -26,4 +29,70 @@ describe("createOpencodePermissionReplier", () => { }), /does not belong/) assert.deepEqual(calls, []) }) + + it("refuses explicit A/B before either client acquisition path while local identical IDs still reply", async () => { + const effects: string[] = [] + const client = { + session: { get: async () => { effects.push("get"); return { location: { directory: "/same" } } } }, + permission: { reply: async () => { effects.push("reply") } }, + } as unknown as OpenCodeClient + const workspaceManager = { + requireWorkspaceCapability(id: string, capability: string) { + assert.equal(capability, "yolo") + if (id !== "local") throw new WorkspaceCapabilityError("yolo", { code: "deferred" }) + return new AbortController().signal + }, + getSharedServiceConnection: async () => { + effects.push("acquire") + return { client, assertCurrent() {} } + }, + ownsLocation: async () => true, + } as unknown as WorkspaceManager + const permissionReceipts = { prepare: async () => { effects.push("prepare") } } as unknown as PermissionReceipts + for (const receipts of [undefined, permissionReceipts]) { + const replier = createOpencodePermissionReplier({ workspaceManager, permissionReceipts: receipts }) + for (const instanceId of ["A", "B"]) { + await assert.rejects(replier({ instanceId, sessionId: "same", permissionId: "same" }), WorkspaceCapabilityError) + } + assert.deepEqual(effects, []) + await replier({ instanceId: "local", sessionId: "same", permissionId: "same" }) + assert.equal(effects.filter(effect => effect === "reply").length, 1) + effects.length = 0 + } + }) + + it("rechecks admission before dispatch without classifying a refusal as a dispatched failure", async () => { + let admitted = true + let replies = 0 + const client = { + session: { get: async () => ({ location: { directory: "/same" } }) }, + permission: { reply: async () => { replies++ } }, + } as unknown as OpenCodeClient + const workspaceManager = { + requireWorkspaceCapability() { + if (!admitted) throw new WorkspaceCapabilityError("yolo", { code: "deferred" }) + return new AbortController().signal + }, + getSharedServiceConnection: async () => ({ client }), + ownsLocation: async () => { admitted = false; return true }, + } as unknown as WorkspaceManager + const replier = createOpencodePermissionReplier({ workspaceManager }) + await assert.rejects(replier({ instanceId: "local", sessionId: "same", permissionId: "same" }), + (error: unknown) => error instanceof WorkspaceCapabilityError && !("retryable" in error)) + assert.equal(replies, 0) + }) + + it("keeps a lost dispatched reply non-retryable", async () => { + const client = { + session: { get: async () => ({ location: { directory: "/same" } }) }, + permission: { reply: async () => { throw new Error("lost response") } }, + } as unknown as OpenCodeClient + const workspaceManager = { + requireWorkspaceCapability: () => new AbortController().signal, + getSharedServiceConnection: async () => ({ client }), + ownsLocation: async () => true, + } as unknown as WorkspaceManager + const replier = createOpencodePermissionReplier({ workspaceManager }) + await assert.rejects(replier({ instanceId: "local", sessionId: "same", permissionId: "same" }), { retryable: false }) + }) }) diff --git a/packages/server/src/permissions/opencode-replier.ts b/packages/server/src/permissions/opencode-replier.ts index 2e8f1772fe..3431b9c8dd 100644 --- a/packages/server/src/permissions/opencode-replier.ts +++ b/packages/server/src/permissions/opencode-replier.ts @@ -14,20 +14,27 @@ interface OpencodeReplierDeps { */ export function createOpencodePermissionReplier(deps: OpencodeReplierDeps): PermissionReplier { return async (reply: AutoAcceptReply) => { - const connection = deps.permissionReceipts ? await deps.workspaceManager.getSharedServiceConnection(reply.instanceId) : undefined + const signal = deps.workspaceManager.requireWorkspaceCapability(reply.instanceId, "yolo") + // prototype-1236: an explicit server replies on its own connection; receipts stay a local history feature. + const receipts = deps.workspaceManager.isExplicitWorkspace?.(reply.instanceId) ? undefined : deps.permissionReceipts + const connection = receipts ? await deps.workspaceManager.getSharedServiceConnection(reply.instanceId) : undefined const client = connection?.client ?? await createInstanceClient(deps.workspaceManager, reply.instanceId) if (!client) { throw new Error(`Yolo: instance ${reply.instanceId} is not ready`) } + signal.throwIfAborted() const session = await client.session.get({ sessionID: reply.sessionId }) if (!(await deps.workspaceManager.ownsLocation(reply.instanceId, session.location))) { throw new Error(`Yolo: session ${reply.sessionId} does not belong to workspace ${reply.instanceId}`) } - const confirm = connection && await deps.permissionReceipts?.prepare(reply.instanceId, connection, + signal.throwIfAborted() + const confirm = connection && await receipts?.prepare(reply.instanceId, connection, reply.sessionId, reply.permissionId, "once", "yolo") connection?.assertCurrent() + signal.throwIfAborted() + deps.workspaceManager.requireWorkspaceCapability(reply.instanceId, "yolo") try { await client.permission.reply({ sessionID: reply.sessionId, diff --git a/packages/server/src/permissions/opencode-yolo-metadata.test.ts b/packages/server/src/permissions/opencode-yolo-metadata.test.ts index 8ae93d19c2..b2651d9267 100644 --- a/packages/server/src/permissions/opencode-yolo-metadata.test.ts +++ b/packages/server/src/permissions/opencode-yolo-metadata.test.ts @@ -20,6 +20,7 @@ function createHarness(serviceDirectory = "/repo") { } as unknown as SettingsService const listInputs: Record[] = [] const workspaceManager = { + requireWorkspaceCapability() { return new AbortController().signal }, get: () => ({ path: "/repo" }), getServiceDirectory: () => serviceDirectory, ownsDirectory: async (_instanceId: string, directory: string) => directory === "/repo" || directory === "/worktree", diff --git a/packages/server/src/permissions/opencode-yolo-metadata.ts b/packages/server/src/permissions/opencode-yolo-metadata.ts index 80b7a4bfb3..e9834a4edd 100644 --- a/packages/server/src/permissions/opencode-yolo-metadata.ts +++ b/packages/server/src/permissions/opencode-yolo-metadata.ts @@ -35,7 +35,9 @@ export function createOpencodeYoloPersistence( createClient: (manager: WorkspaceManager, instanceId: string) => Promise = createInstanceClient, ): OpencodeYoloPersistence { const writes = new Map>() + const requireCapability = (instanceId: string) => { workspaceManager.requireWorkspaceCapability(instanceId, "yolo") } const clientFor = async (instanceId: string) => { + requireCapability(instanceId) const client = await createClient(workspaceManager, instanceId) if (!client) throw new Error(`Yolo: instance ${instanceId} is not ready`) return client @@ -52,6 +54,7 @@ export function createOpencodeYoloPersistence( const page = await client.session.list(cursor ? { cursor } : { directory, limit: SESSION_LIST_LIMIT }) + requireCapability(instanceId) sessions.push(...page.data) cursor = page.cursor.next ?? undefined } while (cursor) @@ -64,10 +67,12 @@ export function createOpencodeYoloPersistence( yoloEnabled: sessionState(settings, session.id).yoloEnabled === true, }) const updateYolo = ( + instanceId: string, sessionId: string, enabled: boolean, ): Promise => { const write = (writes.get(sessionId) ?? Promise.resolve()).catch(() => undefined).then(() => { + requireCapability(instanceId) const next = { ...sessionState(settings, sessionId), yoloEnabled: enabled } settings.mergePatchOwner("state", STATE_OWNER, { sessions: { [sessionId]: next } }) }) @@ -79,9 +84,12 @@ export function createOpencodeYoloPersistence( } return { + requireCapability, async loadSessions(instanceId): Promise { + requireCapability(instanceId) const client = await clientFor(instanceId) const sessions = new Map((await listSessions(instanceId)).map((session) => [session.id, session])) + requireCapability(instanceId) await Promise.all(enabledSessionIds(settings).map(async (sessionId) => { if (sessions.has(sessionId)) return try { @@ -91,22 +99,40 @@ export function createOpencodeYoloPersistence( // Stale persisted IDs are harmless and may belong to a stopped workspace. } })) - const owned = await Promise.all(Array.from(sessions.values()).map(async (session) => ( - await workspaceManager.ownsDirectory(instanceId, session.location.directory) ? persistedSession(session) : null - ))) + const owned = await Promise.all(Array.from(sessions.values()).map(async (session) => { + if (!(await workspaceManager.ownsDirectory(instanceId, session.location.directory))) return null + requireCapability(instanceId) + return persistedSession(session) + })) + requireCapability(instanceId) return owned.filter((session): session is PersistedAutoAcceptSession => session !== null) }, async loadSession(instanceId, sessionId): Promise { + requireCapability(instanceId) try { const session = await (await clientFor(instanceId)).session.get({ sessionID: sessionId }) if (!(await workspaceManager.ownsDirectory(instanceId, session.location.directory))) return null + requireCapability(instanceId) return persistedSession(session) } catch { return null } }, - persist(_instanceId, rootSessionId, enabled): Promise { - return updateYolo(rootSessionId, enabled) + persist(instanceId, rootSessionId, enabled): Promise { + requireCapability(instanceId) + return updateYolo(instanceId, rootSessionId, enabled) + }, + // prototype-1236 (Q2): an explicit server's event stream is live-only. After a reconnect, re-read the + // pending permissions of the Yolo sessions only; local projects keep their own recovery. + async listPendingPermissions(instanceId, sessionId) { + requireCapability(instanceId) + if (!workspaceManager.isExplicitWorkspace?.(instanceId)) return [] + const client = await clientFor(instanceId) + const session = await client.session.get({ sessionID: sessionId }) + if (!(await workspaceManager.ownsDirectory(instanceId, session.location.directory))) return [] + const pending = await client.permission.list({ sessionID: sessionId }, { signal: AbortSignal.timeout(10_000) }) + requireCapability(instanceId) + return pending.flatMap(request => typeof request?.id === "string" && request.sessionID === sessionId ? [request.id] : []) }, } } diff --git a/packages/server/src/permissions/receipts.test.ts b/packages/server/src/permissions/receipts.test.ts index 00a42c22ea..cea7663f9b 100644 --- a/packages/server/src/permissions/receipts.test.ts +++ b/packages/server/src/permissions/receipts.test.ts @@ -18,8 +18,27 @@ import { registerPermissionReceiptRoutes } from "../server/routes/permission-rec import { registerInstanceProxyRoutes } from "../server/http-server" import { WorktreeDeletionFence } from "../workspaces/worktree-session-evacuation" import { CODENOMAD_MISSIONS_RPC } from "../missions/rpc" +import { WorkspaceCapabilityError } from "../opencode/servers/capabilities" const logger = { error() {}, warn() {}, debug() {}, trace() {}, isLevelEnabled: () => false } as unknown as Logger + +test("explicit reconnect receipt recovery does not enumerate or acquire while manual/live admission stays separate", async t => { + const bus = new EventBus(), effects: string[] = [] + const forbidden = () => { effects.push("local/native"); throw new Error("Forbidden") } + const manager = { + get: (id: string) => ({ id, path: "/same", binding: { serverId: id, directory: "/same" } }), + requireWorkspaceCapability: (_id: string, capability: string) => { + assert.equal(capability, "pendingRecovery") + throw new WorkspaceCapabilityError("pendingRecovery", { code: "liveOnly" }) + }, + getSharedServiceConnection: forbidden, getServiceWslDistro: forbidden, getServicePathStyle: forbidden, ownsLocation: forbidden, + } as unknown as WorkspaceManager + const receipts = new PermissionReceipts({ capture: forbidden } as never, manager, bus, logger) + receipts.start(); t.after(() => receipts.stop()) + for (const instanceId of ["A", "B"]) bus.publish({ type: "instance.eventStatus", instanceId, status: "connected", generation: 1 }) + await receipts.stop() + assert.deepEqual(effects, []) +}) const pending = (id = "p", source = true) => ({ id, sessionID: "s", action: "shell", resources: ["git status"], message: "Inspect repository", metadata: { secret: "never-persist", diff: "FULL DIFF" }, ...(source ? { source: { type: "tool", messageID: "m", id: "call" } } : {}) }) @@ -52,6 +71,7 @@ async function fixture() { assertCurrent: () => { if (!state.current) throw new Error("stale connection") }, } as unknown as ServiceConnection const manager = { + requireWorkspaceCapability: () => new AbortController().signal, get: () => workspace, getSharedServiceConnection: async () => connection, getServiceWslDistro: () => state.distro, @@ -311,7 +331,7 @@ test("authenticated native channels and WSL hosts isolate identical session/requ await (await f.receipts.prepare("w", f.connection, "s", "p", "once", "codenomad"))() const otherConnection = { ...f.connection, endpoint: { ...f.connection.endpoint, auth: { type: "basic" as const, username: "opencode", password: "other-native-channel" } } } - const manager = { get: f.manager.get, ownsLocation: f.manager.ownsLocation, + const manager = { get: f.manager.get, ownsLocation: f.manager.ownsLocation, requireWorkspaceCapability: f.manager.requireWorkspaceCapability, getServiceWslDistro: f.manager.getServiceWslDistro, getServicePathStyle: f.manager.getServicePathStyle, getSharedServiceConnection: f.manager.getSharedServiceConnection } const otherManager = { ...manager, getSharedServiceConnection: async () => otherConnection } diff --git a/packages/server/src/permissions/receipts.ts b/packages/server/src/permissions/receipts.ts index 8184a88f10..abfdceb553 100644 --- a/packages/server/src/permissions/receipts.ts +++ b/packages/server/src/permissions/receipts.ts @@ -9,7 +9,7 @@ import { nativeEventConnections } from "../workspaces/opencode-service" import { locationRequestOptions, readLocationRef } from "../opencode/compatibility/location" import { PermissionReceiptStore, permissionSnapshot, receiptHash, type ReceiptQuery } from "./receipt-store" -type Manager = Pick +type Manager = Pick type InstanceEvent = Extract export class PermissionReceipts { private readonly scopes = new WeakMap>() @@ -26,6 +26,7 @@ export class PermissionReceipts { await Promise.allSettled(this.confirmations) } private scope(instanceId: string, connection: ServiceConnection): Promise { + this.manager.requireWorkspaceCapability(instanceId, "historyEnrichment") let pending = this.scopes.get(connection) if (!pending) { const distro = this.manager.getServiceWslDistro(instanceId)?.toLowerCase() @@ -70,6 +71,8 @@ export class PermissionReceipts { const event = payload.event as { type?: string; data?: any; created?: number } if (!event || !["permission.asked", "permission.replied", "session.deleted"].includes(event.type ?? "")) return const { instanceId } = payload + try { this.manager.requireWorkspaceCapability(instanceId, "historyEnrichment") } + catch { return } // Acquire while the ownership-validated event is delivered; stale connections // fail their fence rather than being reassigned to a replacement daemon. const connection = nativeEventConnections.get(payload.event) @@ -78,6 +81,7 @@ export class PermissionReceipts { void scope.catch(() => {}) const request = event.type === "permission.asked" ? permissionSnapshot(event.data) : undefined this.enqueue(instanceId, async () => { + this.manager.requireWorkspaceCapability(instanceId, "historyEnrichment") const identity = await scope if (request) { this.observe(instanceId, identity, request.sessionId) @@ -100,7 +104,12 @@ export class PermissionReceipts { if (event.status !== "connected") return const workspace = this.manager.get(event.instanceId) if (!workspace) return + // Reconnect enumeration requires recovery admission independently of live + // receipt capture and exact, manually submitted permission replies. + try { this.manager.requireWorkspaceCapability(event.instanceId, "pendingRecovery") } + catch { return } this.enqueue(event.instanceId, async () => { + this.manager.requireWorkspaceCapability(event.instanceId, "pendingRecovery") const connection = await this.manager.getSharedServiceConnection(event.instanceId) if (!connection) return const current = () => { @@ -174,6 +183,7 @@ export class PermissionReceipts { } } async list(instanceId: string, sessionId: string, query: ReceiptQuery) { + this.manager.requireWorkspaceCapability(instanceId, "historyEnrichment") const workspace = this.manager.get(instanceId) if (!workspace) throw Object.assign(new Error("Workspace not found"), { statusCode: 404 }) const connection = await this.manager.getSharedServiceConnection(instanceId) diff --git a/packages/server/src/provider-accounts/quota-observer.ts b/packages/server/src/provider-accounts/quota-observer.ts index 3e8869e475..7b570e3e2e 100644 --- a/packages/server/src/provider-accounts/quota-observer.ts +++ b/packages/server/src/provider-accounts/quota-observer.ts @@ -47,10 +47,13 @@ export function observeProviderQuotaFailures(bus: EventBus, accounts: Pick { + if (payload.source && payload.source.serverId !== "local-shared") return const event = payload.event as { id?: unknown; type?: unknown; created?: unknown; data?: any } if (event?.type !== "credential.switched" && event?.type !== "session.step.started" && event?.type !== "session.step.failed" && event?.type !== "session.execution.failed") return const connection = nativeEventConnections.get(payload.event) + const serverId = (connection as { serverId?: string } | undefined)?.serverId + if (serverId && serverId !== "local-shared") return // Every owned workspace receives the same native event object. if (!connection || !once(event.id)) return const created = typeof event.created === "number" && Number.isFinite(event.created) ? event.created : Date.now() diff --git a/packages/server/src/remote-control/gate.ts b/packages/server/src/remote-control/gate.ts index b7453f77d6..d7d06f6191 100644 --- a/packages/server/src/remote-control/gate.ts +++ b/packages/server/src/remote-control/gate.ts @@ -19,7 +19,7 @@ const PUBLIC_PATHS = new Set([PAIR_PAGE_PATH, PAIR_EXCHANGE_PATH, "/api/auth/sta // windows, local tools and the automation bridge. Never reachable remotely, except // web previews through their capability token while the host allows them. const LOCAL_ONLY_PATHS = new Set(["/login", "/api/auth/login", "/api/auth/token", "/api/auth/password", "/api/auth/logout"]) -const LOCAL_ONLY_PREFIXES = ["/auth/", "/api/remote-control/", "/api/remote-proxy/", "/api/remote-servers/", "/api/opencode-plugin/", "/sidecars/", "/previews/"] +const LOCAL_ONLY_PREFIXES = ["/auth/", "/api/remote-control/", "/api/remote-proxy/", "/api/remote-servers/", "/api/opencode-servers/", "/api/opencode-plugin/", "/sidecars/", "/previews/"] const REMOTE_MANAGEMENT_READS = new Set(["/api/remote-control/status"]) // Client-supplied routing or authority metadata is never trusted on the remote surface. const SPOOFABLE_HEADERS = ["forwarded", "x-forwarded-for", "x-forwarded-host", "x-forwarded-proto", "x-real-ip", "x-codenomad-remote-control"] diff --git a/packages/server/src/remote-control/remote-surface.test.ts b/packages/server/src/remote-control/remote-surface.test.ts index 60ee827f25..6bced20514 100644 --- a/packages/server/src/remote-control/remote-surface.test.ts +++ b/packages/server/src/remote-control/remote-surface.test.ts @@ -4,6 +4,11 @@ import http from "node:http" import net from "node:net" import test, { type TestContext } from "node:test" import { FAKE_TUNNEL_HOST, startRemoteSurface } from "./test-support/surface" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { SettingsService } from "../settings/service" +import { resolveConfigLocation } from "../config/location" const HOST = FAKE_TUNNEL_HOST const ORIGIN = `https://${HOST}` @@ -43,6 +48,68 @@ async function pair(target: string, code: string): Promise { return cookie.split(";")[0]! } +test("paired devices cannot write the OpenCode registry through either generic PATCH surface", async t => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "codenomad-remote-registry-")) + t.after(() => fs.rmSync(directory, { recursive: true, force: true })) + const location = resolveConfigLocation(path.join(directory, "config.yaml")) + const events: unknown[] = [] + const logger = { child: () => logger, info() {}, warn() {} } + const settings = new SettingsService(location, { publish: (value: unknown) => events.push(value) } as never, logger as never) + settings.mergePatchDoc("config", { server: { logLevel: "INFO" }, ui: { theme: "light" } }) + const { target, code } = await startRemoteSurface(t, { settings }) + const cookie = await pair(target(), code) + const headers = { cookie, origin: ORIGIN, "content-type": "application/json" } + const profiles = [{ kind: "explicit", id: "remote", label: "Remote", origin: "https://example.test" }] + const legacyFile = fs.readFileSync(location.configYamlPath, "utf8") + const legacyEvents = events.length + for (const [url, body] of [["/api/storage/config", { server: { opencodeServers: profiles } }], + ["/api/storage/config/server", { opencodeServers: profiles }]] as const) { + assert.equal((await send(target(), url, { method: "PATCH", headers, body: JSON.stringify(body) })).status, 400) + assert.equal(fs.readFileSync(location.configYamlPath, "utf8"), legacyFile) + assert.equal(events.length, legacyEvents) + } + for (const existing of [[], profiles]) { + settings.getOpenCodeServerRegistry().replace(existing) + const before = fs.readFileSync(location.configYamlPath, "utf8") + const eventCount = events.length + for (const patch of [{ opencodeServers: profiles }, { opencodeServers: [{ ...profiles[0], credentialRef: "rotation" }] }, + { opencodeServers: null }, { opencodeServers: [] }, { opencodeServers: {} }, + { opencodeServers: [], logLevel: "ERROR" }, null, [], "replace"]) { + for (const [url, body] of [ + ["/api/storage/config", { server: patch, ui: { theme: "dark" } }], + ["/api/storage/config/server", patch], + ["/%61pi/storage/config", { server: patch }], + ["/api/storage/config/%73erver", patch], + ["/api/storage/config/server?conditional=missions-v1", patch], + ["/api/storage/config/%73erver?conditional=other", patch], + ["/api/storage/config/ui?conditional=missions-v1", { patch: { server: patch }, expected: [] }], + ] as const) { + const response = await send(target(), url, { method: "PATCH", headers, body: JSON.stringify(body) }) + assert.equal(response.status, 400, `${url}: ${response.body}`) + assert.equal(fs.readFileSync(location.configYamlPath, "utf8"), before) + assert.equal(events.length, eventCount) + } + } + for (const body of [null, [], "replace"]) { + const response = await send(target(), "/api/storage/config", { method: "PATCH", headers, body: JSON.stringify(body) }) + assert.equal(response.status, 400) + assert.equal(fs.readFileSync(location.configYamlPath, "utf8"), before) + assert.equal(events.length, eventCount) + } + for (const [url, body] of [["/api/storage/config", { server: { logLevel: "WARN" } }], + ["/api/storage/config/server", { logLevel: "INFO" }]] as const) { + const response = await send(target(), url, { method: "PATCH", headers, body: JSON.stringify(body) }) + assert.equal(response.status, 200, response.body) + assert.doesNotMatch(response.body, /sentinel-reference|credentialRef/) + assert.deepEqual(settings.getRawConfigOwner("server").opencodeServers, existing) + } + } + const publicConfig = await send(target(), "/api/storage/config", { headers: { cookie } }) + assert.equal(publicConfig.status, 200) + assert.doesNotMatch(publicConfig.body, /sentinel-reference|credentialRef/) + assert.doesNotMatch(JSON.stringify(events), /sentinel-reference|credentialRef/) +}) + test("an unpaired remote browser reaches only the pairing surface", async (t) => { const { target } = await startRemoteSurface(t) assert.equal((await send(target(), "/api/test/echo")).status, 401) diff --git a/packages/server/src/remote-control/test-support/surface.ts b/packages/server/src/remote-control/test-support/surface.ts index a1e28a31c6..39d7c63ff3 100644 --- a/packages/server/src/remote-control/test-support/surface.ts +++ b/packages/server/src/remote-control/test-support/surface.ts @@ -4,16 +4,19 @@ import path from "node:path" import type { TestContext } from "node:test" import type { OpenRemoteTunnelOptions, RemoteTunnel } from "@codenomad/remote-tunnel" import { AuthManager } from "../../auth/manager" -import { createLogger } from "../../logger" +import { createLogger, type Logger } from "../../logger" import { PreviewManager } from "../../previews/manager" import { createHttpServer } from "../../server/http-server" import type { PanelExtensionStore } from "../../panel-extensions/store" import { RemoteDeviceRegistry } from "../devices" import { RemoteControlManager } from "../manager" +import type { SettingsService } from "../../settings/service" +import type { EventBus } from "../../events/bus" +import type { ClientConnectionManager } from "../../clients/connection-manager" export const FAKE_TUNNEL_HOST = "codenomad-test.device.tunnel.test" // Each logger pipes to stdout, so fixtures share one. -const logger = createLogger({ level: "silent" } as never) +const sharedLogger = createLogger({ level: "silent" } as never) /** * The real CodeNomad HTTP application behind a Remote Control manager, with @@ -22,10 +25,15 @@ const logger = createLogger({ level: "silent" } as never) */ export async function startRemoteSurface(t: TestContext, options: { skipAuth?: boolean + settings?: SettingsService + workspaceManager?: unknown + logger?: Logger openTunnel?: (options: OpenRemoteTunnelOptions) => Promise /** Real panel extension routes over this store, with `workspaceManager` in place of the stub. */ panelExtensions?: { store: PanelExtensionStore; workspaceManager: unknown } + events?: { eventBus: EventBus; connections: ClientConnectionManager } } = {}) { + const logger = options.logger ?? sharedLogger const directory = fs.mkdtempSync(path.join(os.tmpdir(), "codenomad-remote-surface-")) t.after(() => fs.rmSync(directory, { recursive: true, force: true })) const uiDir = path.join(directory, "ui") @@ -73,11 +81,11 @@ export async function startRemoteSurface(t: TestContext, options: { bindPort: 0, defaultPort: 0, protocol: "http", - workspaceManager: (options.panelExtensions?.workspaceManager ?? stub) as never, + workspaceManager: (options.workspaceManager ?? options.panelExtensions?.workspaceManager ?? stub) as never, panelExtensions: options.panelExtensions?.store, - settings: stub, + settings: options.settings ?? stub, fileSystemBrowser: stub, - eventBus: stub, + eventBus: options.events?.eventBus ?? stub, serverMeta: { localUrl: "http://localhost:0", eventsUrl: "/api/events", host: "127.0.0.1", listeningMode: "local", localPort: 0, hostLabel: "test", workspaceRoot: directory, addresses: [] } as never, instanceStore: stub, speechService: stub, @@ -85,7 +93,7 @@ export async function startRemoteSurface(t: TestContext, options: { previewManager, remoteControlManager: manager, authManager, - clientConnectionManager: stub, + clientConnectionManager: options.events?.connections ?? stub, remoteProxySessionManager: stub, yoloManager: stub, uiStaticDir: uiDir, @@ -113,6 +121,8 @@ export async function startRemoteSurface(t: TestContext, options: { }) const { pairing } = await manager.start() return { + app, + authManager, manager, previewManager, pairing, diff --git a/packages/server/src/server/__tests__/explicit-capabilities.test.ts b/packages/server/src/server/__tests__/explicit-capabilities.test.ts new file mode 100644 index 0000000000..da08b330f6 --- /dev/null +++ b/packages/server/src/server/__tests__/explicit-capabilities.test.ts @@ -0,0 +1,18 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { initialServerCapabilities, requireServerCapability, SERVER_CAPABILITY_NAMES } from "../../opencode/servers/capabilities" + +test("closed capability policy rejects unknown and limited explicit authority; local initial semantics stay unchanged", () => { + const explicit = initialServerCapabilities({ kind: "explicit", id: "A", label: "A", origin: "https://a.invalid" }, 1) + const local = initialServerCapabilities({ kind: "local-shared", id: "local-shared" }, 1) + for (const capability of SERVER_CAPABILITY_NAMES) { + assert.throws(() => requireServerCapability(capability, explicit.features[capability]), error => { + assert.equal((error as any).code, "explicit_capability_unavailable") + assert.equal((error as any).capability, capability) + assert.deepEqual((error as any).reason, explicit.features[capability].reason) + return true + }) + assert.doesNotThrow(() => requireServerCapability(capability, local.features[capability], true)) + } + assert.doesNotThrow(() => requireServerCapability("chat", { state: "available", reason: { code: "contractVerified" }, evidence: "nativeContract" })) +}) diff --git a/packages/server/src/server/__tests__/explicit-proxy.test.ts b/packages/server/src/server/__tests__/explicit-proxy.test.ts new file mode 100644 index 0000000000..ce0dcb5991 --- /dev/null +++ b/packages/server/src/server/__tests__/explicit-proxy.test.ts @@ -0,0 +1,538 @@ +import assert from "node:assert/strict" +import test, { type TestContext } from "node:test" +import Fastify, { type FastifyInstance } from "fastify" +import replyFrom from "@fastify/reply-from" +import pino from "pino" +import { EventBus } from "../../events/bus" +import { explicitContractFixture } from "../../opencode/compatibility/contract-fixture" +import { OpenCodeServerConnections, type ServerConnection } from "../../opencode/servers/connections" +import { OpenCodeServerCredentials } from "../../opencode/servers/credentials" +import { OpenCodeServerRegistry } from "../../opencode/servers/registry" +import { WorkspaceManager } from "../../workspaces/manager" +import { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" +import { registerInstanceProxyRoutes } from "../http-server" +import { registerSessionMediaRoutes } from "../routes/session-media" +import { mediaDigest } from "../../opencode/session-media" +import type { OpenCodeServerProfile } from "../../opencode/servers/types" +import { OpenCode, type OpenCodeClient, type LocationRef } from "@opencode/client" +import type { ServiceConnection } from "../../workspaces/opencode-service" +import type { ServerCapability } from "../../opencode/servers/capabilities" +import { EXPLICIT_REQUEST_UNCERTAIN_ERROR_CODE } from "../../api-types" + +const deferred = () => { + let resolve!: () => void + const promise = new Promise(done => { resolve = done }) + return { promise, resolve } +} + +async function fixture(t: TestContext, directory = "/same/project") { + const calls: { server: string; path: string; body: any; headers: any; query: string }[] = [] + let override: ((path: string, server: string) => { status?: number; body: unknown; type?: string } | undefined | Promise<{ status?: number; body: unknown; type?: string } | undefined>) | undefined + const forbidden = () => { throw new Error("Host adapter forbidden") } + const upstreams: FastifyInstance[] = [], profiles: OpenCodeServerProfile[] = [] + let sessionDirectory = directory, sessionIdentity = "s", pause: { entered: ReturnType; release: ReturnType; path: string } | undefined + const images = { A: `data:image/png;base64,${Buffer.from("image-A").toString("base64")}`, B: `data:image/png;base64,${Buffer.from("image-B").toString("base64")}`, "local-shared": "data:image/png;base64,eA==" } + let localConnection: ServiceConnection + for (const server of ["A", "B", "local-shared"] as const) { + const app = Fastify() + app.all("/*", async (request, reply) => { + const url = new URL(request.url, "http://fixture") + calls.push({ server, path: url.pathname, query: url.search, body: request.body, headers: request.headers }) + if (pause?.path === url.pathname) { const hold = pause; hold.entered.resolve(); await hold.release.promise } + if (url.pathname === "/openapi.json") return explicitContractFixture() + if (url.pathname === "/api/location") return { directory, project: { id: "same", directory: "/", canonical: "/" } } + if (url.pathname === "/api/fs/list") return { location: { directory }, data: [] } + const supplied = await override?.(url.pathname, server) + if (supplied) return reply.code(supplied.status ?? 200).type(supplied.type ?? "application/json").send(supplied.body) + reply.header("set-cookie", "forbidden=secret").header("www-authenticate", "Basic secret").header("proxy-authenticate", "Basic secret").header("location", "https://forbidden.invalid/") + const session = { id: sessionIdentity, location: { directory: sessionDirectory }, parentID: "foreign-parent", projectID: "same", title: server } + if (url.pathname === "/api/session" && request.method === "GET") return { data: [session], cursor: {} } + if (url.pathname === "/api/session/active") return { data: { s: { type: "running" }, foreign: { type: "running" }, gone: { type: "running" } } } + if (url.pathname === "/api/session/gone") return reply.code(404).send({ _tag: "SessionNotFoundError", sessionID: "gone", message: "missing" }) + if (url.pathname === "/api/session/foreign") return { data: { ...session, id: "foreign", location: { directory: "/sibling" } } } + if (url.pathname === "/api/session/s" && request.method === "GET") return { data: session } + const form = url.pathname.match(/^\/api\/session\/(s|global)\/form\/q$/) + if (form && request.method === "GET") return { data: { id: "q", sessionID: form[1], title: server, + fields: [{ key: "answer", type: "string" }], state: { status: "pending" } } } + if (url.pathname === "/api/session" || url.pathname.endsWith("/fork")) return { data: session } + if (url.pathname === "/api/session/s/message/m") return { data: { id: "m", type: "assistant", content: [{ type: "tool", state: { content: [{ type: "file", mime: "image/png", uri: images[server] }] } }] } } + if (url.pathname === "/api/session/s/message") return { data: [{ id: "m", type: "assistant", content: [{ type: "tool", state: { content: [{ type: "file", mime: "image/png", uri: images[server] }] } }] }], cursor: {} } + if (url.pathname === "/api/session/s/prompt") return { data: { id: "inbox", server } } + if (server === "local-shared" && url.pathname === "/api/rpc/codenomad.missions/scheduleCarrierRead") return { output: { owned: false } } + if (url.pathname === "/api/session/s/interrupt") return { interrupted: true } + if (request.method !== "GET") return reply.code(204).send() + return { marker: server } + }) + await app.listen({ host: "127.0.0.1", port: 0 }) + upstreams.push(app) + const origin = `http://127.0.0.1:${(app.server.address() as { port: number }).port}` + if (server !== "local-shared") profiles.push({ id: server, kind: "explicit" as const, label: server, origin }) + else localConnection = { endpoint: { url: origin }, client: OpenCode.make({ baseUrl: origin }), fetch: globalThis.fetch, assertCurrent() {}, invalidate() {}, profile: async () => "modern" } + } + const registry = new OpenCodeServerRegistry(() => profiles, forbidden) + const credentials = new OpenCodeServerCredentials({ profileKey: "proxy-test", configIdentity: "proxy-test" }, registry) + for (const id of ["A", "B"]) await credentials.set(id, JSON.stringify({ username: id, password: `fixture-${id}` })) + const connections = new OpenCodeServerConnections({ registry, credentials, local: { acquire: forbidden, existing: forbidden, invalidate: forbidden } }) + const manager = new WorkspaceManager({ rootDir: "C:/forbidden", logger: pino({ level: "silent" }), eventBus: new EventBus(), + binaryResolver: { resolveDefault: forbidden } as never, + settings: { getOpenCodeServerConnections: () => connections, getOwner: forbidden, readEnvironmentForAdmission: forbidden, disposeOpenCodeServers: () => connections.dispose() } as never, + sharedService: { endpoint: forbidden, client: forbidden, headers: forbidden, validateLocation: forbidden, subscribe: forbidden, shutdown: async () => {} }, + }) + const a = (await manager.create(directory, undefined, { serverId: "A" })).workspace + const b = (await manager.create(directory, undefined, { serverId: "B" })).workspace + const local = { id: "local", path: directory, binding: { serverId: "local-shared", directory } } as typeof a + const localSignal = new AbortController().signal + const get = manager.get.bind(manager), acquire = manager.getSharedServiceConnection.bind(manager), requireCapability = manager.requireWorkspaceCapability.bind(manager), ownsLocation = manager.ownsLocation.bind(manager), translate = manager.getServiceDirectoryForPath.bind(manager) + t.mock.method(manager, "get", (id: string) => id === "local" ? local : get(id)) + t.mock.method(manager, "getSharedServiceConnection", (id: string) => id === "local" ? Promise.resolve(localConnection) : acquire(id)) + t.mock.method(manager, "requireWorkspaceCapability", (id: string, capability: ServerCapability) => id === "local" ? localSignal : requireCapability(id, capability)) + t.mock.method(manager, "ownsLocation", (id: string, location: LocationRef, client?: OpenCodeClient, signal?: AbortSignal) => id === "local" ? Promise.resolve(location.directory === directory && location.workspaceID === undefined) : ownsLocation(id, location, client, signal)) + t.mock.method(manager, "getServiceDirectoryForPath", (id: string, path: string) => id === "local" ? Promise.resolve(path === directory ? path : undefined) : translate(id, path)) + for (const method of ["getSharedServiceEndpoint", "getSharedServiceClient", "getSharedServiceFetch", "getServicePathForPath", "getHostPathForServicePath", "ownsDirectory", "ownsPath"] as const) t.mock.method(manager, method, forbidden) + const desktopPluginsReady = t.mock.method(manager, "desktopPluginsReady", forbidden) + t.mock.method(manager, "getSessionEnvironment", async (id: string) => { if (id !== "local") return forbidden(); return { PATH: "host-sentinel", HOME: "host-sentinel", TOKEN: "host-sentinel" } }) + t.mock.method(manager, "getWorktreeIdentityForPath", async (id: string) => { if (id !== "local") return forbidden(); return "local-identity" }) + const app = Fastify() + const publication = { onSend: 0, write: 0, end: 0 } + const observerClosed = deferred() + app.addHook("onRequest", async (request, reply) => { + if (request.method !== "GET" || !/\/form\//.test(request.url)) return + const raw = reply.raw as any, write = raw.write, end = raw.end + raw.once("close", observerClosed.resolve) + raw.write = function (...args: any[]) { publication.write++; return write.apply(this, args) } + raw.end = function (...args: any[]) { publication.end++; return end.apply(this, args) } + }) + app.addHook("onSend", async (request, _reply, body) => { + if (request.method === "GET" && /\/form\//.test(request.url)) publication.onSend++ + return body + }) + await app.register(replyFrom) + registerInstanceProxyRoutes(app, { workspaceManager: manager, logger: pino({ level: "silent" }), worktreeDeletionFence: new WorktreeDeletionFence(), + accounts: { beforeSend: (connection: ServiceConnection) => { if (connection !== localConnection) forbidden() }, manual: forbidden } as never, + permissionReceipts: { prepare: forbidden, prepareDeletion: forbidden } as never, humanAnswers: forbidden as never }) + registerSessionMediaRoutes(app, { workspaceManager: manager }) + await app.ready() + t.after(async () => { pause?.release.resolve(); await app.close(); await manager.shutdown(); await Promise.all(upstreams.map(value => value.close())) }) + const url = (id: string, suffix: string) => `/workspaces/${id}/instance/api/${suffix}` + const nativeClient = (id: string): OpenCodeClient => OpenCode.make({ baseUrl: `http://proxy/workspaces/${id}/instance`, fetch: async (input, init) => { + const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url) + const result = await app.inject({ method: init?.method as "GET", url: url.pathname + url.search, payload: init?.body as string, headers: Object.fromEntries(new Headers(init?.headers).entries()) }) + return new Response(result.statusCode === 204 ? null : Uint8Array.from(result.rawPayload), { status: result.statusCode, headers: result.headers as Record }) + } }) + return { app, manager, connections, credentials, a, b, local, calls, images, url, nativeClient, publication, observerClosed, desktopPluginsReady, + respond: (value: typeof override) => { override = value }, + move: (value: string) => { sessionDirectory = value }, identity: (value: string) => { sessionIdentity = value }, + hold: (path: string) => { pause = { path, entered: deferred(), release: deferred() }; return pause }, + } +} + +test("individual Form GET uses exact captured A/B/global placement, bounds reads and keeps Permission GET closed", async t => { + const directory = "/é %25 日本" + const f = await fixture(t, directory) + for (const workspace of [f.a, f.b]) for (const sessionID of ["s", "global"]) { + const before = f.calls.length + const value = await f.nativeClient(workspace.id).session.form.get({ sessionID, formID: "q" }, { headers: { + "x-codenomad-connection-generation": String(f.manager.get(workspace.id)!.capabilities!.generation), + ...(sessionID === "global" ? { "x-opencode-directory": encodeURIComponent(directory) } : {}), + } }) + assert.equal(value.title, workspace.binding!.serverId) + assert.equal(value.state.status, "pending") + const reads = f.calls.slice(before) + assert.equal(reads.length, sessionID === "global" ? 1 : 3) + assert(reads.every(call => call.server === workspace.binding!.serverId)) + assert(reads.every(call => call.headers["x-codenomad-connection-generation"] === undefined)) + if (sessionID === "global") assert.equal(reads[0].headers["x-opencode-directory"], encodeURIComponent(directory)) + } + const acquire = t.mock.method(f.manager, "getSharedServiceConnection", () => { throw new Error("No permission acquisition") }) + assert.equal((await f.app.inject(f.url(f.a.id, "session/s/permission/p"))).statusCode, 403) + const stale = f.manager.get(f.a.id)!.capabilities!.generation! + 1 + assert.equal((await f.app.inject({ url: f.url(f.a.id, "session/s/form/q"), headers: { "x-codenomad-connection-generation": String(stale) } })).statusCode, 409) + assert.equal(acquire.mock.callCount(), 0) +}) + +test("Form wire failures never escape as usable data or leak native bodies; fresh explicit retry works", async t => { + const f = await fixture(t) + const header = { "x-codenomad-connection-generation": String(f.manager.get(f.a.id)!.capabilities!.generation) } + for (const [status, body] of [[404, { _tag: "PermissionNotFoundError", requestID: "q" }], [200, { data: { unexpected: true } }], + [404, { _tag: "FormNotFoundError", id: "q", message: "NATIVE-SECRET-SENTINEL" }]] as const) { + f.respond(path => path.includes("/form/") ? { status, body } : undefined) + const response = await f.app.inject({ url: f.url(f.a.id, "session/s/form/q"), headers: header }) + assert.equal(response.statusCode, 503); assert.deepEqual(response.json(), { error: "form_verification_indeterminate" }) + assert(!response.body.includes("SENTINEL")) + } + f.respond(() => undefined) + f.move("/foreign") + const before = f.calls.filter(call => call.path.includes("/form/")).length + assert.equal((await f.app.inject({ url: f.url(f.a.id, "session/s/form/q"), headers: header })).statusCode, 503) + assert.equal(f.calls.filter(call => call.path.includes("/form/")).length, before, "mismatched Session never reads a Form") + f.move("/same/project") + assert.equal((await f.app.inject({ url: f.url(f.a.id, "session/s/form/q"), headers: header })).statusCode, 200) +}) + +test("Form pre/post Session responses also have the 4MiB ceiling, and post-read placement fences publication", async t => { + const f = await fixture(t) + for (const phase of [1, 2]) { + let sessions = 0 + const before = f.calls.length + f.respond(path => path === "/api/session/s" && ++sessions === phase ? { body: JSON.stringify({ data: { id: "s", location: { directory: "/same/project" } } }) + " ".repeat(4 * 1024 * 1024) } : undefined) + assert.equal((await f.app.inject(f.url(f.a.id, "session/s/form/q"))).statusCode, 503) + assert.equal(f.calls.slice(before).filter(call => call.path.includes("/form/")).length, phase - 1) + } + const pause = f.hold("/api/session/s/form/q") + f.respond(undefined) + const pending = f.app.inject(f.url(f.a.id, "session/s/form/q")) + await pause.entered.promise + f.move("/foreign"); pause.release.resolve() + assert.equal((await pending).statusCode, 503) +}) + +test("one real ten-second Form budget includes acquisition, profile and sequential wire phases", async t => { + const f = await fixture(t) + const connection = (await f.manager.getSharedServiceConnection(f.a.id))! + let profile = 0 + const delay = () => new Promise(resolve => setTimeout(resolve, 3500)) + t.mock.method(f.manager, "getSharedServiceConnection", async () => { await delay(); return { ...connection, profile: async () => { profile++; await delay(); return "modern" as const } } }) + f.respond(async path => { if (path.includes("/form/")) await delay(); return undefined }) + const before = f.calls.length, start = Date.now() + const response = await f.app.inject(f.url(f.a.id, "session/s/form/q")) + const elapsed = Date.now() - start + assert.equal(response.statusCode, 503) + assert(elapsed >= 9900 && elapsed < 12_000, `whole operation took ${elapsed}ms`) + assert.equal(profile, 1) + assert.equal(f.calls.slice(before).filter(call => call.path === "/api/session/s").length, 1, "no post-read after deadline") +}) + +test("elapsed Form deadline fences response parsing before a delayed timer turn can permit post-read or publication", async t => { + const f = await fixture(t) + let elapsed = performance.now() + t.mock.method(performance, "now", () => elapsed) + f.respond(path => { if (path.includes("/form/")) elapsed += 10_001; return undefined }) + const before = f.calls.length + const response = await f.app.inject(f.url(f.a.id, "session/s/form/q")) + assert.equal(response.statusCode, 503) + assert.equal(f.calls.slice(before).filter(call => call.path === "/api/session/s").length, 1) +}) + +test("closing a Form HTTP observer during shared acquisition writes nothing and prevents later native reads", async t => { + const f = await fixture(t), acquired = deferred(), release = deferred() + t.after(() => release.resolve()) + const connection = (await f.manager.getSharedServiceConnection(f.a.id))! + t.mock.method(f.manager, "getSharedServiceConnection", async () => { acquired.resolve(); await release.promise; return connection }) + await f.app.listen({ host: "127.0.0.1", port: 0 }) + const origin = `http://127.0.0.1:${(f.app.server.address() as { port: number }).port}` + const controller = new AbortController(), before = f.calls.length + const response = fetch(origin + f.url(f.a.id, "session/s/form/q"), { signal: controller.signal }) + const rejected = assert.rejects(response) + await acquired.promise; controller.abort(); await rejected + // Native response close is observed before allowing shared work to return. + await f.observerClosed.promise + release.resolve() + await new Promise(resolve => setImmediate(resolve)) + assert.deepEqual(f.publication, { onSend: 0, write: 0, end: 0 }) + assert.equal(f.calls.length, before) +}) + +test("current manager capabilities revoke and restore proxy admission independently for two A occurrences, B and local", async t => { + const f = await fixture(t) + const a2 = (await f.manager.create(f.a.path, "second", { serverId: "A" })).workspace + const historical = f.manager.get(f.a.id)!, b = f.manager.get(f.b.id)! + await f.credentials.set("A", JSON.stringify({ username: "rotated", password: "fixture-only" })) + const before = f.calls.length + for (const id of [f.a.id, a2.id]) { + assert.equal(f.manager.get(id)!.capabilities!.features.chat.state, "unknown") + const result = await f.app.inject(f.url(id, "agent")) + assert.equal(result.statusCode, 403) + assert.deepEqual(result.json().reason, { code: "contractUnverified" }) + } + assert.equal(f.calls.length, before) + assert.equal((await f.app.inject(f.url(f.b.id, "agent"))).json().marker, "B") + assert.equal((await f.app.inject(f.url(f.local.id, "session/s"))).json().data.title, "local-shared") + const connection = (await f.manager.acquireForWorkspace(a2.id))! + for (const id of [f.a.id, a2.id]) { + const current = f.manager.get(id)! + assert.equal(current.capabilities!.features.chat.state, "available") + assert.equal(current.capabilities!.generation, (connection as ServerConnection).generation) + assert.equal((await f.app.inject(f.url(id, "agent"))).json().marker, "A") + const image = f.images.A + const media = await f.app.inject(`/api/workspaces/${id}/session-media/s/m/0/0/${mediaDigest(image)}`) + assert.equal(media.statusCode, 200) + assert.equal(media.rawPayload.toString(), "image-A") + } + assert.notEqual(historical.capabilities!.generation, f.manager.get(f.a.id)!.capabilities!.generation) + assert.equal(historical.capabilities!.features.chat.state, "available") + assert.deepEqual(f.manager.get(f.b.id)!.capabilities, b.capabilities) +}) + +test("a multi-request chat action keeps its captured generation before renderer metadata catches up", async t => { + const f = await fixture(t) + const header = "x-codenomad-connection-generation" + const captured = f.manager.get(f.a.id)!.capabilities!.generation + const native = f.nativeClient(f.a.id) + const options = { headers: { [header]: String(captured) } } + await native.session.instructions.entry.put({ sessionID: "s", key: "placement", value: "native boundary" }, options) + await f.credentials.set("A", JSON.stringify({ username: "rotated", password: "fixture-only" })) + await f.manager.acquireForWorkspace(f.a.id) + assert.notEqual(f.manager.get(f.a.id)!.capabilities!.generation, captured) + const before = f.calls.length + for (const [method, path, body] of [ + ["POST", "session/s/prompt", { text: "do not replay" }], + ["POST", "session/s/command", { name: "review", text: "args" }], + ["POST", "session/s/shell", { command: "pwd" }], + ["POST", "session/s/fork", {}], ["POST", "session", {}], + ["GET", "agent", undefined], + ] as const) { + const result = await f.app.inject({ method, url: f.url(f.a.id, path), payload: body, headers: options.headers }) + assert.equal(result.statusCode, 409) + assert.equal(result.json().error, "explicit_action_superseded") + } + assert.equal(f.calls.length, before, "stale action must not even hydrate ownership on the new connection") + const current = f.manager.get(f.a.id)!.capabilities!.generation + await native.session.prompt({ sessionID: "s", text: "fresh explicit action" }, { headers: { [header]: String(current) } }) + assert.equal(f.calls.filter(call => call.path.endsWith("/prompt")).length, 1) + assert.equal(f.calls.at(-2)?.headers[header], undefined, "private generation fence never reaches OpenCode") + assert.equal((await f.app.inject(f.url(f.b.id, "agent"))).json().marker, "B") +}) + +test("explicit generation-fence headers reject malformed values before native access", async t => { + const f = await fixture(t) + const before = f.calls.length + for (const value of ["0", "-1", "1.0", "1,2", "9007199254740992"]) { + assert.equal((await f.app.inject({ url: f.url(f.a.id, "agent"), headers: { "x-codenomad-connection-generation": value } })).statusCode, 400) + } + assert.equal(f.calls.length, before) +}) + +test("the local proxy accepts the ordinary send but strips an injected private generation header", async t => { + const f = await fixture(t) + const localReady = t.mock.method(f.manager, "desktopPluginsReady", async () => {}) + const result = await f.app.inject({ method: "POST", url: f.url(f.local.id, "session/s/prompt"), + headers: { "x-codenomad-connection-generation": "7" }, payload: { text: "local native send" } }) + assert.equal(result.statusCode, 200, result.body) + assert.equal(localReady.mock.callCount(), 1) + localReady.mock.restore() + const prompt = f.calls.find(call => call.server === "local-shared" && call.path === "/api/session/s/prompt") + assert.ok(prompt) + assert.equal(prompt.headers["x-codenomad-connection-generation"], undefined) + assert.ok(f.calls.some(call => call.server === "local-shared" && call.path.endsWith("/environment"))) +}) + +test("explicit handlers isolate homonymous sessions, native sends, catalogues and media without host effects", async t => { + const f = await fixture(t) + assert.equal((await f.app.inject(f.url(f.local.id, "session/s"))).json().data.title, "local-shared") + const localReady = t.mock.method(f.manager, "desktopPluginsReady", async () => {}) + const localPrompt = await f.app.inject({ method: "POST", url: f.url(f.local.id, "session/s/prompt"), payload: { text: "local" } }) + assert.equal(localPrompt.statusCode, 200, localPrompt.body) + assert.equal(localReady.mock.callCount(), 1) + localReady.mock.restore() + for (const [server, workspace] of [["A", f.a], ["B", f.b]] as const) { + assert.equal((await f.app.inject(f.url(workspace.id, "agent"))).json().marker, server) + assert.equal((await f.app.inject(f.url(workspace.id, "session"))).json().data[0].title, server) + assert.equal((await f.app.inject(f.url(workspace.id, "session/s"))).json().data.title, server) + assert.deepEqual(Object.keys((await f.app.inject(f.url(workspace.id, "session/active"))).json().data), ["s"]) + assert.equal((await f.app.inject({ method: "POST", url: f.url(workspace.id, "session"), payload: { title: server } })).statusCode, 200) + for (const [operation, payload] of [["prompt", { text: "direct" }], ["prompt", { text: "queued", delivery: "queue" }], ["prompt", { text: "restored", resume: true, files: [{ uri: "data:text/plain;base64,eA==" }] }], ["command", { name: "goal", arguments: "pause" }], ["shell", { command: "echo native" }], ["interrupt", {}], ["form/q/reply", { answers: [] }], ["permission/p/reply", { decision: "once" }]] as const) { + const response = await f.app.inject({ method: "POST", url: f.url(workspace.id, `session/s/${operation}`), payload }) + assert.equal(response.statusCode, ["prompt", "interrupt"].includes(operation) ? 200 : 204, `${server} ${operation}: ${response.body}`) + } + assert.equal((await f.app.inject({ method: "POST", url: f.url(workspace.id, "session/s/fork"), payload: {} })).statusCode, 200) + assert.equal((await f.app.inject({ method: "POST", url: f.url(workspace.id, "session/s/prompt"), payload: { text: "fork resumed" } })).statusCode, 200) + const native = f.nativeClient(workspace.id) + assert.equal((await native.session.get({ sessionID: "s" })).title, server) + await native.session.prompt({ sessionID: "s", text: "queued using generated wire", delivery: "queue", resume: true }) + await native.session.interrupt({ sessionID: "s", resume: false }) + await native.session.form.reply({ sessionID: "global", formID: "q", answer: {} }, { headers: { "x-opencode-directory": encodeURIComponent("/same/project") } }) + const globalReply = f.calls.filter(call => call.server === server && call.path === "/api/session/global/form/q/reply").at(-1)! + assert.equal(globalReply.headers["x-opencode-directory"], encodeURIComponent("/same/project")) + const media = await f.app.inject(`/api/workspaces/${workspace.id}/session-media/s/m/0/0/${mediaDigest(f.images[server])}`) + assert.equal(media.statusCode, 200) + assert.equal(media.rawPayload.toString(), `image-${server}`) + const response = await f.app.inject({ url: f.url(workspace.id, "agent"), headers: { authorization: "Basic browser-secret", cookie: "browser=secret", forwarded: "host=evil", "x-forwarded-host": "evil", "x-internal-secret": "evil" } }) + for (const header of ["set-cookie", "www-authenticate", "proxy-authenticate", "location"]) assert.equal(response.headers[header], undefined) + const outgoing = f.calls.at(-1)!.headers + assert.equal(outgoing.authorization, `Basic ${Buffer.from(`${server}:fixture-${server}`).toString("base64")}`) + for (const header of ["cookie", "forwarded", "x-forwarded-host", "x-internal-secret"]) assert.equal(outgoing[header], undefined) + } + assert(f.calls.filter(call => call.server !== "local-shared").every(call => !/environment|instructions|credential|integration|rpc/.test(call.path))) + assert.deepEqual(f.calls.find(call => call.server === "local-shared" && call.path.endsWith("/environment"))!.body.variables, { PATH: "host-sentinel", HOME: "host-sentinel", TOKEN: "host-sentinel" }) + assert(f.calls.filter(call => call.server !== "local-shared").every(call => !JSON.stringify(call.body)?.includes("host-sentinel"))) + assert.equal((await f.app.inject(`/api/workspaces/${f.a.id}/session-media/s/m/0/0/${mediaDigest(f.images.B)}`)).statusCode, 404) + assert.equal(f.desktopPluginsReady.mock.callCount(), 0, "explicit projects never await host plugin readiness") +}) + +test("explicit deferred operations and malformed scopes reject before acquisition or any upstream effect", async t => { + const f = await fixture(t) + const acquire = t.mock.method(f.manager, "getSharedServiceConnection", () => { throw new Error("Acquisition forbidden") }) + const count = f.calls.length + for (const [method, route, capability] of [ + ["GET", "fs/list", "files"], ["GET", "vcs/status", "git"], ["GET", "session/s/diff", "conversationDiffs"], ["POST", "session/s/move", "worktrees"], + ["POST", "shell", "backgroundShells"], ["POST", "pty", "terminal"], ["GET", "form", "pendingRecovery"], ["GET", "permission/request", "pendingRecovery"], + ["POST", "rpc/arbitrary/method", "historyEnrichment"], ["GET", "config", "executionSettings"], ["GET", "credential", "executionSettings"], ["POST", "integration/x/connect/key", "executionSettings"], + ["POST", "session/s/environment", "sessionEnvironment"], ["POST", "plugin/update", "executionSettings"], + ] as const) { + const response = await f.app.inject({ method, url: f.url(f.a.id, route) }) + assert.equal(response.statusCode, 403, route) + assert.equal(response.json().capability, capability) + assert.equal(response.json().error, "explicit_capability_unavailable") + } + for (const route of ["session?directory=/same/project&directory=/same/project", "session?directory=/same/project&location[directory]=/same/project", "session?project=same", "session?location[workspaceID]=x", "session?location.directory=/same/project", "session?directory=%FF", "session?directory=%252Fsame%252Fproject", "session/s%252Fforeign", "session?cursor=invalid"]) { + const response = await f.app.inject(f.url(f.a.id, route)) + assert([400, 403].includes(response.statusCode), `${route}: ${response.body}`) + } + for (const payload of [{ text: "x", location: { directory: "/sibling" } }, { text: "x", cwd: "/same/project" }, { text: "x", workspaceID: "legacy" }, { text: "x", files: [{ uri: "file:///host/secret" }] }]) { + const response = await f.app.inject({ method: "POST", url: f.url(f.a.id, "session/s/prompt"), payload }) + assert([400, 403].includes(response.statusCode), response.body) + } + for (const headers of [{ "x-opencode-directory": "/sibling" }, { "x-opencode-workspace": "legacy" }, { "x-codenomad-human-answer": "1" }, { "x-codenomad-location": encodeURIComponent(JSON.stringify({ directory: "/sibling" })) }]) { + assert.equal((await f.app.inject({ url: f.url(f.a.id, "session/s"), headers })).statusCode, 400) + } + assert.equal(acquire.mock.callCount(), 0) + assert.equal(f.calls.length, count) +}) + +test("explicit session authority never broadens to parent/project and checks exact native identity", async t => { + const f = await fixture(t) + f.move("/same/project/child") + assert.equal((await f.app.inject({ method: "POST", url: f.url(f.a.id, "session/s/prompt"), payload: { text: "denied" } })).statusCode, 403) + f.move("/same/project") + f.identity("different") + assert.equal((await f.app.inject({ method: "POST", url: f.url(f.a.id, "session/s/prompt"), payload: { text: "denied" } })).statusCode, 403) + assert(!f.calls.some(call => call.path.endsWith("/prompt"))) +}) + +test("explicit inventory forwards a native-shaped cursor alone on its own target and rejects broader cursor authority", async t => { + const f = await fixture(t) + const nativeShape = { order: "desc", archived: "false", type: "directory", directory: "/same/project", + anchor: { id: "s", time: 1, direction: "next" } } + const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url") + const cursor = encode(nativeShape) + for (const [server, workspace] of [["A", f.a], ["B", f.b]] as const) { + const page = await f.nativeClient(workspace.id).session.list({ cursor }) + assert.equal(page.data[0].title, server) + const call = f.calls.filter(call => call.server === server && call.path === "/api/session").at(-1)! + assert.deepEqual([...new URLSearchParams(call.query)], [["cursor", cursor]]) + assert.equal(call.headers["x-opencode-directory"], undefined) + assert.equal(call.headers["x-codenomad-location"], undefined) + } + const before = f.calls.length + for (const scope of [ + { ...nativeShape, directory: "/" }, { ...nativeShape, directory: "/same" }, + { ...nativeShape, directory: "/same/project/sibling" }, { ...nativeShape, directory: "/same/project/.worktrees/task" }, + { ...nativeShape, type: "project", directory: undefined, project: "same" }, + { ...nativeShape, type: "project", directory: undefined, project: "same", subpath: "child" }, + ]) { + const denied = await f.app.inject(f.url(f.a.id, `session?cursor=${encode(scope)}`)) + assert.equal(denied.statusCode, 400) + assert.deepEqual(denied.json(), { error: "Invalid explicit workspace scope" }) + } + assert.equal((await f.app.inject(f.url(f.a.id, `session?cursor=${encode({ ...nativeShape, subpath: "child" })}`))).statusCode, 400) + assert.equal(f.calls.length, before) +}) + +test("explicit native message pages preserve opaque cursors on A/B and reject unknown cursor formats before acquisition", async t => { + const f = await fixture(t) + const cursor = Buffer.from(JSON.stringify({ id: "m", order: "desc", direction: "previous" })).toString("base64url") + for (const workspace of [f.a, f.b]) { + await f.nativeClient(workspace.id).message.list({ sessionID: "s", limit: 200, cursor }) + const call = f.calls.filter(call => call.path === "/api/session/s/message").at(-1)! + assert.equal(call.server, workspace.binding!.serverId) + assert.deepEqual([...new URLSearchParams(call.query)], [["limit", "200"], ["cursor", cursor]]) + } + const before = f.calls.length + for (const query of ["cursor=unknown", "cursor=codenomad%3Ahistory-window%3A1%3Aanything", + `cursor=${cursor}&order=desc`, `cursor=${Buffer.from(JSON.stringify({ id: "m", order: "desc", direction: "next", unknown: true })).toString("base64url")}`, + "order=sideways", "limit=201"]) { + const response = await f.app.inject(f.url(f.a.id, `session/s/message?${query}`)) + assert.equal(response.statusCode, 400, query) + } + assert.equal(f.calls.length, before, "invalid native-page requests have zero upstream effects") +}) + +test("published capabilities cannot grant or revoke private workspace authority", async t => { + const f = await fixture(t) + f.a.capabilities!.features.worktrees = { state: "available", evidence: "nativeContract", reason: { code: "contractVerified" } } + f.a.capabilities!.features.chat = { state: "unavailable", evidence: "e1Policy", reason: { code: "deferred" } } + assert.throws(() => f.manager.requireWorkspaceCapability(f.a.id, "worktrees"), { code: "explicit_capability_unavailable", capability: "worktrees" }) + assert.doesNotThrow(() => f.manager.requireWorkspaceCapability(f.a.id, "chat")) + assert.equal((await f.app.inject(f.url(f.a.id, "agent"))).statusCode, 200) +}) + +test("media in flight is revoked per occurrence even when another occurrence retains the same target", async t => { + for (const retire of ["close", "rotate"] as const) { + const f = await fixture(t) + await f.manager.create("/same/project", undefined, { serverId: "A" }) + const hold = f.hold("/api/session/s/message/m") + const read = f.app.inject(`/api/workspaces/${f.a.id}/session-media/s/m/0/0/${mediaDigest(f.images.A)}`) + await hold.entered.promise + if (retire === "close") await f.manager.delete(f.a.id) + else await f.credentials.set("A", JSON.stringify({ username: "A", password: "replacement" })) + hold.release.resolve() + const response = await read + assert.equal(response.statusCode, 502) + assert(!response.body.includes("image-A")) + assert.equal((await f.app.inject(f.url(f.b.id, "agent"))).statusCode, 200) + } +}) + +test("a native move while a mutation waits yields an uncertain failure without replay", async t => { + const f = await fixture(t), hold = f.hold("/api/session/s/prompt") + const send = f.app.inject({ method: "POST", url: f.url(f.a.id, "session/s/prompt"), payload: { text: "only once" } }) + await hold.entered.promise + f.move("/sibling") + hold.release.resolve() + const result = await send + assert.equal(result.statusCode, 502) + assert.equal(result.json().error, EXPLICIT_REQUEST_UNCERTAIN_ERROR_CODE) + assert.match(result.body, /do not replay/) + assert.equal(f.calls.filter(call => call.path.endsWith("/prompt")).length, 1) +}) + +test("close and credential rotation while ownership waits fence sends and media; B stays usable", async t => { + for (const retire of ["close", "rotate"] as const) { + const f = await fixture(t), hold = f.hold("/api/session/s") + const send = f.app.inject({ method: "POST", url: f.url(f.a.id, "session/s/prompt"), payload: { text: "uncertain" } }) + await hold.entered.promise + if (retire === "close") await f.manager.delete(f.a.id) + else await f.credentials.set("A", JSON.stringify({ username: "A", password: "rotated" })) + hold.release.resolve() + assert([403, 502].includes((await send).statusCode)) + assert(!f.calls.some(call => call.path.endsWith("/prompt"))) + assert.equal((await f.app.inject(f.url(f.b.id, "agent"))).statusCode, 200) + } +}) + +// prototype-1236: background shells, branch and MCP runtime controls reach only the project's folder; secrets never. +test("explicit proxy serves the shell panel inside the folder only and never relays credentials or config", async t => { + const f = await fixture(t) + const shell = (id: string, cwd: string) => ({ id, command: "npm test", cwd, status: "running", time: { created: 1 } }) + f.respond((path) => { + if (path === "/api/shell") return { body: { location: { directory: "/same/project" }, data: [shell("in", "/same/project"), shell("child", "/same/project/web"), shell("out", "/same/projectx"), shell("up", "/same")] } } + if (path === "/api/shell/in" || path === "/api/shell/in/output") return { body: { location: { directory: "/same/project" }, data: path.endsWith("output") ? { output: "ok", cursor: 2, size: 2, truncated: false } : shell("in", "/same/project") } } + if (path === "/api/shell/out") return { body: { location: { directory: "/same/project" }, data: shell("out", "/elsewhere") } } + if (path === "/api/vcs") return { body: { location: { directory: "/same/project" }, data: { provider: "git", branch: { current: "main" } } } } + if (path === "/api/credential") return { body: { data: [{ value: { key: "secret-value" } }] } } + return undefined + }) + for (const workspace of [f.a, f.b]) { + const list = await f.app.inject(f.url(workspace.id, "shell")) + assert.equal(list.statusCode, 200, list.body) + assert.deepEqual(list.json().data.map((value: { id: string }) => value.id), ["in", "child"]) + assert.equal((await f.app.inject(f.url(workspace.id, "shell/in/output?cursor=0&limit=10"))).json().data.output, "ok") + assert.equal((await f.app.inject(f.url(workspace.id, "shell/out"))).statusCode, 403) + assert.equal((await f.app.inject({ method: "DELETE", url: f.url(workspace.id, "shell/out") })).statusCode, 403) + assert.ok((await f.app.inject({ method: "DELETE", url: f.url(workspace.id, "shell/in") })).statusCode < 300) + assert.equal(f.calls.filter(call => call.path === "/api/shell/out" && call.server === workspace.binding!.serverId).length, 2, "ownership read only, no DELETE dispatched") + assert.equal((await f.app.inject(f.url(workspace.id, "vcs"))).json().data.branch.current, "main") + assert.equal((await f.app.inject({ method: "POST", url: f.url(workspace.id, "shell"), payload: { command: "rm -rf /" } })).statusCode, 403) + } + const before = f.calls.length + for (const route of ["credential", "config", "vcs/status", "vcs/diff?mode=working", "experimental/config", "fs/read/secret", "experimental/fs/write"]) { + for (const method of ["GET", "POST", "PATCH"] as const) { + const response = await f.app.inject({ method, url: f.url(f.a.id, route), ...(method === "GET" ? {} : { payload: {} }) }) + assert.equal(response.statusCode, 403, `${method} ${route}`) + assert(!response.body.includes("secret-value")) + } + } + assert.equal(f.calls.length, before, "refused routes have zero upstream effects") + assert(f.calls.every(call => call.path !== "/api/credential")) + assert(f.calls.filter(call => call.path.startsWith("/api/shell")).every(call => new URLSearchParams(call.query).get("location[directory]") === "/same/project")) +}) diff --git a/packages/server/src/server/explicit-form-verification.test.ts b/packages/server/src/server/explicit-form-verification.test.ts new file mode 100644 index 0000000000..b2c68cf169 --- /dev/null +++ b/packages/server/src/server/explicit-form-verification.test.ts @@ -0,0 +1,111 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { createServer } from "node:http" +import { gzipSync, deflateSync, brotliCompressSync } from "node:zlib" +import { OpenCode } from "@opencode/client" +import { readExplicitForm } from "./explicit-form-verification" +import { FORM_VERIFICATION_LIMIT as limit } from "../opencode/form-verification-policy" +import type { ServiceConnection } from "../workspaces/opencode-service" + +const directory = "/é %25 日本", fields = [{ key: "answer", type: "string", required: true }] +const form = (state: unknown = { status: "pending" }, extra = {}) => ({ data: { id: "frm_q", sessionID: "ses_s", title: "Known", fields, state, ...extra } }) +const session = { data: { id: "ses_s", location: { directory } } } +function reader(response: () => Response, options: { global?: boolean; signal?: AbortSignal; current?: () => void; native?: typeof fetch } = {}) { + const calls: { path: string; headers: Headers }[] = [] + const fetch: typeof globalThis.fetch = options.native ?? (async (input, init) => { + const path = new URL(input instanceof Request ? input.url : input).pathname + calls.push({ path, headers: new Headers(init?.headers) }) + return path.includes("/form/") ? response() : Response.json(session) + }) + const connection: ServiceConnection = { endpoint: { url: "http://127.0.0.1" }, fetch, client: OpenCode.make({ baseUrl: "http://127.0.0.1", fetch }), + profile: async () => "modern", assertCurrent: options.current ?? (() => {}), invalidate() {} } + return { calls, read: () => readExplicitForm({ acquire: async () => connection, signal: options.signal ?? new AbortController().signal, + current: options.current ?? (() => {}), sessionId: options.global ? "global" : "ses_s", formId: "frm_q", directory }) } +} +test("session 2+1 and global 1; complete native fields/codecs, extensions ignored, answers never leave reader", async () => { + const nativeFields = [ + ...fields, { type: "number", key: "n", minimum: "-Infinity", maximum: "Infinity", default: "NaN", when: [{ key: "a", op: "neq", value: true }] }, + { type: "integer", key: "i", minimum: -0.5, default: "Infinity" }, { type: "boolean", key: "b", default: false }, + { type: "multiselect", key: "m", options: [{ value: "x", label: "X", description: "desc" }], minItems: 0, maxItems: 2, default: ["x"] }, + { type: "external", key: "e", url: "https://example.invalid" }, + { type: "string", key: "s", format: "email", options: [], custom: true, hidden: true, pattern: ".*", minLength: 0, maxLength: 3 }, + ] + for (const global of [false, true]) for (const status of ["pending", "answered", "cancelled"]) { + const state = status === "answered" ? { status, answer: { text: "ANSWER-SENTINEL", numeric: "NaN", bool: false, multi: ["x"] } } : { status } + const f = reader(() => Response.json(form(state, { sessionID: global ? "global" : "ses_s", fields: nativeFields, future: "ignored" })), { global }) + const result = await f.read() + assert.equal(result.data.state.status, status) + assert(!JSON.stringify(result).includes("ANSWER-SENTINEL")) + assert.equal(f.calls.length, global ? 1 : 3) + assert.equal(f.calls.filter(call => call.path.includes("/form/")).length, 1) + if (global) assert.equal(f.calls[0].headers.get("x-opencode-directory"), encodeURIComponent(directory)) + assert(!f.calls.some(call => /permission|list|rpc|location/.test(call.path))) + } +}) +for (const [name, value] of [ + ["missing success shape", { data: { unexpected: true } }], + ["wrong Form", form(undefined, { id: "frm_other" })], ["wrong session", form(undefined, { sessionID: "ses_other" })], + ["unknown state", form({ status: "future" })], ["missing answer", form({ status: "answered" })], + ["bad answer", form({ status: "answered", answer: { value: {} } })], + ["bad cancel message", form({ status: "cancelled", message: 12 })], + ["unknown field", form(undefined, { fields: [{ key: "x", type: "future" }] })], + ["bad option", form(undefined, { fields: [{ key: "x", type: "multiselect", options: [{ value: "x" }] }] })], + ["bad condition", form(undefined, { fields: [{ key: "x", type: "string", when: [{ key: "a", op: "gt", value: 1 }] }] })], + ["negative count", form(undefined, { fields: [{ key: "x", type: "string", minLength: -1 }] })], + ["fractional count", form(undefined, { fields: [{ key: "x", type: "multiselect", options: [], maxItems: 0.5 }] })], + ["foreign envelope", { ...form(), location: { directory: "/foreign" } }], +] as const) test(`WIRE rejects ${name} before usable SDK data`, async () => { + const f = reader(() => Response.json(value)) + await assert.rejects(f.read()) + assert.equal(f.calls.length, 2) +}) +test("SDK counterexamples, all error statuses, wrong media type and nonfinite JSON remain indeterminate", async () => { + for (const status of [400, 401, 404, 500]) for (const body of [ + { _tag: "PermissionNotFoundError", requestID: "frm_q" }, { _tag: "FormNotFoundError", id: "frm_q", message: "PRIVATE-SENTINEL" }, + { message: "generic" }, { _tag: "SessionNotFoundError", sessionID: "ses_s", message: "missing" }, + ]) await assert.rejects(reader(() => Response.json(body, { status })).read()) + for (const raw of ["{", JSON.stringify(form()).replace('"pending"', '1e400')]) await assert.rejects(reader(() => new Response(raw, { headers: { "content-type": "application/json" } })).read()) + await assert.rejects(reader(() => new Response(JSON.stringify(form()), { headers: { "content-type": "text/plain" } })).read()) +}) +test("each success/error HTTP response has exact 4MiB decompressed ceiling, regardless of Content-Length", async () => { + const base = JSON.stringify(form()), padded = (bytes: number) => base + " ".repeat(bytes - Buffer.byteLength(base)) + await reader(() => new Response(padded(limit), { headers: { "content-type": "application/json", "content-length": "1" } })).read() + await assert.rejects(reader(() => new Response(padded(limit), { status: 404, headers: { "content-type": "application/json" } })).read(), /Invalid Form verification response/) + for (const status of [200, 404]) { + const f = reader(() => new Response(padded(limit + 1), { status, headers: { "content-type": "application/json", "content-length": "1" } })) + await assert.rejects(f.read(), /too large/) + } +}) +test("real HTTP gzip/deflate/br are counted after native fetch decompression", async t => { + let length = limit, status = 200 + const compress = { gzip: gzipSync, deflate: deflateSync, br: brotliCompressSync } + let encoding: keyof typeof compress = "gzip" + const app = createServer((_request, response) => { + const body = JSON.stringify(form(undefined, { sessionID: "global" })) + const bytes = compress[encoding](Buffer.from(body + " ".repeat(length - Buffer.byteLength(body)))) + response.writeHead(status, { "content-type": "application/json", "content-encoding": encoding, "content-length": bytes.length }) + response.end(bytes) + }) + await new Promise(resolve => app.listen(0, "127.0.0.1", resolve)) + t.after(() => new Promise(resolve => app.close(() => resolve()))) + const origin = `http://127.0.0.1:${(app.address() as { port: number }).port}` + for (encoding of ["gzip", "deflate", "br"] as const) { + const native: typeof fetch = (input, init) => globalThis.fetch(new URL(new URL(String(input)).pathname, origin), init) + for (status of [200, 404]) { + length = limit + const exact = reader(() => { throw new Error("unused") }, { global: true, native }).read() + if (status === 200) await exact + else await assert.rejects(exact, /Invalid Form verification response/) + length = limit + 1; await assert.rejects(reader(() => { throw new Error("unused") }, { global: true, native }).read(), /too large/) + } + } +}) +test("overflow cancels once and releases lock without waiting for a held rejecting cleanup", async () => { + let cancels = 0, rejectCleanup!: (error: Error) => void + const stream = new ReadableStream({ start(controller) { controller.enqueue(new Uint8Array(limit + 1)) }, + cancel() { cancels++; return new Promise((_resolve, reject) => { rejectCleanup = reject }) } }) + const f = reader(() => new Response(stream, { headers: { "content-type": "application/json" } })) + await assert.rejects(f.read(), /too large/) + assert.equal(cancels, 1); assert.equal(stream.locked, false) + rejectCleanup(new Error("Owned cleanup rejection")) +}) diff --git a/packages/server/src/server/explicit-form-verification.ts b/packages/server/src/server/explicit-form-verification.ts new file mode 100644 index 0000000000..afdf667ff4 --- /dev/null +++ b/packages/server/src/server/explicit-form-verification.ts @@ -0,0 +1,72 @@ +import { OpenCode } from "@opencode/client" +import { z } from "zod" +import { boundedResponseFetch } from "../opencode/bounded-response-fetch" +import { wireFormSchema } from "../opencode/form-contract" +import { FORM_VERIFICATION_LIMIT } from "../opencode/form-verification-policy" +import type { ServiceConnection } from "../workspaces/opencode-service" +import { waitForAdmission } from "./request-admission" + +const location = z.object({ directory: z.string(), workspaceID: z.string().optional() }) +const sessionEnvelope = z.object({ data: z.object({ id: z.string(), location }) }) +const formEnvelope = z.object({ data: wireFormSchema, location: location.optional() }) + +/** One admitted native GET. Every body is bounded and validated before the SDK sees it. */ +export async function readExplicitForm(args: { + acquire: () => Promise + current: () => void + signal: AbortSignal + sessionId: string + formId: string + directory: string +}) { + const { signal, sessionId, formId, directory } = args + const wait = (pending: Promise) => waitForAdmission(pending, signal) + const current = () => { signal.throwIfAborted(); args.current(); connection?.assertCurrent() } + let connection: ServiceConnection | undefined + current() + connection = await wait(args.acquire()) + current() + if (!connection) throw new Error("Form verification unavailable") + await wait(connection.profile(signal)) + current() + const transport = boundedResponseFetch(connection.fetch, signal, current, FORM_VERIFICATION_LIMIT) + const client = OpenCode.make({ baseUrl: connection.endpoint.url, fetch: async (input, init) => { + current() + const response = await wait(transport(input, init)) + current() + // All error statuses, including native absence, remain indeterminate. The wire + // body never becomes an SDK Error whose inherited message could supply proof. + if (response.status !== 200 || !/^application\/json\s*(?:;|$)/i.test(response.headers.get("content-type") ?? "")) throw new Error("Invalid Form verification response") + const value: unknown = JSON.parse(await wait(response.text()), (_key, item) => { + if (typeof item === "number" && !Number.isFinite(item)) throw new Error("Invalid JSON number") + return item + }) + current() + const path = new URL(input instanceof Request ? input.url : input).pathname + if (path.endsWith(`/form/${formId}`)) { + const parsed = formEnvelope.safeParse(value) + if (!parsed.success || parsed.data.data.id !== formId || parsed.data.data.sessionID !== sessionId + || (parsed.data.location && (parsed.data.location.directory !== directory || parsed.data.location.workspaceID !== undefined))) throw new Error("Invalid Form identity or state") + const form = parsed.data.data + // Validate the complete native answer, then discard it before publication. + return Response.json({ data: { ...form, state: { status: form.state.status } } }) + } + const parsed = sessionEnvelope.safeParse(value) + if (!parsed.success || parsed.data.data.id !== sessionId || parsed.data.data.location.directory !== directory + || parsed.data.data.location.workspaceID !== undefined) throw new Error("Invalid Form session placement") + return Response.json(parsed.data) + } }) + const session = async () => { + current() + if (sessionId !== "global") await wait(client.session.get({ sessionID: sessionId }, { signal })) + current() + } + await session() + const result = await wait(client.session.form.get({ sessionID: sessionId, formID: formId }, { + signal, ...(sessionId === "global" ? { headers: { "x-opencode-directory": encodeURIComponent(directory) } } : {}), + })) + current() + await session() + current() + return { data: result } +} diff --git a/packages/server/src/server/explicit-proxy.ts b/packages/server/src/server/explicit-proxy.ts new file mode 100644 index 0000000000..54544fbc05 --- /dev/null +++ b/packages/server/src/server/explicit-proxy.ts @@ -0,0 +1,291 @@ +import type { FastifyReply, FastifyRequest } from "fastify" +import { isInvalidRequestError, isSessionNotFoundError } from "@opencode/client" +import type { InstanceProxyWorkspaceManager } from "./http-server" +import { WorkspaceCapabilityError, type ServerCapability } from "../opencode/servers/capabilities" +import { LOCATION_CONTEXT_HEADER, readLocationContext, readLocationRef } from "../opencode/compatibility/location" +import { decodeMessageListCursor, decodeSessionListScope } from "../opencode/compatibility/proxy-locations" +import { deferToolMedia, wantsDeferredMedia } from "../opencode/session-media" +import { forwardRuntimeRequest } from "../opencode/compatibility/proxy" +import { validatePromptAttachmentBudget } from "./prompt-attachment-budget" +import { readExplicitForm } from "./explicit-form-verification" +import { FORM_VERIFICATION_TIMEOUT_MS } from "../opencode/form-verification-policy" + +/** Closed E1 product operations; adding upstream APIs requires a policy review. */ +function operation(method: string, path: string): ServerCapability | undefined { + if (method === "GET" && /^\/api\/(?:agent(?:\/[^/]+)?|command|location|mcp|model(?:\/default)?|provider|reference|skill|websearch\/provider)$/.test(path)) return "chat" + if (method === "GET" && /^\/api\/session(?:\/active)?$/.test(path)) return "sessions" + if (method === "POST" && path === "/api/session") return "sessions" + if (method === "GET" && /^\/api\/session\/[^/]+(?:\/message(?:\/[^/]+)?|\/inbox)?$/.test(path)) return "sessions" + if (["PATCH", "DELETE"].includes(method) && /^\/api\/session\/[^/]+$/.test(path)) return "sessions" + if (["PATCH", "DELETE"].includes(method) && /^\/api\/session\/[^/]+\/inbox\/[^/]+$/.test(path)) return "chat" + if (method === "POST" && /^\/api\/session\/[^/]+\/(?:agent|model|prompt|command|shell|compact|interrupt|fork|generate)$/.test(path)) return "chat" + if ((method === "GET" && /^\/api\/experimental\/session\/[^/]+\/instructions\/entries$/.test(path)) + || (["PUT", "DELETE"].includes(method) && /^\/api\/experimental\/session\/[^/]+\/instructions\/entries\/[^/]+$/.test(path))) return "chat" + if (method === "POST" && /^\/api\/session\/[^/]+\/permission\/[^/]+\/reply$/.test(path)) return "permissions" + if ((method === "POST" && /^\/api\/session\/[^/]+\/form\/[^/]+\/reply$/.test(path)) + || (method === "GET" && /^\/api\/session\/[^/]+\/form\/[^/]+$/.test(path)) + || (method === "DELETE" && /^\/api\/session\/[^/]+\/form\/[^/]+$/.test(path))) return "questions" + // prototype-1236: branch read and the background-shell panel's operations. Never credentials or config. + if (method === "GET" && path === "/api/vcs") return "git" + // Runtime MCP connect/disconnect of servers the remote configuration already declares (no config write). + if (method === "POST" && /^\/api\/experimental\/mcp\/[^/]+\/(?:connect|disconnect)$/.test(path)) return "plugins" + if ((method === "GET" && /^\/api\/shell(?:\/[^/]+(?:\/output)?)?$/.test(path)) + || (method === "DELETE" && /^\/api\/shell\/[^/]+$/.test(path))) return "backgroundShells" + return undefined +} + +function deferredCapability(path: string): ServerCapability { + if (/\/fs\//.test(path)) return "files" + if (/\/vcs(?:\/|$)/.test(path)) return "git" + if (/\/diff$/.test(path)) return "conversationDiffs" + if (/\/move$|\/worktree(?:\/|$)/.test(path)) return "worktrees" + if (/\/pty(?:\/|$)/.test(path)) return "terminal" + if (/^\/api\/shell(?:\/|$)/.test(path)) return "backgroundShells" + if (/\/environment$/.test(path)) return "sessionEnvironment" + if (/\/(?:form|permission\/request)$/.test(path)) return "pendingRecovery" + if (/\/rpc\//.test(path)) return "historyEnrichment" + return "executionSettings" +} + +const object = (value: unknown): value is Record => Boolean(value) && typeof value === "object" && !Array.isArray(value) && !Buffer.isBuffer(value) + +/** No host adapters, global clients, environment snapshots, receipts or account activation. */ +export async function proxyExplicitWorkspaceRequest(args: { + request: FastifyRequest; reply: FastifyReply; workspaceManager: InstanceProxyWorkspaceManager + workspaceId: string; workspace: NonNullable> + pathname: string; signal: AbortSignal; wait(pending: Promise): Promise +}) { + const { request, reply, workspaceManager: manager, workspaceId: id, workspace, wait } = args + const path = args.pathname.replace(/\/+$/, ""), method = request.method + const formRead = method === "GET" && path.match(/^\/api\/session\/([^/]+)\/form\/([^/]+)$/) + // A single deadline includes admission, acquisition, profile and all three reads. + const formExpiresAt = formRead ? performance.now() + FORM_VERIFICATION_TIMEOUT_MS : 0 + const formDeadline = formRead ? AbortSignal.timeout(FORM_VERIFICATION_TIMEOUT_MS) : undefined + const capability = operation(method, path) + let workspaceSignal: AbortSignal + try { + // A URL can select an operation, never a caller-supplied capability name. + if (!capability) { + const denied = deferredCapability(path) + manager.requireWorkspaceCapability?.(id, denied) + throw new WorkspaceCapabilityError(denied, { code: "deferred" }) + } + if (!manager.requireWorkspaceCapability) throw new WorkspaceCapabilityError(capability, { code: "contractUnverified" }) + workspaceSignal = manager.requireWorkspaceCapability(id, capability) + } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, capability: error.capability, reason: error.reason }) + throw error + } + const signal = AbortSignal.any([args.signal, workspaceSignal]) + signal.throwIfAborted() + + const directory = workspace.binding!.directory + const query = new URLSearchParams((request.raw.url ?? "").split("?").slice(1).join("?")) + const locations: unknown[] = [] + const sessionMatch = path.match(/^\/api\/(?:experimental\/)?session\/([^/]+)(?:\/|$)/) + const sessionId = sessionMatch && sessionMatch[1] !== "active" ? sessionMatch[1] : undefined + const globalForm = sessionId === "global" && /\/form\//.test(path) + let body = request.body + const expectedGeneration = request.headers["x-codenomad-connection-generation"] + try { + // Malformed escapes and multiply encoded route segments have no native authority. + if (/%|\\/.test(path) || path.split("/").some(value => value === "." || value === "..")) throw new Error() + const rawHeaders = request.raw.rawHeaders + const counts = new Map() + for (let i = 0; i < rawHeaders.length; i += 2) counts.set(rawHeaders[i].toLowerCase(), (counts.get(rawHeaders[i].toLowerCase()) ?? 0) + 1) + for (const name of [LOCATION_CONTEXT_HEADER, "x-opencode-directory", "x-opencode-workspace", "x-codenomad-connection-generation"]) if ((counts.get(name) ?? 0) > 1) throw new Error() + if (expectedGeneration !== undefined && (typeof expectedGeneration !== "string" || !/^[1-9]\d*$/.test(expectedGeneration) + || !Number.isSafeInteger(Number(expectedGeneration)))) throw new Error() + if (request.headers["x-opencode-workspace"] !== undefined || request.headers["x-codenomad-human-answer"] !== undefined + || request.headers["x-codenomad-pending-reconciliation"] !== undefined) throw new Error() + const context = readLocationContext(request.headers[LOCATION_CONTEXT_HEADER]) + if (context) locations.push(context.directory) + const header = request.headers["x-opencode-directory"] + if (header !== undefined) { + if (!globalForm || typeof header !== "string") throw new Error() + locations.push(decodeURIComponent(header)) + } + for (const key of query.keys()) { + if (query.getAll(key).length !== 1) throw new Error() + if (["directory", "location[directory]"].includes(key)) locations.push(query.get(key)) + else if (!(method === "GET" && ["cursor", "limit", "order", "search", "parentID", "archived"].includes(key)) + && !(method === "POST" && /\/interrupt$/.test(path) && key === "resume") + && !(method === "DELETE" && /\/form\/[^/]+$/.test(path) && key === "message")) throw new Error() + } + if (query.has("directory") && query.has("location[directory]")) throw new Error() + if (body !== undefined) { + if (!object(body) || request.headers["content-type"]?.split(";")[0].trim().toLowerCase() !== "application/json") throw new Error() + const input = body + if (["workspace", "workspaceID", "cwd", "project", "projectID", "subpath"].some(key => key in input)) throw new Error() + if ("directory" in body) locations.push(body.directory) + if ("location" in body) { + if (!object(body.location) || Object.keys(body.location).some(key => key !== "directory")) throw new Error() + locations.push(body.location.directory) + } + if ("directory" in body && "location" in body) throw new Error() + if (method === "POST" && path === "/api/session" && "parentID" in body) throw new Error() + if ("files" in body && (!Array.isArray(body.files) || body.files.some(file => !object(file) || typeof file.uri !== "string" || !file.uri.startsWith("data:")))) { + return reply.code(403).send({ error: "explicit_capability_unavailable", capability: "files", reason: { code: "deferred" } }) + } + } + if (locations.some(value => value !== directory)) throw new Error() + if (query.has("cursor") && path === "/api/session") { + const scope = decodeSessionListScope(query.get("cursor")!) + if (scope?.directory !== directory || scope.project !== undefined || scope.subpath !== undefined + || query.has("directory") || query.has("location[directory]") || (object(body) && ("location" in body || "directory" in body))) throw new Error() + } + if (method === "GET" && /^\/api\/session\/[^/]+\/message$/.test(path)) { + if (query.has("cursor") && (query.has("order") || !decodeMessageListCursor(query.get("cursor")!))) throw new Error() + if (query.has("order") && !["asc", "desc"].includes(query.get("order")!)) throw new Error() + if (query.has("limit") && (!/^\d+$/.test(query.get("limit")!) || Number(query.get("limit")) < 1 || Number(query.get("limit")) > 200)) throw new Error() + } + const budget = validatePromptAttachmentBudget(path, method, body) + if (!budget.ok) return reply.code(budget.reason === "limit" ? 413 : 400).send({ error: "Invalid prompt attachments" }) + } catch { return reply.code(400).send({ error: "Invalid explicit workspace scope" }) } + + // Only this capture supplies endpoint, client and fetch. Never fall back to local. + const matchesGeneration = () => expectedGeneration === undefined + || manager.get(id)?.capabilities?.generation === Number(expectedGeneration) + if (!matchesGeneration()) return reply.code(409).send({ error: "explicit_action_superseded" }) + if (formRead) { + reply.header("Cache-Control", "no-store") + const formSignal = AbortSignal.any([signal, formDeadline!]) + const formCurrent = () => { + formSignal.throwIfAborted() + // Parsing can finish in a microtask before the deadline timer gets its turn. + if (performance.now() >= formExpiresAt || !matchesGeneration() || manager.get(id)?.binding !== workspace.binding) throw new Error("Form verification superseded") + manager.requireWorkspaceCapability!(id, "questions") + } + try { + const result = await readExplicitForm({ + acquire: () => Promise.resolve(manager.getSharedServiceConnection?.(id)), + current: formCurrent, + signal: formSignal, sessionId: formRead[1], formId: formRead[2], directory, + }) + formCurrent() + return reply.send(result) + } catch { + if (signal.aborted || reply.raw.destroyed) { reply.hijack(); return } + return reply.code(503).send({ error: "form_verification_indeterminate" }) + } + } + const connection = await wait(Promise.resolve(manager.getSharedServiceConnection?.(id))) + if (!connection) return reply.code(503).send({ error: "OpenCode service is not ready" }) + const current = () => { + signal.throwIfAborted() + connection.assertCurrent() + if (!matchesGeneration()) throw new Error("Explicit action was superseded") + if (manager.get(id)?.binding !== workspace.binding) throw new Error("Workspace changed") + manager.requireWorkspaceCapability!(id, capability) + } + current() + await wait(connection.profile(signal)) + current() + const owns = (session: { id: string; location: { directory: string; workspaceID?: string } }) => session.id === sessionId + && session.location.directory === directory && session.location.workspaceID === undefined + const checkSession = async () => { + current() + if (!sessionId || globalForm) return + const session = await wait(connection.client.session.get({ sessionID: sessionId }, { signal })) + current() + if (!owns(session)) throw new Error("Session does not belong to workspace") + } + try { await checkSession() } catch (error) { + current() + if (isSessionNotFoundError(error)) return reply.code(404).send({ _tag: "SessionNotFoundError", sessionID: sessionId, message: "Session not found" }) + if (isInvalidRequestError(error)) return reply.code(400).send({ error: "Invalid session ID" }) + return reply.code(403).send({ error: "Session does not belong to workspace" }) + } + // prototype-1236: a shell is the project's when its working directory is the folder or inside it. + const separator = /^[A-Za-z]:\\/.test(directory) || (directory.includes("\\") && !directory.includes("/")) ? "\\" : "/" + const root = directory.replace(/[\\/]+$/, "") + const ownsCwd = (cwd: unknown) => typeof cwd === "string" && (cwd.replace(/[\\/]+$/, "") === root || cwd.startsWith(root + separator)) + const shellId = path.match(/^\/api\/shell\/([^/]+)/)?.[1] + if (shellId) { + let shell + try { shell = await wait(connection.client.shell.get({ id: shellId as never, location: { directory } }, { signal })) } + catch { current(); return reply.code(404).send({ error: "Shell not found" }) } + current() + if (shell.location?.directory !== directory || !ownsCwd(shell.data?.cwd)) return reply.code(403).send({ error: "Shell does not belong to workspace" }) + } + const target = new URL(path, connection.endpoint.url) + target.search = query.toString() + if (method === "GET" && path === "/api/session" && !query.has("cursor")) { + target.searchParams.delete("location[directory]") + target.searchParams.set("directory", directory) + } else if (!sessionId && path !== "/api/session/active" && path !== "/api/session") { + target.searchParams.delete("directory") + target.searchParams.set("location[directory]", directory) + } + if (method === "POST" && path === "/api/session") body = { ...(object(body) ? body : {}), location: { directory } } + // Allow headers by role; auth, cookies, forwarding and internal control headers + // stay at the CodeNomad boundary. The protected target transport supplies auth. + const headers: Record = {} + for (const name of ["accept", "content-type"]) if (typeof request.headers[name] === "string") headers[name] = request.headers[name] + if (globalForm) headers["x-opencode-directory"] = encodeURIComponent(directory) + return forwardRuntimeRequest({ request, reply, url: target.toString(), body, headers, + invalidate: () => connection.invalidate(), + assertCurrent: current, + fetch: async (input, init) => { + // Scope was read above; header/body preparation since then is synchronous. + // Recheck lifetime and generation at the actual dispatch boundary. + current() + const response = await connection.fetch(input, { ...init, signal: AbortSignal.any([signal, ...(init?.signal ? [init.signal] : [])]), redirect: "error" }) + current() + // ponytail: finite E1 responses cap at 64 MiB; a streaming reader needs its + // own publication protocol before adding streaming operations here. + // Hold responses until their scope and captured + // generation are revalidated; never publish a partial stale response. + const reader = response.body?.getReader(), chunks: Uint8Array[] = [] + let size = 0 + try { + while (reader) { + const chunk = await wait(reader.read()) + current() + if (chunk.done) break + size += chunk.value.byteLength + if (size > 64 * 1024 * 1024) throw new Error("Explicit response too large") + chunks.push(chunk.value) + } + } catch (error) { await reader?.cancel().catch(() => {}); throw error } + finally { reader?.releaseLock() } + // Deleted sessions cannot be re-read; the pre-dispatch ownership check still applies. + if (!(method === "DELETE" && path === `/api/session/${sessionId}` && response.ok)) await checkSession() + current() + let bytes = Buffer.concat(chunks, size) + if (response.ok && /^application\/json\b/i.test(response.headers.get("content-type") ?? "")) { + const value = JSON.parse(bytes.toString("utf8")) + if ((value.location !== undefined && (value.location?.directory !== directory || value.location.workspaceID !== undefined)) + || (path === "/api/location" && (value.directory !== directory || value.workspaceID !== undefined))) throw new Error("Unowned response location") + if (method === "GET" && path === "/api/session/active") { + for (const key of Object.keys(value.data ?? {})) { + let session + try { session = await wait(connection.client.session.get({ sessionID: key }, { signal })) } + catch (error) { + current() + if (!isSessionNotFoundError(error)) throw error + delete value.data[key] + continue + } + current() + if (session.id !== key || session.location.directory !== directory || readLocationRef(session.location).workspaceID !== undefined) delete value.data[key] + } + } + if (method === "GET" && path === "/api/session" && (!Array.isArray(value.data) + || value.data.some((session: { location?: { directory?: string; workspaceID?: string } }) => session.location?.directory !== directory || session.location.workspaceID !== undefined))) throw new Error("Unowned session list") + if (method === "POST" && (path === "/api/session" || /\/fork$/.test(path)) + && (value.data?.location?.directory !== directory || value.data.location.workspaceID !== undefined)) throw new Error("Unowned session result") + if (method === "GET" && path === `/api/session/${sessionId}` && !owns(value.data)) throw new Error("Unowned session result") + if (method === "GET" && path === "/api/shell") { + if (!Array.isArray(value.data)) throw new Error("Unowned shell list") + value.data = value.data.filter((shell: { cwd?: unknown }) => ownsCwd(shell?.cwd)) + } + if (method === "GET" && shellId && !path.endsWith("/output") && !ownsCwd(value.data?.cwd)) throw new Error("Unowned shell result") + if (sessionId && method === "GET" && /\/message$/.test(path) && wantsDeferredMedia(request.headers)) deferToolMedia(value.data, { workspaceId: id, sessionId }) + bytes = Buffer.from(JSON.stringify(value)) + } + current() + return new Response(response.body ? bytes : null, { status: response.status, headers: response.headers }) + }, + }) +} diff --git a/packages/server/src/server/http-server.ts b/packages/server/src/server/http-server.ts index 15f21fbf6f..e8ba077996 100644 --- a/packages/server/src/server/http-server.ts +++ b/packages/server/src/server/http-server.ts @@ -20,10 +20,14 @@ import { syncSessionGitContext } from "../workspaces/session-git-context" import { assertOrdinaryMissionScheduleBody, assertOrdinaryMissionScheduleSession, MissionScheduleInputError } from "./mission-schedule-input-guard" import { readGitStatus } from "../workspaces/git-requirement" import { registerSettingsRoutes } from "./routes/settings" +import { registerOpenCodeServerAdminGuard, registerOpenCodeServerAdminPrivacy, registerOpenCodeServerRoutes, isOpenCodeServerAdminTarget } from "./routes/opencode-servers" +import { registerOpenCodeFolderRoutes } from "./routes/opencode-folders" import { registerFilesystemRoutes } from "./routes/filesystem" import { registerConfigFileRoutes } from "./routes/config-files" import { registerMetaRoutes } from "./routes/meta" import { registerEventRoutes } from "./routes/events" +import { isProjectParticipationTarget, registerProjectParticipationPrivacy, registerProjectParticipationRoutes } from "./routes/project-participation" +import { ProjectParticipants } from "../workspaces/project-participants" import { registerStorageRoutes } from "./routes/storage" import { registerYoloRoutes } from "./routes/yolo" import { registerPermissionReceiptRoutes } from "./routes/permission-receipts" @@ -77,7 +81,7 @@ import { registerOpenCodeLoginStartRoutes } from "./routes/opencode-login-start" import { registerSubagentDepthSettingsRoutes } from "./routes/subagent-depth-settings" import { ImageSettings } from "../opencode/image-settings" import { registerImageSettingsRoutes } from "./routes/image-settings" -import { PROMPT_INLINE_FILE_LIMITS, ServerMeta, SESSION_ENVIRONMENT_FAILED_ERROR_CODE } from "../api-types" +import { PROMPT_INLINE_FILE_LIMITS, ServerMeta, SESSION_ENVIRONMENT_FAILED_ERROR_CODE, EXPLICIT_REQUEST_UNCERTAIN_ERROR_CODE } from "../api-types" import { InstanceStore } from "../storage/instance-store" import type { AutoAcceptManager } from "../permissions/auto-accept-manager" import type { AuthManager } from "../auth/manager" @@ -101,6 +105,7 @@ import { parsePreviewUpgradePath } from "../previews/upgrade-path" import { forwardRuntimeRequest } from "../opencode/compatibility/proxy" import { requestAdmission } from "./request-admission" import { LOCATION_CONTEXT_HEADER, locationRequestOptions, readLocationContext, readLocationRef, sameLocation } from "../opencode/compatibility/location" +import { proxyExplicitWorkspaceRequest } from "./explicit-proxy" import { DEFERRED_MEDIA_HEADER, deferToolMedia, wantsDeferredMedia } from "../opencode/session-media" import { decodeSessionListScope, prepareLocationImport, readRequestLocations, type SessionListScope } from "../opencode/compatibility/proxy-locations" import type { RemoteProxySessionManager } from "./remote-proxy" @@ -170,6 +175,11 @@ export function createHttpServer(deps: HttpServerDeps) { const app = Fastify( ({ logger: false, + frameworkErrors: (error: unknown, request: FastifyRequest, reply: FastifyReply) => { + // Router decoding can fail before hooks; never echo the unparsed target. + if (!isOpenCodeServerAdminTarget(request.raw.url ?? request.url) && !isProjectParticipationTarget(request.raw.url ?? request.url)) { reply.send(error); return } + reply.header("cache-control", "no-store").code(400).send({ error: "invalid_request", code: "invalid_request" }) + }, ...(deps.protocol === "https" && deps.httpsOptions ? { https: deps.httpsOptions } : {}), } as unknown) as any, ) as unknown as FastifyInstance @@ -190,6 +200,8 @@ export function createHttpServer(deps: HttpServerDeps) { } registerRequestLogging(app, apiLogger) + registerOpenCodeServerAdminPrivacy(app) + registerProjectParticipationPrivacy(app) // Remote Control admission runs before CORS, authentication and routing. const remoteGate = deps.remoteControlManager.gate() @@ -219,6 +231,13 @@ export function createHttpServer(deps: HttpServerDeps) { return origins } + registerOpenCodeServerAdminGuard(app, { auth: deps.authManager, selfOrigins: getSelfOrigins, devOrigins: allowedDevOrigins, protocol: deps.protocol }) + const participation = deps.workspaceManager.projectParticipants instanceof ProjectParticipants + ? registerProjectParticipationRoutes(app, { auth: deps.authManager, remote: deps.remoteControlManager, + owner: deps.workspaceManager.projectParticipants, manager: deps.workspaceManager, + selfOrigins: getSelfOrigins, devOrigins: allowedDevOrigins, protocol: deps.protocol }) + : undefined + app.register(cors, { origin: (origin, cb) => { if (!origin) { @@ -371,6 +390,8 @@ export function createHttpServer(deps: HttpServerDeps) { const loginStart = createOpenCodeLoginStart(deps.settings, deps.workspaceManager) registerOpenCodeLoginStartRoutes(app, { loginStart, auth: deps.authManager, remoteDevices: deps.remoteControlManager }) registerSettingsRoutes(app, { settings: deps.settings, logger: apiLogger, refreshLoginStart: () => loginStart.refresh() }) + registerOpenCodeServerRoutes(app, { settings: deps.settings, connections: () => deps.workspaceManager.getServerConnections() }) + registerOpenCodeFolderRoutes(app, { connections: () => deps.workspaceManager.getServerConnections() }) // prototype-1236 const accounts = new ProviderAccountsService(deps.settings) const stopQuotaObserver = observeProviderQuotaFailures(deps.eventBus, accounts) app.addHook("onClose", async () => stopQuotaObserver()) @@ -388,6 +409,7 @@ export function createHttpServer(deps: HttpServerDeps) { registerClient: registerSseClient, logger: sseLogger, connectionManager: deps.clientConnectionManager, + participation, }) registerWorktreeRoutes(app, { workspaceManager: deps.workspaceManager, worktreeDeletionFence }) registerPendingRequestRoutes(app, { workspaceManager: deps.workspaceManager, worktreeDeletionFence }) @@ -515,6 +537,7 @@ export function createHttpServer(deps: HttpServerDeps) { } export interface InstanceProxyWorkspaceManager { + requireWorkspaceCapability?(id: string, capability: import("../opencode/servers/capabilities").ServerCapability): AbortSignal get(id: string): ReturnType getSharedServiceEndpoint(id: string): ReturnType getSharedServiceConnection?(id: string): ReturnType @@ -817,6 +840,14 @@ async function proxyWorkspaceAdmission(args: InstanceProxyRequestArgs, admission return } const pathname = decodeURIComponent(routeUrl.pathname) + if (workspace.binding?.serverId && workspace.binding.serverId !== "local-shared") { + try { + return await proxyExplicitWorkspaceRequest({ request, reply, workspaceManager, workspaceId, workspace, pathname, signal, wait }) + } catch { + signal.throwIfAborted() + return reply.code(502).send({ error: EXPLICIT_REQUEST_UNCERTAIN_ERROR_CODE, message: "Explicit OpenCode request unavailable; do not replay uncertain mutations" }) + } + } if (!isAllowedInstanceApiRoute(request.method, pathname)) { reply.code(403).send({ error: "OpenCode route is not available through a workspace" }) return @@ -1408,6 +1439,7 @@ function sanitizeInstanceProxyRequestHeaders( LOCATION_CONTEXT_HEADER, HUMAN_ANSWER_HEADER, DEFERRED_MEDIA_HEADER, + "x-codenomad-connection-generation", ]) const connection = headers.connection for (const name of (Array.isArray(connection) ? connection.join(",") : connection ?? "").split(",")) blocked.add(name.trim().toLowerCase()) diff --git a/packages/server/src/server/request-admission.ts b/packages/server/src/server/request-admission.ts index 2bcd05429d..c03bd3c877 100644 --- a/packages/server/src/server/request-admission.ts +++ b/packages/server/src/server/request-admission.ts @@ -13,29 +13,32 @@ export function requestAdmission(request: FastifyRequest, reply: FastifyReply) { if (request.raw.aborted || reply.raw.destroyed) abort() return { signal: controller.signal, - async wait(pending: Promise): Promise { - if (controller.signal.aborted) { - // A caller may already have allocated the Promise. Observe its rejection - // even when admission was revoked immediately before this boundary. - void pending.catch(() => undefined) - controller.signal.throwIfAborted() - } - let rejectAbort!: () => void - const aborted = new Promise((_resolve, reject) => { - rejectAbort = () => reject(controller.signal.reason) - controller.signal.addEventListener("abort", rejectAbort, { once: true }) - }) - try { - const result = await Promise.race([pending, aborted]) - controller.signal.throwIfAborted() - return result - } finally { - controller.signal.removeEventListener("abort", rejectAbort) - } - }, + wait: (pending: Promise) => waitForAdmission(pending, controller.signal), dispose() { request.raw.off("aborted", abort) reply.raw.off("close", close) }, } } + +/** Stop one observer without cancelling shared acquisition or awaiting body cleanup. */ +export async function waitForAdmission(pending: Promise, signal: AbortSignal): Promise { + if (signal.aborted) { + // A caller may already have allocated the Promise. Observe its rejection + // even when admission was revoked immediately before this boundary. + void pending.catch(() => undefined) + signal.throwIfAborted() + } + let rejectAbort!: () => void + const aborted = new Promise((_resolve, reject) => { + rejectAbort = () => reject(signal.reason) + signal.addEventListener("abort", rejectAbort, { once: true }) + }) + try { + const result = await Promise.race([pending, aborted]) + signal.throwIfAborted() + return result + } finally { + signal.removeEventListener("abort", rejectAbort) + } +} diff --git a/packages/server/src/server/request-logging.ts b/packages/server/src/server/request-logging.ts index 901845b5c0..96508d5837 100644 --- a/packages/server/src/server/request-logging.ts +++ b/packages/server/src/server/request-logging.ts @@ -2,6 +2,8 @@ import type { FastifyInstance, FastifyRequest } from "fastify" import type { Logger } from "../logger" import { isHumanAnswerProofPayload } from "../missions/human-answer" import { isRecurrenceProofPayload } from "../missions/recurrence-control-proof" +import { isOpenCodeServerAdminTarget } from "./routes/opencode-servers" +import { isProjectParticipationTarget } from "./routes/project-participation" const integrationRoute = "/api/workspaces/:id/integrations" const integrationRoutes = new Set([integrationRoute, "/api/workspaces/:id/plugin-sources", ...["hosts", "binding", "attach", "detach", "install", "install-host"].map(action => `${integrationRoute}/:integrationId/${action}`)]) @@ -30,10 +32,17 @@ export function registerRequestLogging(app: FastifyInstance, apiLogger: Logger) const start = starts.get(request) const durationMs = start === undefined ? undefined : Number((process.hrtime.bigint() - start) / BigInt(1_000_000)) const integration = integrationLogRoute(request) - const base = { method: request.method, url: integration ?? request.url, status: reply.statusCode, durationMs } + const privateAdmin = isOpenCodeServerAdminTarget(request.raw.url ?? request.url) + const privateParticipation = isProjectParticipationTarget(request.raw.url ?? request.url) + const privatePayload = privateAdmin || privateParticipation + const base = { + method: privatePayload && !["GET", "POST", "HEAD", "OPTIONS", "PATCH", "PUT", "DELETE"].includes(request.method) ? "OTHER" : request.method, + url: privateAdmin ? "/api/opencode-servers/" : privateParticipation ? "/api/project-participation/" : integration ?? request.url, + status: reply.statusCode, durationMs, + } apiLogger.debug(base, "HTTP request completed") if (apiLogger.isLevelEnabled("trace")) { - apiLogger.trace(integration ? base : { + apiLogger.trace(integration || privatePayload ? base : { ...base, params: redactSecrets(request.params), query: redactSecrets(request.query), diff --git a/packages/server/src/server/routes/automation-plugin.test.ts b/packages/server/src/server/routes/automation-plugin.test.ts index 9d7e2b1b97..73d8ac00a5 100644 --- a/packages/server/src/server/routes/automation-plugin.test.ts +++ b/packages/server/src/server/routes/automation-plugin.test.ts @@ -4,6 +4,42 @@ import Fastify from "fastify" import { AUTOMATION_BRIDGE_PATH } from "../../opencode/automation-plugin" import { registerAutomationPluginRoute } from "./automation-plugin" +test("explicit-only bindings never acquire the local client or reach host automation, even for identical IDs and paths", async t => { + const app = Fastify() + t.after(() => app.close()) + const unexpected = () => { throw new Error("Explicit workspace crossed the local bridge") } + registerAutomationPluginRoute(app, { + authManager: { isLoopbackRequest: () => true }, bridgeToken: "fixture", + nativeParent: { available: true, request: unexpected }, developerCdp: {}, + workspaceManager: { list: () => [{ id: "explicit", binding: { serverId: "loopback-explicit", directory: "/repo" } }], + getSharedServiceClient: unexpected, ownsLocation: unexpected }, + } as never) + for (const mode of ["browser-claim", "browser-probe", "browser-execute", "developer-probe", "developer-execute", "mission-input"]) { + const result = await app.inject({ method: "POST", url: AUTOMATION_BRIDGE_PATH, + headers: { "x-codenomad-automation-token": "fixture" }, payload: { mode, sessionID: "ses_same" } }) + assert.equal(result.statusCode, 403) + assert.deepEqual(result.json(), { error: "explicit_capability_unavailable", code: "explicit_capability_unavailable", + capability: mode === "mission-input" ? "missions" : "automation", reason: { code: "deferred" } }) + } +}) + +test("an explicit workspace sharing a local session path cannot become a bridge owner", async t => { + const app = Fastify(), checked: string[] = [] + t.after(() => app.close()) + registerAutomationPluginRoute(app, { + authManager: { isLoopbackRequest: () => true }, bridgeToken: "fixture", nativeParent: { available: true }, developerCdp: {}, + workspaceManager: { + list: () => [{ id: "explicit", binding: { serverId: "loopback-explicit", directory: "/repo" } }, { id: "local" }], + getSharedServiceClient: async () => ({ session: { get: async () => ({ location: { directory: "/repo" } }) } }), + ownsLocation: async (id: string) => { checked.push(id); return id === "explicit" }, + }, + } as never) + const result = await app.inject({ method: "POST", url: AUTOMATION_BRIDGE_PATH, + headers: { "x-codenomad-automation-token": "fixture" }, payload: { mode: "browser-claim", sessionID: "ses_same" } }) + assert.equal(result.statusCode, 404) + assert.deepEqual(checked, ["local"]) +}) + test("a slow unrelated workspace cannot hide an already verified automation owner", { timeout: 2_000 }, async t => { const app = Fastify() let unblock!: () => void diff --git a/packages/server/src/server/routes/automation-plugin.ts b/packages/server/src/server/routes/automation-plugin.ts index 4b79cfcabf..0263fc100a 100644 --- a/packages/server/src/server/routes/automation-plugin.ts +++ b/packages/server/src/server/routes/automation-plugin.ts @@ -1,4 +1,6 @@ import { timingSafeEqual } from "node:crypto" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" +import { localMissionWorkspaces } from "../../missions/workspace-capability" import type { FastifyInstance, FastifyRequest } from "fastify" import type { AuthManager } from "../../auth/manager" import type { DeveloperCdp } from "../../developer-cdp" @@ -69,14 +71,20 @@ export function registerAutomationPluginRoute(app: FastifyInstance, deps: Automa if (!deps.settings) return reply.code(503).send({ error: "Human answer admission unavailable" }) try { return reply.send({ result: await verifyMissionHumanAnswer(body.command, { auth: deps.authManager, manager: deps.workspaceManager, settings: deps.settings, remoteDevices: deps.remoteDevices }, lifetime.signal) }) } - catch { return reply.code(403).send({ error: "Human answer admission unavailable" }) } + catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + return reply.code(403).send({ error: "Human answer admission unavailable" }) + } } if (body?.mode === "recurrence-control-verify") { try { return reply.send({ result: await verifyHumanRecurrenceRequest(body.command, { auth: deps.authManager, manager: deps.workspaceManager, settings: deps.settings, remoteDevices: deps.remoteDevices, }, lifetime.signal) }) - } catch { return reply.code(403).send({ error: "Recurrence human admission unavailable" }) } + } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + return reply.code(403).send({ error: "Recurrence human admission unavailable" }) + } } if (!body || !["developer-probe", "developer-execute", "browser-claim", "browser-probe", "browser-execute", "mission-input"].includes(String(body.mode)) || typeof body.sessionID !== "string" || body.sessionID.length > 256) { @@ -89,6 +97,12 @@ export function registerAutomationPluginRoute(app: FastifyInstance, deps: Automa const signal = body.mode === "mission-input" ? AbortSignal.any([lifetime.signal, AbortSignal.timeout(lifecycle ? 85_000 : 30_000)]) : lifetime.signal + const candidates = localMissionWorkspaces(deps.workspaceManager) + if (!candidates.length) { + if (!deps.workspaceManager.list().length) return reply.code(404).send({ error: "Session is not owned by this CodeNomad instance" }) + const capability = body.mode === "mission-input" || body.purpose === "mission" ? "missions" : "automation" + return reply.code(403).send({ error: "explicit_capability_unavailable", code: "explicit_capability_unavailable", capability, reason: { code: "deferred" } }) + } let location try { signal.throwIfAborted() @@ -100,7 +114,7 @@ export function registerAutomationPluginRoute(app: FastifyInstance, deps: Automa } // One validated owner is sufficient. Waiting for every unrelated inventory // can exceed the plugin's discovery deadline despite a ready local owner. - const owned = await lifetime.wait(Promise.any(deps.workspaceManager.list().map(async workspace => { + const owned = await lifetime.wait(Promise.any(candidates.map(async workspace => { if (!await deps.workspaceManager.ownsLocation(workspace.id, location, undefined, signal)) throw new Error("Not an owner") return true }))).catch(() => false) diff --git a/packages/server/src/server/routes/config-files.ts b/packages/server/src/server/routes/config-files.ts index d1854966bd..0fc6fc869c 100644 --- a/packages/server/src/server/routes/config-files.ts +++ b/packages/server/src/server/routes/config-files.ts @@ -1,4 +1,4 @@ -import { FastifyInstance } from "fastify" +import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify" import fs from "fs/promises" import os from "os" import path from "path" @@ -15,7 +15,8 @@ interface ConfigFileRouteOptions { const ConfigFileContentBodySchema = z.object({ contents: z.string(), -}) +}).strict() +const HostOnlyQuerySchema = z.object({}).strict() function resolveOpenCodeGlobalConfigPaths(): ConfigFileEntry[] { if (process.platform === "win32") { @@ -69,11 +70,18 @@ function getConfigFile(files: ConfigFileEntry[], id: string): ConfigFileEntry | } export function registerConfigFileRoutes(app: FastifyInstance, options: ConfigFileRouteOptions = {}) { + // The fixed allowlist belongs to the CodeNomad host, independently of the + // selected project. Explicit-server configuration has its own admission. const configFiles = options.files ?? defaultConfigFileEntries() + const hostOnlyQuery = async (request: FastifyRequest, reply: FastifyReply) => { + if (!HostOnlyQuerySchema.safeParse(request.query ?? {}).success) { + return reply.code(400).send({ error: "Invalid host config file query" }) + } + } - app.get("/api/config-files", async () => listConfigFiles(configFiles)) + app.get("/api/config-files", { preHandler: hostOnlyQuery }, async () => listConfigFiles(configFiles)) - app.get<{ Params: { id: string } }>("/api/config-files/:id/content", async (request, reply) => { + app.get<{ Params: { id: string } }>("/api/config-files/:id/content", { preHandler: hostOnlyQuery }, async (request, reply) => { const file = getConfigFile(configFiles, request.params.id) if (!file) { reply.code(404) @@ -93,7 +101,7 @@ export function registerConfigFileRoutes(app: FastifyInstance, options: ConfigFi } }) - app.put<{ Params: { id: string } }>("/api/config-files/:id/content", async (request, reply) => { + app.put<{ Params: { id: string } }>("/api/config-files/:id/content", { preHandler: hostOnlyQuery }, async (request, reply) => { const file = getConfigFile(configFiles, request.params.id) if (!file) { reply.code(404) diff --git a/packages/server/src/server/routes/events-diagnostics.test.ts b/packages/server/src/server/routes/events-diagnostics.test.ts new file mode 100644 index 0000000000..fec8697c28 --- /dev/null +++ b/packages/server/src/server/routes/events-diagnostics.test.ts @@ -0,0 +1,29 @@ +import assert from "node:assert/strict" +import test from "node:test" +import Fastify from "fastify" +import { EventBus } from "../../events/bus" +import { registerEventRoutes } from "./events" + +for (const sentinel of ["review-answer-sentinel", "review-feedback-sentinel"]) test(`SSE trace retains useful event types without ${sentinel}`, async () => { + const entries: unknown[] = [] + const logger = { debug() {}, trace: (...args: unknown[]) => entries.push(args), isLevelEnabled: () => true } as any + const bus = new EventBus(logger), app = Fastify() + let ready!: () => void, close!: () => void + const opened = new Promise(resolve => { ready = resolve }) + registerEventRoutes(app, { eventBus: bus, logger, registerClient: callback => { close = callback; ready(); return () => {} }, + connectionManager: { register: () => () => {}, pong: () => false } as any }) + const response = app.inject({ method: "GET", url: "/api/events?clientId=owned&connectionId=owned" }) + await opened + try { + bus.publish({ type: "instance.event", instanceId: "owned", source: { serverId: "A", generation: 1 }, + event: { type: "form.replied", data: { id: "form", sessionID: "global", answer: { token: "review-answer-sentinel" } } } } as any) + bus.publish({ type: "instance.event", instanceId: "owned", source: { serverId: "A", generation: 1 }, + event: { type: "permission.asked", data: { id: "permission", sessionID: "session", message: "review-feedback-sentinel" } } } as any) + } finally { close(); await response; await app.close() } + assert.equal(JSON.stringify(entries).includes(sentinel), false) + assert.deepEqual(entries, [ + [{ clientId: (entries[0] as any[])[0].clientId, type: "instance.event", nativeType: "form.replied" }, "SSE event dispatched"], + [{ clientId: (entries[1] as any[])[0].clientId, type: "instance.event", nativeType: "permission.asked" }, "SSE event dispatched"], + ]) + assert.equal(typeof (entries[0] as any[])[0].clientId, "number") +}) diff --git a/packages/server/src/server/routes/events.ts b/packages/server/src/server/routes/events.ts index c3d6b547b0..777897d7ad 100644 --- a/packages/server/src/server/routes/events.ts +++ b/packages/server/src/server/routes/events.ts @@ -4,6 +4,8 @@ import { EventBus } from "../../events/bus" import { WorkspaceEventPayload } from "../../api-types" import type { ClientConnectionManager } from "../../clients/connection-manager" import { Logger } from "../../logger" +import { PARTICIPATION_EVENT } from "../../workspaces/project-participants" +import type { registerProjectParticipationRoutes } from "./project-participation" interface RouteDeps { eventBus: EventBus @@ -12,6 +14,7 @@ interface RouteDeps { connectionManager: ClientConnectionManager backpressureLimitBytes?: number backpressureTimeoutMs?: number + participation?: ReturnType } let nextClientId = 0 @@ -20,6 +23,7 @@ const ConnectionQuerySchema = z.object({ clientId: z.string().trim().min(1), connectionId: z.string().trim().min(1), }) +const EventQuerySchema = ConnectionQuerySchema.extend({ participation: z.literal("1").optional() }) const PongBodySchema = ConnectionQuerySchema.extend({ pingTs: z.number().optional(), @@ -28,7 +32,7 @@ const PongBodySchema = ConnectionQuerySchema.extend({ export function registerEventRoutes(app: FastifyInstance, deps: RouteDeps) { app.get("/api/events", (request, reply) => { const clientId = ++nextClientId - const connection = ConnectionQuerySchema.parse(request.query ?? {}) + const connection = EventQuerySchema.parse(request.query ?? {}) deps.logger.debug({ clientId }, "SSE client connected") for (const [name, value] of Object.entries(reply.getHeaders())) { @@ -37,7 +41,7 @@ export function registerEventRoutes(app: FastifyInstance, deps: RouteDeps) { } } reply.raw.setHeader("Content-Type", "text/event-stream") - reply.raw.setHeader("Cache-Control", "no-cache") + reply.raw.setHeader("Cache-Control", connection.participation === "1" ? "no-store" : "no-cache") reply.raw.setHeader("Connection", "keep-alive") reply.raw.flushHeaders?.() reply.hijack() @@ -50,6 +54,7 @@ export function registerEventRoutes(app: FastifyInstance, deps: RouteDeps) { let closed = false let cleaned = false let backpressured = false + let participant: ReturnType["open"]> let bufferedBytes = 0 const pending: Array<{ payload: string; bytes: number }> = [] const backpressureLimitBytes = Math.max(1, deps.backpressureLimitBytes ?? 1024 * 1024) @@ -62,6 +67,7 @@ export function registerEventRoutes(app: FastifyInstance, deps: RouteDeps) { const close = (force = false) => { if (closed) return closed = true + participant?.close() if (heartbeat) clearInterval(heartbeat) clearDrain() pending.length = 0 @@ -120,7 +126,7 @@ export function registerEventRoutes(app: FastifyInstance, deps: RouteDeps) { const send = (event: WorkspaceEventPayload) => { deps.logger.debug({ clientId, type: event.type }, "SSE event dispatched") if (deps.logger.isLevelEnabled("trace")) { - deps.logger.trace({ clientId, event }, "SSE event payload") + deps.logger.trace({ clientId, type: event.type, ...(event.type === "instance.event" ? { nativeType: event.event.type } : {}) }, "SSE event dispatched") } write(`data: ${JSON.stringify(event)}\n\n`) } @@ -141,6 +147,12 @@ export function registerEventRoutes(app: FastifyInstance, deps: RouteDeps) { close, }) + if (!closed && connection.participation === "1") { + participant = deps.participation?.open(request, () => !closed && !reply.raw.destroyed + && !reply.raw.writableEnded && !request.raw.aborted && !request.raw.socket.destroyed) + if (participant) write(`event: ${PARTICIPATION_EVENT}\ndata: ${JSON.stringify(participant.grant)}\n\n`) + } + request.raw.on("close", () => handleClose()) request.raw.on("error", () => handleClose()) }) diff --git a/packages/server/src/server/routes/explicit-panels.test.ts b/packages/server/src/server/routes/explicit-panels.test.ts new file mode 100644 index 0000000000..b4f241e5d3 --- /dev/null +++ b/packages/server/src/server/routes/explicit-panels.test.ts @@ -0,0 +1,242 @@ +// prototype-1236: panels of a project on an explicit OpenCode server read natively, bounded, read-only. +import assert from "node:assert/strict" +import test, { type TestContext } from "node:test" +import fs from "node:fs/promises" +import childProcess from "node:child_process" +import { syncBuiltinESMExports } from "node:module" +import Fastify, { type FastifyInstance } from "fastify" +import pino from "pino" +import { EventBus } from "../../events/bus" +import { explicitContractFixture } from "../../opencode/compatibility/contract-fixture" +import { OpenCodeServerConnections } from "../../opencode/servers/connections" +import { OpenCodeServerCredentials } from "../../opencode/servers/credentials" +import { OpenCodeServerRegistry } from "../../opencode/servers/registry" +import type { OpenCodeServerProfile } from "../../opencode/servers/types" +import { locationPrefix, patchSides, REMOTE_FILE_READ_LIMIT, remoteRelativePath } from "../../opencode/servers/remote-workspace" +import { WorkspaceManager } from "../../workspaces/manager" +import { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" +import { PluginControls } from "../../opencode/plugin-controls" +import { AutoAcceptManager } from "../../permissions/auto-accept-manager" +import { createOpencodeYoloPersistence } from "../../permissions/opencode-yolo-metadata" +import { registerWorkspaceRoutes } from "./workspaces" +import { registerUsageRoutes } from "./usage" +import { registerPluginControlRoutes } from "./plugin-controls" + +const DIRECTORY = "/repo/app" + +async function fixture(t: TestContext) { + const calls: { path: string; query: URLSearchParams; method: string }[] = [] + const state = { + provider: "git" as string | undefined, root: "/repo" as string | undefined, big: false, + diff: [] as unknown[], limits: null as unknown, pending: [] as unknown[], + } + const forbidden = () => { throw new Error("Host adapter forbidden") } + const upstream: FastifyInstance = Fastify() + upstream.all("/*", async (request, reply) => { + const url = new URL(request.url, "http://fixture") + calls.push({ path: url.pathname, query: url.searchParams, method: request.method }) + const location = { directory: url.searchParams.get("location[directory]") ?? DIRECTORY } + if (url.pathname === "/openapi.json") return explicitContractFixture() + if (url.pathname === "/api/location") return { directory: location.directory, project: { id: "p", directory: state.root ?? "/elsewhere", canonical: "/repo" } } + if (url.pathname === "/api/fs/list") { + const path = url.searchParams.get("path") + if (!path || path === ".") return { location, data: [{ path: "src", type: "directory" }, { path: "README.md", type: "file" }, + { path: "../secret", type: "file" }, { path: "/etc/passwd", type: "file" }, { path: "src/deep.ts", type: "file" }, { path: "C:\\x", type: "file" }] } + return { location, data: [{ path: `${path}/index.ts`, type: "file" }, { path: `${path}/../../escape`, type: "file" }] } + } + if (url.pathname === "/api/fs/find") return { location, data: [{ path: "src/index.ts", type: "file" }, { path: "../outside.ts", type: "file" }] } + if (url.pathname.startsWith("/api/fs/read/")) { + if (url.pathname.endsWith("missing.ts")) return reply.code(404).send({ _tag: "FileNotFoundError" }) + return reply.type("application/octet-stream").send(state.big ? Buffer.alloc(REMOTE_FILE_READ_LIMIT + 1, 97) : Buffer.from("hello\n")) + } + if (url.pathname === "/api/vcs") return { location, data: { ...(state.provider ? { provider: state.provider } : {}), branch: { current: "main" } } } + if (url.pathname === "/api/vcs/diff") return { location, data: state.diff } + if (url.pathname === "/api/experimental/usage/limits") return { location, data: state.limits } + if (url.pathname === "/api/session/ses_s") return { data: { id: "ses_s", location: { directory: DIRECTORY } } } + if (url.pathname === "/api/session/ses_s/permission") return { data: state.pending } + if (url.pathname === "/api/session" && request.method === "GET") return { data: [{ id: "ses_s", location: { directory: DIRECTORY } }], cursor: {} } + if (url.pathname === "/api/config") return [{ type: "directory", path: "/home/user/.config/opencode" }] + if (url.pathname === "/api/plugin") return { location, data: [{ id: "remote.plugin", source: { type: "package", target: "remote-plugin@1", version: "1.0.0" }, features: { server: true }, state: { status: "active" } }] } + return reply.code(404).send({}) + }) + await upstream.listen({ host: "127.0.0.1", port: 0 }) + const origin = `http://127.0.0.1:${(upstream.server.address() as { port: number }).port}` + const profiles: OpenCodeServerProfile[] = [{ id: "A", kind: "explicit", label: "A", origin }] + const registry = new OpenCodeServerRegistry(() => profiles, forbidden) + const credentials = new OpenCodeServerCredentials({ profileKey: "panels-test", configIdentity: "panels-test" }, registry) + await credentials.set("A", JSON.stringify({ username: "A", password: "fixture-A" })) + const connections = new OpenCodeServerConnections({ registry, credentials, local: { acquire: forbidden, existing: forbidden, invalidate: forbidden } }) + const bus = new EventBus() + const settingsState: Record = {} + const manager = new WorkspaceManager({ rootDir: "C:/forbidden", logger: pino({ level: "silent" }), eventBus: bus, + binaryResolver: { resolveDefault: forbidden } as never, + settings: { getOpenCodeServerConnections: () => connections, getOwner: () => settingsState, mergePatchOwner: forbidden, + readEnvironmentForAdmission: forbidden, disposeOpenCodeServers: () => connections.dispose() } as never, + sharedService: { endpoint: forbidden, client: forbidden, headers: forbidden, validateLocation: forbidden, subscribe: forbidden, shutdown: async () => {} }, + }) + const workspace = (await manager.create(DIRECTORY, undefined, { serverId: "A" })).workspace + const app = Fastify() + const deps = { workspaceManager: manager, worktreeDeletionFence: new WorktreeDeletionFence() } + registerWorkspaceRoutes(app, deps) + registerUsageRoutes(app, deps) + registerPluginControlRoutes(app, { controls: new PluginControls({ ...deps, logger: pino({ level: "silent" }) }) }) + await app.ready() + t.after(async () => { await app.close(); await manager.shutdown(); await upstream.close() }) + // Host disk and processes are forbidden from here on: every read must be native. + const hostCalls: string[] = [] + const mocks = [ + ...(["realpath", "stat", "lstat", "readdir", "readFile", "writeFile", "open"] as const).map(method => + t.mock.method(fs, method, () => { hostCalls.push(method); throw new Error("Host FS forbidden") })), + ...(["spawn", "spawnSync", "execFile", "execFileSync"] as const).map(method => + t.mock.method(childProcess, method, () => { hostCalls.push(method); throw new Error("Host process forbidden") })), + ] + syncBuiltinESMExports() + t.after(() => { for (const mock of mocks) mock.mock.restore(); syncBuiltinESMExports() }) + const base = `/api/workspaces/${encodeURIComponent(workspace.id)}` + return { app, manager, bus, workspace, base, calls, state, hostCalls } +} + +test("relative paths only: absolute, drive, parent and NUL paths are refused", () => { + for (const value of ["/etc/passwd", "C:\\Windows", "c:/x", "../x", "a/../../b", "a\0b", "\\\\server\\share"]) { + assert.throws(() => remoteRelativePath(value), { code: "invalid_path" }, value) + } + assert.equal(remoteRelativePath("./src//a\\b.ts"), "src/a/b.ts") + assert.equal(remoteRelativePath(""), ".") +}) + +test("Git paths come back to the opened folder from the worktree root", () => { + assert.equal(locationPrefix("/repo", "/repo"), "") + assert.equal(locationPrefix("/repo", "/repo/app"), "app/") + assert.equal(locationPrefix("D:\\Repo", "d:\\repo\\App\\web"), "App/web/") + assert.equal(locationPrefix("/repo", "/repository"), undefined) + assert.equal(locationPrefix("/other", "/repo/app"), undefined) +}) + +test("whole-file patches rebuild both sides exactly or not at all", () => { + assert.deepEqual(patchSides("diff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1,2 +1,2 @@\n keep\n-old\n+new\n"), { before: "keep\nold\n", after: "keep\nnew\n" }) + assert.deepEqual(patchSides("@@ -0,0 +1,1 @@\n+only\n\\ No newline at end of file\n"), { before: "", after: "only" }) + assert.deepEqual(patchSides("@@ -1 +0,0 @@\n-gone\n"), { before: "gone\n", after: "" }) + // Partial context, two hunks, wrong counts or mode-only headers prove nothing. + assert.equal(patchSides("@@ -10,2 +10,2 @@\n a\n-b\n+c\n"), undefined) + assert.equal(patchSides("@@ -1,1 +1,1 @@\n-a\n+b\n@@ -9,1 +9,1 @@\n-c\n+d\n"), undefined) + assert.equal(patchSides("@@ -1,3 +1,3 @@\n-a\n+b\n"), undefined) + assert.equal(patchSides("diff --git a/x b/x\nold mode 100644\nnew mode 100755\n"), undefined) +}) + +test("Files list, search and read go through the server, filtered to the folder and bounded", async t => { + const f = await fixture(t) + const list = await f.app.inject(`${f.base}/files?path=.`) + assert.equal(list.statusCode, 200, list.body) + assert.deepEqual(list.json(), [{ name: "README.md", path: "README.md", type: "file" }, { name: "src", path: "src", type: "directory" }]) + assert.deepEqual((await f.app.inject(`${f.base}/files?path=src&directory=${encodeURIComponent(DIRECTORY)}`)).json(), [{ name: "index.ts", path: "src/index.ts", type: "file" }]) + assert.deepEqual((await f.app.inject(`${f.base}/files/search?q=index`)).json(), [{ name: "index.ts", path: "src/index.ts", type: "file" }]) + const read = await f.app.inject(`${f.base}/files/content?path=src/index.ts`) + assert.deepEqual(read.json(), { workspaceId: f.workspace.id, relativePath: "src/index.ts", contents: "hello\n", encoding: "utf-8" }) + assert.equal((await f.app.inject(`${f.base}/files/preview?path=src/index.ts`)).json().contents, Buffer.from("hello\n").toString("base64")) + assert.equal((await f.app.inject(`${f.base}/files/content?path=missing.ts`)).statusCode, 404) + f.state.big = true + const big = await f.app.inject(`${f.base}/files/preview?path=big.bin`) + assert.equal(big.statusCode, 413) + assert.equal(big.json().code, "too_large") + const before = f.calls.length + for (const path of ["../secret", "/etc/passwd", "C:%5Cx"]) { + assert.equal((await f.app.inject(`${f.base}/files/content?path=${path}`)).statusCode, 400, path) + assert.equal((await f.app.inject(`${f.base}/files?path=${path}`)).statusCode, 400, path) + } + assert.equal((await f.app.inject(`${f.base}/files?directory=%2Frepo`)).statusCode, 403) + assert.equal((await f.app.inject({ method: "PUT", url: `${f.base}/files/content?path=a.ts`, payload: { contents: "x" } })).statusCode, 403) + assert.equal(f.calls.length, before, "refused paths, other folders and writes never reach the server") + assert(f.calls.filter(call => call.path.startsWith("/api/fs")).every(call => call.query.get("location[directory]") === DIRECTORY)) + assert(f.calls.every(call => call.method === "GET" && call.path !== "/api/credential")) + assert.deepEqual(f.hostCalls, []) +}) + +test("Changes read native working changes relative to the folder; unknown or partial state is never clean", async t => { + const f = await fixture(t) + const status = () => f.app.inject(`${f.base}/worktrees/root/git-status`) + f.state.diff = [ + { file: "app/src/a.ts", patch: "@@ -1,1 +1,1 @@\n-old\n+new\n", additions: 1, deletions: 1, status: "modified" }, + { file: "other/b.ts", patch: "", additions: 3, deletions: 0, status: "added" }, + { file: "app/new/", patch: "", additions: 0, deletions: 0, status: "added", more: true }, + ] + const rows = await status() + assert.equal(rows.statusCode, 200, rows.body) + assert.deepEqual(rows.json().map((row: { path: string; unstagedStatus: string; stagedStatus: null }) => [row.path, row.unstagedStatus, row.stagedStatus]), + [["src/a.ts", "modified", null], ["new/", "added", null]]) + const diff = await f.app.inject(`${f.base}/worktrees/root/git-diff?path=src/a.ts&scope=unstaged`) + assert.deepEqual(diff.json(), { path: "src/a.ts", originalPath: null, scope: "unstaged", before: "old\n", after: "new\n" }) + assert.equal(f.calls.find(call => call.path === "/api/vcs/diff" && call.query.has("context"))!.query.get("mode"), "working") + assert.equal((await f.app.inject(`${f.base}/worktrees/root/git-diff?path=new&scope=unstaged`)).statusCode, 404) + f.state.diff = [{ file: "app/src/a.ts", patch: "", additions: 1, deletions: 1, status: "modified" }] + assert.equal((await f.app.inject(`${f.base}/worktrees/root/git-diff?path=src/a.ts&scope=unstaged`)).json().code, "ambiguous") + // An untraversed ancestor folder, an unknown worktree root or no repository: an error, never an empty list. + f.state.diff = [{ file: "app/", patch: "", additions: 0, deletions: 0, status: "added", more: true }] + assert.deepEqual([(await status()).statusCode, (await status()).json().code], [409, "ambiguous"]) + f.state.diff = [] + f.state.root = undefined + assert.deepEqual([(await status()).statusCode, (await status()).json().code], [409, "ambiguous"]) + f.state.root = "/repo" + f.state.provider = undefined + assert.deepEqual([(await status()).statusCode, (await status()).json().code], [409, "not_repository"]) + f.state.provider = "git" + assert.deepEqual((await status()).json(), []) + for (const [method, suffix, payload] of [["POST", "git-stage", { paths: ["src/a.ts"] }], ["POST", "git-unstage", { paths: ["src/a.ts"] }], + ["POST", "git-commit", { message: "x" }], ["GET", "git-history", undefined]] as const) { + assert.equal((await f.app.inject({ method, url: `${f.base}/worktrees/root/${suffix}`, ...(payload ? { payload } : {}) })).statusCode, 403, suffix) + } + assert.equal((await f.app.inject({ method: "POST", url: `${f.base}/git-init`, payload: { directory: DIRECTORY } })).statusCode, 403) + assert.equal((await f.app.inject(`${f.base}/git-branches?directory=${encodeURIComponent(DIRECTORY)}`)).statusCode, 403) + assert(f.calls.every(call => call.method === "GET"), "no Git mutation reaches the server") + assert.deepEqual(f.hostCalls, []) +}) + +test("Usage shows only quotas OpenCode publishes and never reads server credentials", async t => { + const f = await fixture(t) + const usage = (provider: string) => f.app.inject(`/api/usage/${provider}?instanceId=${f.workspace.id}&sessionId=ses_s`) + f.state.limits = { workspace: { id: "w", usageURL: "https://opencode.ai" }, budgets: [], + go: { rolling: { percent: 12, limited: false, resetsAt: 1000 }, weekly: { percent: 40, limited: false, resetsAt: 2000 }, monthly: { percent: 5, limited: true, resetsAt: 3000 } } } + const go = await usage("opencode-go") + assert.equal(go.statusCode, 200, go.body) + assert.deepEqual(Object.fromEntries(Object.entries(go.json().windows).map(([key, value]: [string, any]) => [key, value.usedPercent])), { "5h": 12, weekly: 40, monthly: 100 }) + assert.equal(go.json().ok, true) + f.state.limits = null + assert.deepEqual([(await usage("opencode-go")).json().configured, (await usage("opencode-go")).json().ok], [false, false]) + for (const provider of ["openai", "anthropic", "claude-code", "openrouter"]) { + const response = await usage(provider) + assert.equal(response.statusCode, 200) + assert.equal(response.json().supported, false, provider) + } + assert(f.calls.every(call => call.path !== "/api/credential"), "credentials are never read") + assert.deepEqual(f.hostCalls, []) +}) + +test("Plugins list the server's inventory read-only; activation writes are refused", async t => { + const f = await fixture(t) + const read = await f.app.inject(`${f.base}/plugin-controls?directory=${encodeURIComponent(DIRECTORY)}`) + assert.equal(read.statusCode, 200, read.body) + assert.deepEqual(read.json().targets, []) + assert.equal(read.json().runtime[0].source.target, "remote-plugin@1") + const write = await f.app.inject({ method: "PATCH", url: `${f.base}/plugin-controls`, payload: { location: { directory: DIRECTORY }, pluginId: "remote.plugin", scope: "global", enabled: false } }) + assert.equal(write.statusCode, 403) + assert(f.calls.every(call => call.method === "GET" && call.path !== "/api/credential")) + assert.deepEqual(f.hostCalls, []) +}) + +test("Yolo re-reads pending permissions of its own sessions after a reconnect and replies on the server", async t => { + const f = await fixture(t) + const settings = { getOwner: () => ({ sessions: { ses_s: { yoloEnabled: true } } }), mergePatchOwner: () => {} } as never + const persistence = createOpencodeYoloPersistence(f.manager, settings) + const replies: string[] = [] + const yolo = new AutoAcceptManager({ eventBus: f.bus, logger: pino({ level: "silent" }) as never, persistence, + replier: async reply => { replies.push(`${reply.sessionId}:${reply.permissionId}`) } }) + yolo.start() + t.after(() => yolo.stop()) + await yolo.hydrateInstance(f.workspace.id) + assert.equal(yolo.isEnabled(f.workspace.id, "ses_s"), true) + f.state.pending = [{ id: "per_1", sessionID: "ses_s", action: "bash", resources: ["ls"] }, { id: "per_x", sessionID: "ses_other", action: "bash", resources: [] }] + f.bus.publish({ type: "instance.eventStatus", instanceId: f.workspace.id, status: "connected", generation: 2 } as never) + for (let i = 0; i < 50 && replies.length === 0; i++) await new Promise(resolve => setTimeout(resolve, 10)) + assert.deepEqual(replies, ["ses_s:per_1"]) + assert.equal(f.calls.filter(call => call.path.endsWith("/permission")).length, 1, "only the Yolo session is re-read") + assert.deepEqual(f.hostCalls, []) +}) diff --git a/packages/server/src/server/routes/explicit-surfaces.test.ts b/packages/server/src/server/routes/explicit-surfaces.test.ts new file mode 100644 index 0000000000..73e920f47e --- /dev/null +++ b/packages/server/src/server/routes/explicit-surfaces.test.ts @@ -0,0 +1,164 @@ +import assert from "node:assert/strict" +import test from "node:test" +import Fastify from "fastify" +import pino from "pino" +import { EventBus } from "../../events/bus" +import { WorkspaceManager } from "../../workspaces/manager" +import { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" +import { PluginControls } from "../../opencode/plugin-controls" +import { PluginSources } from "../../opencode/plugin-sources" +import { ImageSettings } from "../../opencode/image-settings" +import { WebSearchSettings } from "../../opencode/websearch-settings" +import { IntegrationsReader } from "../../opencode/integrations/integrations" +import { ServiceUsage } from "../../opencode/service-usage" +import { SubagentDepthSettings } from "../../opencode/subagent-depth-settings" +import { registerSessionPruningRoutes } from "./session-pruning" +import { registerSessionGoalRoute } from "./session-goal" +import { registerImagesConversationRoute, resolveImagesConversationAt } from "./images-conversation" +import { registerPanelExtensionApi4Routes } from "./panel-extension-api4" +import { registerPanelExtensionAssetRoutes } from "./panel-extension-assets" +import { registerProviderAccountsRoutes } from "./provider-accounts" +import { registerUsageRoutes } from "./usage" +import { registerServiceUsageRoutes } from "./service-usage" +import { registerPluginControlRoutes } from "./plugin-controls" +import { registerPluginSourceRoutes } from "./plugin-sources" +import { registerImageSettingsRoutes } from "./image-settings" +import { registerWebSearchSettingsRoutes } from "./websearch-settings" +import { registerIntegrationRoutes } from "./integrations" +import { registerSubagentDepthSettingsRoutes } from "./subagent-depth-settings" +import { historyDirectories, ownedHistorySessions } from "./session-history-scope" +import type { ServerCapability } from "../../opencode/servers/capabilities" + +test("explicit surfaces use real workspace admission before any local lookup, acquisition, RPC or exclusion", async t => { + const effects: string[] = [] + const forbidden = (name: string) => () => { effects.push(name); throw new Error(`Unexpected ${name}`) } + const logger = pino({ level: "silent" }), directory = "/same/project" + // A pre-admitted in-memory transport supplies attachment proof only. The real + // manager and ExplicitWorkspace own the capability decision below. + const connection = { serverId: "explicit", generation: 1, endpoint: { url: "http://fixture.invalid" }, + assertCurrent() {}, fetch: async (input: RequestInfo | URL) => { + const url = new URL(String(input)) + if (url.pathname === "/api/location") return Response.json({ directory, project: { id: "p" } }) + if (url.pathname === "/api/fs/list") return Response.json({ location: { directory }, data: [] }) + return forbidden("unexpected transport")() + } } + const connections = { retainProject: () => ({ acquire: async () => connection, published() {}, release() {} }), + existingForServer: (serverId: string) => serverId === connection.serverId ? connection : undefined, + dispose: async () => {} } + const manager = new WorkspaceManager({ rootDir: "C:/unused", logger, eventBus: new EventBus(), + binaryResolver: { resolveDefault: forbidden("binary") } as never, + settings: { getOpenCodeServerConnections: () => connections, getOwner: forbidden("settings"), + disposeOpenCodeServers: async () => {} } as never, + sharedService: { endpoint: forbidden("endpoint"), client: forbidden("client"), headers: forbidden("headers"), + validateLocation: forbidden("location"), subscribe: forbidden("subscribe"), shutdown: async () => {} }, + }) + const workspace = (await manager.create(directory, undefined, { serverId: "explicit" })).workspace + const id = workspace.id + assert.doesNotThrow(() => manager.requireWorkspaceCapability(id, "chat")) + assert.doesNotThrow(() => manager.requireWorkspaceCapability(id, "media")) + for (const method of ["get", "getServiceLocation", "getSharedServiceClient", "getSharedServiceConnection", "desktopPluginsReady", + "getWorktrees", "getWorktreeIdentityForPath", "ownsLocation", "getServiceDirectoryForPath", "getServicePathStyle", + "getServiceWslDistro", "getHostPathForServicePath", "getSessionEnvironment"] as const) { + t.mock.method(manager, method, forbidden(method)) + } + const fence = new WorktreeDeletionFence() + t.mock.method(fence, "enter", forbidden("deletion fence")) + const controls = new PluginControls({ workspaceManager: manager, worktreeDeletionFence: fence, logger }) + const sources = new PluginSources({ documents: controls, logger, catalog: { read: forbidden("catalog") } }) + const images = new ImageSettings(controls, manager), websearch = new WebSearchSettings(controls) + const integrations = new IntegrationsReader({ workspaceManager: manager, controls, catalog: { read: forbidden("catalog") } }) + const usage = new ServiceUsage(manager) + const imageDeps = { workspaceManager: manager, worktreeDeletionFence: fence, excludeDesignFolder: forbidden("exclude write") } + const app = Fastify() + registerSessionPruningRoutes(app, imageDeps) + registerSessionGoalRoute(app, imageDeps) + registerImagesConversationRoute(app, imageDeps) + registerPanelExtensionApi4Routes(app, { ...imageDeps, store: { authorize: forbidden("panel consent") } as never, + imageSettings: images, checkDesignFolderExclusion: forbidden("exclude read") }) + registerPanelExtensionAssetRoutes(app, { workspaceManager: manager, store: { authorize: forbidden("asset consent") } as never }) + registerProviderAccountsRoutes(app, { ...imageDeps, accounts: { snapshot: forbidden("credentials"), setEnabled: forbidden("policy") } as never }) + registerUsageRoutes(app, imageDeps) + registerServiceUsageRoutes(app, usage) + registerPluginControlRoutes(app, { controls }) + registerPluginSourceRoutes(app, { sources }) + registerImageSettingsRoutes(app, images) + registerWebSearchSettingsRoutes(app, websearch) + registerIntegrationRoutes(app, { integrations }) + registerSubagentDepthSettingsRoutes(app, new SubagentDepthSettings(controls, manager)) + t.after(async () => { await app.close(); t.mock.restoreAll(); await manager.shutdown() }) + const base = `/api/workspaces/${id}`, location = { directory }, revision = "a".repeat(64) + const cases: Array<[string, string, unknown, ServerCapability]> = [ + ["POST", `${base}/session-history/query`, {}, "historyEnrichment"], + ["POST", `${base}/session-history/query`, { sessionID: "ses_s", purpose: "prune" }, "historyEnrichment"], + ["POST", `${base}/session-history/ranked`, { version: 1, query: "needle" }, "historyEnrichment"], + ["POST", `${base}/session-history/window`, { sessionID: "ses_s", target: { kind: "latest" } }, "historyEnrichment"], + ["POST", `${base}/session-history/outline`, { sessionID: "ses_s" }, "historyEnrichment"], + ["POST", `${base}/session-history/outlinePreview`, { sessionID: "ses_s", messageIDs: ["m"] }, "historyEnrichment"], + ["POST", `${base}/session-history/prune`, { sessionID: "ses_s", candidates: [{ messageID: "m", revision, toolCount: 1, reasoningCount: 0 }] }, "sessionPruning"], + ["POST", `${base}/session-pruning/preview`, { sessionID: "ses_s", messageID: "m" }, "sessionPruning"], + ["POST", `${base}/session-pruning/prune`, { sessionID: "ses_s", messageID: "m", revision, indexes: [0] }, "sessionPruning"], + ["GET", `${base}/sessions/ses_s/goal`, undefined, "historyEnrichment"], + ...["lookup", "open", "new"].map(mode => ["POST", `${base}/images-conversation`, { directory, mode }, "integratedImages"] as typeof cases[number]), + ["GET", `${base}/provider-accounts/openai?directory=${directory}`, undefined, "executionSettings"], + ["PUT", `${base}/provider-accounts/openai`, { directory, enabled: true }, "executionSettings"], + ["GET", `${base}/service-usage/owner`, undefined, "executionSettings"], + ["GET", `${base}/service-usage/cache?timezone=UTC`, undefined, "executionSettings"], + ["GET", `${base}/service-usage?from=1&to=2&timezone=UTC`, undefined, "executionSettings"], + ["PATCH", `${base}/plugin-controls`, { location, pluginId: "example.plugin", scope: "global", enabled: true }, "executionSettings"], + ["POST", `${base}/plugin-sources`, { location, scope: "global", spec: "example-plugin@1" }, "executionSettings"], + ["DELETE", `${base}/plugin-sources`, { location, scope: "global", target: "example-plugin@1", entryIndex: 0, expectedRevision: revision }, "executionSettings"], + ["GET", `${base}/image-settings?directory=${directory}`, undefined, "executionSettings"], + ["PUT", `${base}/image-settings`, { location, generation: false }, "executionSettings"], + ["GET", `${base}/websearch-settings?directory=${directory}`, undefined, "executionSettings"], + ["PUT", `${base}/websearch-settings`, { location, scope: "project", provider: false }, "executionSettings"], + ["GET", `${base}/subagent-depth?directory=${directory}`, undefined, "executionSettings"], + ["PUT", `${base}/subagent-depth`, { location, depth: 1, expectation: revision }, "executionSettings"], + ["POST", "/api/panel-extensions/example.assets/assets", { instanceId: id, digest: revision, sessionID: "ses_s" }, "integratedImages"], + ["POST", "/api/panel-extensions/example.assets/assetRead", { instanceId: id, digest: revision, sessionID: "ses_s", + target: { messageID: "m", part: 0, index: 0, digest: revision } }, "integratedImages"], + ...["images", "imageRead", "imagesStatus", "prefillReferences", "conversationStatus", "conversationOpen", "conversationNew"].map(method => { + const target = { messageID: "m", part: 0, index: 0, digest: revision } + const fields = method === "images" || method === "imagesStatus" ? { sessionID: "ses_s" } + : method === "imageRead" ? { sessionID: "ses_s", target } + : method === "prefillReferences" ? { sessionID: "ses_s", targets: [target] } + : method === "conversationStatus" ? { directory } : { directory, title: "Images" } + return ["POST", `/api/panel-extensions/example.design/${method}`, { instanceId: id, digest: revision, ...fields }, "integratedImages"] as typeof cases[number] + }), + ] + for (const [method, url, payload, capability] of cases) { + const response = await app.inject({ method: method as "POST", url, ...(payload ? { payload } : {}) }) + assert.equal(response.statusCode, 403, `${method} ${url}: ${response.body}`) + assert.deepEqual(response.json(), { error: "explicit_capability_unavailable", code: "explicit_capability_unavailable", capability, reason: { code: "deferred" } }) + assert.deepEqual(effects, [], `${method} ${url} admitted effects`) + } + // The trusted shared guard's missing-workspace status must survive settings + // error translation, including the Stats owner/cache routes' separate catches. + for (const [method, url, payload, capability] of cases) { + const missing = url.replaceAll(id, "missing-workspace") + const missingPayload = payload ? JSON.parse(JSON.stringify(payload).replaceAll(id, "missing-workspace")) : undefined + const response = await app.inject({ method: method as "POST", url: missing, ...(missingPayload ? { payload: missingPayload } : {}) }) + assert.equal(response.statusCode, 404, `${method} ${missing}: ${response.body}`) + if (url.endsWith("/plugin-sources")) assert.deepEqual(response.json(), { error: "Plugin source update refused" }) + else if (capability === "executionSettings") assert.equal(response.json().message ?? response.json().error, "Workspace not found", `${method} ${missing}`) + assert.deepEqual(effects, [], `${capability} missing workspace admitted effects`) + } + const denied = { code: "explicit_capability_unavailable" } + await assert.rejects(historyDirectories(manager, id, directory), denied) + await assert.rejects(ownedHistorySessions(manager, id, {} as never, []), denied) + await assert.rejects(resolveImagesConversationAt(imageDeps, id, directory, { mode: "open" }), denied) + // Separate preambles must also hold when the shared configuration dependency is replaced. + const configuration = { readConfigDocuments: forbidden("documents"), editConfigDocument: forbidden("edit") } + await assert.rejects(new ImageSettings(configuration, manager).read(id, location), denied) + await assert.rejects(new SubagentDepthSettings(configuration, manager).read(id, location), denied) + // prototype-1236: usage, the plugin inventory and integrations are admitted (explicit-panels.test.ts). + // Qualifying images alone must still leave the independent Design boundary closed. + const requireCapability = manager.requireWorkspaceCapability.bind(manager) + t.mock.method(manager, "requireWorkspaceCapability", (workspaceId: string, capability: ServerCapability) => + capability === "integratedImages" ? new AbortController().signal : requireCapability(workspaceId, capability)) + await assert.rejects(resolveImagesConversationAt(imageDeps, id, directory, { mode: "open" }), { ...denied, capability: "design" }) + const gallery = await app.inject({ method: "POST", url: "/api/panel-extensions/example.design/images", + payload: { instanceId: id, digest: revision, sessionID: "ses_s" } }) + assert.equal(gallery.statusCode, 403) + assert.equal(gallery.json().capability, "design") + assert.deepEqual(effects, []) +}) diff --git a/packages/server/src/server/routes/files-history.test.ts b/packages/server/src/server/routes/files-history.test.ts index bcfd565e73..76241a6c36 100644 --- a/packages/server/src/server/routes/files-history.test.ts +++ b/packages/server/src/server/routes/files-history.test.ts @@ -33,6 +33,9 @@ test("real Git history routes and bounded file previews use the requested owned // Exercise the actual manager fileBrowserRoot + previewFile boundary. Native // discovery is isolated to an explicit inventory, with no shared daemon. const manager = Object.assign(Object.create(WorkspaceManager.prototype), { + requireWorkspaceCapability: () => new AbortController().signal, + assertLocalWorkspace: () => {}, + isExplicitWorkspace: () => false, get: (requested: string) => requested === id ? workspace : undefined, getWorktreeIdentityForPath: async (_id: string, directory: string) => directory === root || directory === linked ? directory : undefined, requireWorkspace: (requested: string) => { if (requested !== id) throw new Error("Workspace not found"); return workspace }, @@ -87,6 +90,9 @@ test("file preview remains available for an explicitly opened directory without try { await writeFile(path.join(root, "readme.md"), "# Directory only") const manager = Object.assign(Object.create(WorkspaceManager.prototype), { + requireWorkspaceCapability: () => new AbortController().signal, + assertLocalWorkspace: () => {}, + isExplicitWorkspace: () => false, requireWorkspace: () => ({ path: root }), resolveOwnedWorktree: async (_workspace: unknown, directory: string) => directory === root ? { directory } : null, }) as WorkspaceManager diff --git a/packages/server/src/server/routes/filesystem.ts b/packages/server/src/server/routes/filesystem.ts index f5cf6fccac..a9df2edd30 100644 --- a/packages/server/src/server/routes/filesystem.ts +++ b/packages/server/src/server/routes/filesystem.ts @@ -1,6 +1,7 @@ import { FastifyInstance } from "fastify" import { z } from "zod" import { FileSystemBrowser } from "../../filesystem/browser" +import { hostOnlyQuery } from "./host-only-query" interface RouteDeps { fileSystemBrowser: FileSystemBrowser @@ -9,23 +10,24 @@ interface RouteDeps { const FilesystemQuerySchema = z.object({ path: z.string().optional(), includeFiles: z.coerce.boolean().optional(), -}) +}).strict() const FilesystemCreateFolderSchema = z.object({ parentPath: z.string().optional(), name: z.string(), -}) +}).strict() const FilesystemFileContentQuerySchema = z.object({ path: z.string(), encoding: z.enum(["utf-8", "base64"]).optional(), -}) +}).strict() export function registerFilesystemRoutes(app: FastifyInstance, deps: RouteDeps) { + // These are host browser operations. Project paths use the workspace API; + // reject scope selectors rather than silently treating them as host paths. app.get("/api/filesystem", async (request, reply) => { - const query = FilesystemQuerySchema.parse(request.query ?? {}) - try { + const query = FilesystemQuerySchema.parse(request.query ?? {}) return await deps.fileSystemBrowser.browse(query.path, { includeFiles: query.includeFiles, }) @@ -35,10 +37,9 @@ export function registerFilesystemRoutes(app: FastifyInstance, deps: RouteDeps) } }) - app.post("/api/filesystem/folders", async (request, reply) => { - const body = FilesystemCreateFolderSchema.parse(request.body ?? {}) - + app.post("/api/filesystem/folders", { preHandler: hostOnlyQuery("files") }, async (request, reply) => { try { + const body = FilesystemCreateFolderSchema.parse(request.body ?? {}) const created = await deps.fileSystemBrowser.createFolder(body.parentPath, body.name) reply.code(201) return created @@ -58,9 +59,8 @@ export function registerFilesystemRoutes(app: FastifyInstance, deps: RouteDeps) }) app.get("/api/filesystem/files/content", async (request, reply) => { - const query = FilesystemFileContentQuerySchema.parse(request.query ?? {}) - try { + const query = FilesystemFileContentQuerySchema.parse(request.query ?? {}) return await deps.fileSystemBrowser.readFileContent(query.path, { encoding: query.encoding }) } catch (error) { reply.code(400).type("text/plain").send((error as Error).message) diff --git a/packages/server/src/server/routes/git-init.test.ts b/packages/server/src/server/routes/git-init.test.ts index 53c244d3ad..2f861fc00f 100644 --- a/packages/server/src/server/routes/git-init.test.ts +++ b/packages/server/src/server/routes/git-init.test.ts @@ -23,6 +23,7 @@ describe("Git initialization route", () => { const fence = new WorktreeDeletionFence() const calls: string[] = [] const workspaceManager = { + requireWorkspaceCapability: () => new AbortController().signal, get: (id: string) => id === "test" ? { id, path: folder } : undefined, getWorktreeIdentityForPath: async (_id: string, directory: string) => { calls.push(`identity:${directory}`); return "identity" in overrides ? overrides.identity : directory }, initializeGit: async (id: string) => { diff --git a/packages/server/src/server/routes/host-file-scopes.test.ts b/packages/server/src/server/routes/host-file-scopes.test.ts new file mode 100644 index 0000000000..0e191a0034 --- /dev/null +++ b/packages/server/src/server/routes/host-file-scopes.test.ts @@ -0,0 +1,80 @@ +import assert from "node:assert/strict" +import test from "node:test" +import fs from "node:fs/promises" +import Fastify from "fastify" +import type { FileSystemBrowser } from "../../filesystem/browser" +import { registerFilesystemRoutes } from "./filesystem" +import { registerConfigFileRoutes } from "./config-files" +import { registerTemporaryWorkspaceRoutes } from "./temporary-workspaces" +import { TemporaryWorkspaces } from "../../workspaces/temporary-workspaces" +import type { WorkspaceManager } from "../../workspaces/manager" +import type { EventBus } from "../../events/bus" +import { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" + +test("host filesystem/config routes reject project/server selectors before IO", async t => { + const app = Fastify(); t.after(() => app.close()) + let effects = 0 + const forbidden = () => { effects++; throw new Error("Host IO forbidden") } + registerFilesystemRoutes(app, { fileSystemBrowser: { + browse: forbidden, createFolder: forbidden, readFileContent: forbidden, + } as unknown as FileSystemBrowser }) + registerConfigFileRoutes(app, { files: [{ id: "host", label: "Host", path: "display", absolutePath: "/exact", language: "json" }] }) + await app.ready() + t.mock.method(fs, "readFile", forbidden) + t.mock.method(fs, "writeFile", forbidden) + t.mock.method(fs, "mkdir", forbidden) + for (const serverId of ["A", "B"]) { + for (const selector of [`serverId=${serverId}`, `workspaceId=${serverId}`, `binding%5BserverId%5D=${serverId}`]) { + for (const url of [ + `/api/filesystem?path=%2Fexact&${selector}`, + `/api/filesystem/files/content?path=%2Fexact&${selector}`, + `/api/config-files?${selector}`, `/api/config-files/host/content?${selector}`, + ]) assert.equal((await app.inject(url)).statusCode, 400, url) + assert.equal((await app.inject({ method: "PUT", url: `/api/config-files/host/content?${selector}`, payload: { contents: "forbidden" } })).statusCode, 400) + } + for (const scope of [{ serverId }, { binding: { serverId, directory: "/exact" } }]) { + assert.equal((await app.inject({ method: "POST", url: "/api/filesystem/folders", payload: { name: "forbidden", parentPath: "/exact", ...scope } })).statusCode, 400) + assert.equal((await app.inject({ method: "PUT", url: "/api/config-files/host/content", payload: { contents: "forbidden", ...scope } })).statusCode, 400) + } + } + assert.equal(effects, 0) +}) + +test("host mutations reject query scope before adapters, including encoded and mixed intents", async t => { + const app = Fastify(); t.after(() => app.close()) + const effects: string[] = [] + registerFilesystemRoutes(app, { fileSystemBrowser: { + createFolder: async () => { effects.push("folder"); return { path: "/host/new" } }, + } as unknown as FileSystemBrowser }) + t.mock.method(TemporaryWorkspaces.prototype, "createFolder", async () => { effects.push("temporary"); return "/host/new" }) + t.mock.method(TemporaryWorkspaces.prototype, "abandonFolder", async () => { effects.push("abandon") }) + registerTemporaryWorkspaceRoutes(app, { + workspaceManager: { temporaryFolders: {} } as WorkspaceManager, + eventBus: {} as EventBus, worktreeDeletionFence: new WorktreeDeletionFence(), + }) + const routes = [ + { url: "/api/filesystem/folders", payload: { parentPath: "/host", name: "new" }, capability: "files", status: 201 }, + { url: "/api/workspaces/temporary", payload: {}, capability: "worktrees", status: 201 }, + { url: "/api/workspaces/temporary/abandon", payload: { path: "/host/new" }, capability: "worktrees", status: 204 }, + ] + for (const route of routes) { + for (const selector of ["serverId=A", "workspaceId=B", "binding%5BserverId%5D=A", + "%73erverId=A", "binding.serverId=A", "serverId=local-shared&workspaceId=B"]) { + await t.test(`${route.url}?${selector}`, async () => { + const response = await app.inject({ method: "POST", url: `${route.url}?${selector}`, payload: route.payload }) + assert.equal(response.statusCode, 403) + assert.deepEqual(response.json(), { error: "explicit_capability_unavailable", code: "explicit_capability_unavailable", capability: route.capability, reason: { code: "localOnly" } }) + }) + } + // A local body selector cannot override the URL's explicit intent. + const mixed = await app.inject({ method: "POST", url: `${route.url}?serverId=A`, payload: { ...route.payload, serverId: "local-shared" } }) + await t.test(`${route.url} mixed URL/body`, () => assert.equal(mixed.statusCode, 403)) + // The production server has no form parser: forms fail before any handler. + const form = await app.inject({ method: "POST", url: route.url, headers: { "content-type": "application/x-www-form-urlencoded" }, payload: "serverId=A" }) + assert.equal(form.statusCode, 415) + } + assert.deepEqual(effects, []) + assert.equal((await app.inject({ method: "POST", url: "/api/filesystem/missing?serverId=A", payload: {} })).statusCode, 404) + for (const route of routes) assert.equal((await app.inject({ method: "POST", url: route.url, payload: route.payload })).statusCode, route.status) + assert.deepEqual(effects, ["folder", "temporary", "abandon"]) +}) diff --git a/packages/server/src/server/routes/host-only-query.ts b/packages/server/src/server/routes/host-only-query.ts new file mode 100644 index 0000000000..fc942d187c --- /dev/null +++ b/packages/server/src/server/routes/host-only-query.ts @@ -0,0 +1,14 @@ +import type { FastifyReply, FastifyRequest } from "fastify" +import type { ServerCapability } from "../../opencode/servers/capabilities" + +/** Host mutations have no query scope; never discard a caller's target intent. */ +export function hostOnlyQuery(capability: ServerCapability) { + return async (request: FastifyRequest, reply: FastifyReply) => { + if (Object.keys(request.query ?? {}).length) { + return reply.code(403).send({ + error: "explicit_capability_unavailable", code: "explicit_capability_unavailable", + capability, reason: { code: "localOnly" }, + }) + } + } +} diff --git a/packages/server/src/server/routes/image-settings.ts b/packages/server/src/server/routes/image-settings.ts index a3231715ea..13a0ae9b3e 100644 --- a/packages/server/src/server/routes/image-settings.ts +++ b/packages/server/src/server/routes/image-settings.ts @@ -2,6 +2,7 @@ import type { FastifyInstance, FastifyReply } from "fastify" import { z } from "zod" import { PluginControlsError } from "../../opencode/plugin-controls" import { IMAGE_MODEL_REF, type ImageSettings } from "../../opencode/image-settings" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" const Location = z.object({ directory: z.string().trim().min(1).max(32_768) }).strict() const Generation = z.union([z.boolean(), z.string().max(512).regex(IMAGE_MODEL_REF) @@ -31,6 +32,7 @@ export function registerImageSettingsRoutes(app: FastifyInstance, settings: Pick } function fail(error: unknown, reply: FastifyReply) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) if (error instanceof PluginControlsError) { const status = { "not-found": 404, forbidden: 403, invalid: 422, conflict: 409, unavailable: 503 }[error.kind] return reply.code(status).send({ error: error.message }) diff --git a/packages/server/src/server/routes/images-conversation.test.ts b/packages/server/src/server/routes/images-conversation.test.ts index 0426b09842..c0ab0a89a1 100644 --- a/packages/server/src/server/routes/images-conversation.test.ts +++ b/packages/server/src/server/routes/images-conversation.test.ts @@ -4,10 +4,12 @@ import Fastify from "fastify" import { registerImagesConversationRoute } from "./images-conversation" import { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" import type { ExcludeTarget, GitExclusion } from "../../workspaces/design-git-exclude" +import { WorkspaceCapabilityError, type ServerCapability } from "../../opencode/servers/capabilities" const url = "/api/workspaces/w/images-conversation" const model = { providerID: "fixture", id: "chosen" } -function fixture(options: { owned?: boolean; output?: unknown; fail?: boolean; distro?: string; exclusion?: GitExclusion; directory?: string } = {}) { +function fixture(options: { owned?: boolean; output?: unknown; fail?: boolean; distro?: string; exclusion?: GitExclusion; directory?: string; + admit?: (capability: ServerCapability, rpcCalls: number) => void } = {}) { const calls: any[] = [] const order: string[] = [] const excluded: ExcludeTarget[] = [] @@ -17,6 +19,7 @@ function fixture(options: { owned?: boolean; output?: unknown; fail?: boolean; d worktreeDeletionFence: fence, excludeDesignFolder: async target => { excluded.push(target); return options.exclusion ?? "excluded" }, workspaceManager: { + requireWorkspaceCapability: (_id, capability) => { options.admit?.(capability, calls.length); return new AbortController().signal }, getSharedServiceClient: async () => { order.push("client") return { @@ -86,6 +89,19 @@ test("open pins the fixed method, passes the caller's title, agent and model, th } finally { await app.close() } }) +test("Design admission is rechecked after creation before any exclude write", async () => { + const { app, calls, excluded } = fixture({ admit: (capability, rpcCalls) => { + if (capability === "design" && rpcCalls) throw new WorkspaceCapabilityError(capability, { code: "deferred" }) + } }) + try { + const response = await app.inject({ method: "POST", url, payload: { directory: "/owned/repo", mode: "open" } }) + assert.equal(response.statusCode, 403) + assert.deepEqual(response.json(), { error: "explicit_capability_unavailable", code: "explicit_capability_unavailable", capability: "design", reason: { code: "deferred" } }) + assert.equal(calls.length, 1) + assert.deepEqual(excluded, []) + } finally { await app.close() } +}) + test("a WSL location excludes through the owned distro and the host translation", async () => { const { app, excluded } = fixture({ distro: "Ubuntu", exclusion: "unavailable" }) try { diff --git a/packages/server/src/server/routes/images-conversation.ts b/packages/server/src/server/routes/images-conversation.ts index aecdcac72b..66e751372a 100644 --- a/packages/server/src/server/routes/images-conversation.ts +++ b/packages/server/src/server/routes/images-conversation.ts @@ -7,10 +7,11 @@ import { locationRequestOptions, readLocationRef } from "../../opencode/compatib import { PRUNING_RPC_ID } from "../../opencode/session-pruning/contract" import { imagesConversationInputSchema, imagesConversationResultSchema, type ImagesConversationInput } from "../../opencode/session-pruning/assets-gallery-contract" import type { GitExclusion, ImagesConversationResponse } from "./images-conversation-contract" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" export interface ImagesConversationRouteDeps { workspaceManager: Pick + | "getServiceWslDistro" | "getHostPathForServicePath" | "requireWorkspaceCapability"> worktreeDeletionFence: WorktreeDeletionFence excludeDesignFolder?: typeof excludeDesignFolder } @@ -34,6 +35,8 @@ export async function resolveImagesConversationAt(deps: ImagesConversationRouteD ): Promise { const exclude = deps.excludeDesignFolder ?? excludeDesignFolder const manager = deps.workspaceManager + manager.requireWorkspaceCapability(workspaceId, "integratedImages") + manager.requireWorkspaceCapability(workspaceId, "design") // Authorize the caller's directory before any OpenCode request: reading a // Location boots its services (configuration discovery, plugins). if (!await manager.ownsLocation(workspaceId, { directory }, undefined, options.signal)) return "denied" @@ -69,6 +72,7 @@ export async function resolveImagesConversationAt(deps: ImagesConversationRouteD } if (result.status !== "found" || input.mode === "lookup") return result options.signal?.throwIfAborted() + manager.requireWorkspaceCapability(workspaceId, "design") const gitExclusion: GitExclusion = await exclude({ directory, distro: manager.getServiceWslDistro(workspaceId), toHost: servicePath => manager.getHostPathForServicePath(workspaceId, servicePath), @@ -94,7 +98,12 @@ export function registerImagesConversationRoute(app: FastifyInstance, deps: Imag const parsed = requestSchema.safeParse(request.body) if (!parsed.success) return reply.code(400).send({ error: "Invalid Images conversation request" }) const { directory, ...input } = parsed.data - const result = await resolveImagesConversationAt(deps, request.params.id, directory, input) + let result + try { result = await resolveImagesConversationAt(deps, request.params.id, directory, input) } + catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + throw error + } if (result === "denied") return reply.code(403).send({ error: "Location does not belong to workspace" }) if (result === "deleting") return reply.code(409).send({ error: "Worktree deletion is in progress" }) return result diff --git a/packages/server/src/server/routes/integration-attachments.test.ts b/packages/server/src/server/routes/integration-attachments.test.ts index 4eeaa29426..2116963404 100644 --- a/packages/server/src/server/routes/integration-attachments.test.ts +++ b/packages/server/src/server/routes/integration-attachments.test.ts @@ -34,6 +34,7 @@ function harness(options: { catalogEmpty?: boolean updateError?: boolean guardHintRead?: boolean + explicit?: boolean } = {}) { const state = { current: true, owned: true, directory: "/work", workspaceID: undefined as string | undefined, sessionID: undefined as string | undefined, locations: {} as Record, @@ -77,6 +78,7 @@ function harness(options: { controls: { read: async (_id, location) => { await options.onControls?.(); if (options.controlsError) throw options.controlsError; return { ...snapshot(), location } } }, catalog: { read: async input => { catalogReads.push(input); return { state: "fresh", catalog: options.catalogEmpty ? catalogOf() : catalogOf(catalogEntry("fixture", { family: options.family ?? "native" })) } } }, workspaceManager: { + requireWorkspaceCapability: () => { if (options.explicit) throw new Error("Explicit host controls unavailable"); return new AbortController().signal }, getSharedServiceConnection: async () => ({ client, assertCurrent: () => { if (!state.current) throw new Error(secret) } }) as never, ownsLocation: async () => state.owned, getServiceWslDistro: () => options.wslDistro, @@ -104,6 +106,19 @@ function harness(options: { return { app, attachments, state, calls, trace, writes, logs, request, catalogReads } } +it("explicit projects refuse every host control before catalog, RPC, metadata or kernel reads", async t => { + const f = harness({ explicit: true, readKernelVersion: async () => { throw new Error("Host kernel read") } }) + t.after(() => f.app.close()) + for (const action of ["hosts", "binding", "attach", "detach", "install-host"] as const) { + const response = await f.request(action) + assert.equal(response.statusCode, 403, action) + } + assert.deepEqual(f.calls, []) + assert.deepEqual(f.catalogReads, []) + assert.deepEqual(f.writes, []) + assert.deepEqual(f.trace, []) +}) + describe("integration attachment routes (real service and schemas)", () => { it("AC-C12 validates the whole binding then projects only state/label, independent of Q8", async t => { for (const output of [binding, { state: "none", authority }, { state: "unknown" }, { state: "unknown", authority }]) { diff --git a/packages/server/src/server/routes/integration-install.test.ts b/packages/server/src/server/routes/integration-install.test.ts index 8675a51a06..31ac311788 100644 --- a/packages/server/src/server/routes/integration-install.test.ts +++ b/packages/server/src/server/routes/integration-install.test.ts @@ -20,6 +20,18 @@ const API = "@neuralnomads/opencode-mail@^0.1" const GIT = "github:NeuralNomadsAI/opencode-integrations#" const catalog = catalogOf(catalogEntry("fixture", { sources: { git: [GIT] } }), catalogEntry("mail", { family: "api" })) +it("explicit projects refuse installation before connection, catalog or config access", async () => { + let reads = 0 + const unexpected = async () => { reads++; throw new Error("Unexpected host work") } + const installer = new IntegrationInstaller({ + workspaceManager: { requireWorkspaceCapability: () => { throw new Error("Explicit host controls unavailable") }, + getSharedServiceConnection: unexpected, ownsLocation: unexpected }, + controls: { read: unexpected }, catalog: { read: unexpected }, sources: { add: unexpected }, + }) + await assert.rejects(installer.install("remote", "fixture", { directory: "/repo" }, "global"), { code: "forbidden" }) + assert.equal(reads, 0) +}) + /** Real route, installer, plugin sources and configuration documents on disk, with a fake native connection. */ async function fixture() { const root = await mkdtemp(path.join(os.tmpdir(), "integration-install-")) @@ -44,6 +56,7 @@ async function fixture() { }, } const manager = { + requireWorkspaceCapability: () => new AbortController().signal, get: (id: string) => id === "w" ? {} : undefined, getSharedServiceConnection: async () => connection, getServiceDirectoryForPath: async (_id: string, directory: string) => directory === project ? directory : undefined, diff --git a/packages/server/src/server/routes/integrations.test.ts b/packages/server/src/server/routes/integrations.test.ts index 19b6e49e42..ac73ae1880 100644 --- a/packages/server/src/server/routes/integrations.test.ts +++ b/packages/server/src/server/routes/integrations.test.ts @@ -40,6 +40,7 @@ function harness(options: { const reader = new IntegrationsReader({ controls: { read: async () => (options.snapshot ?? loadedSnapshot)() }, workspaceManager: { + requireWorkspaceCapability: () => new AbortController().signal, getSharedServiceConnection: async () => ({ client, assertCurrent: options.assertCurrent ?? (() => undefined) }) as never, ownsLocation: async () => options.owns?.(ownership++) ?? true, }, diff --git a/packages/server/src/server/routes/integrations.ts b/packages/server/src/server/routes/integrations.ts index 526f48de25..bbb2639a0e 100644 --- a/packages/server/src/server/routes/integrations.ts +++ b/packages/server/src/server/routes/integrations.ts @@ -2,6 +2,7 @@ import type { FastifyInstance } from "fastify" import { z } from "zod" import type { IntegrationsReader } from "../../opencode/integrations/integrations" import { PluginControlsError } from "../../opencode/plugin-controls" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" export interface IntegrationRouteDeps { integrations: Pick @@ -25,6 +26,7 @@ export function registerIntegrationRoutes(app: FastifyInstance, deps: Integratio try { return await deps.integrations.read(request.params.id, parsed.data, controller.signal) } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) if (error instanceof PluginControlsError) { const status = error.kind === "not-found" ? 404 : error.kind === "forbidden" ? 403 : error.kind === "invalid" ? 422 : error.kind === "conflict" ? 409 : 503 if (status >= 500) request.log.warn({ status }, "OpenCode integrations unavailable") diff --git a/packages/server/src/server/routes/mission-cleanup.ts b/packages/server/src/server/routes/mission-cleanup.ts index be9116089a..f4a021657f 100644 --- a/packages/server/src/server/routes/mission-cleanup.ts +++ b/packages/server/src/server/routes/mission-cleanup.ts @@ -1,4 +1,5 @@ import { z } from "zod" +import { localMissionWorkspaces } from "../../missions/workspace-capability" import { CODENOMAD_MISSIONS_RPC } from "../../missions/rpc" import { removeCleanupTarget, type MissionCleanupTarget } from "../../missions/native-session-cleanup" import { locationRequestOptions, sameLocation } from "../../opencode/compatibility/location" @@ -18,7 +19,7 @@ type Manager = Pick { + const owner = await Promise.any(localMissionWorkspaces(manager).map(async workspace => { const connection = await manager.getSharedServiceConnection(workspace.id) if (!connection) throw new Error("Workspace unavailable") const coordinator = await connection.client.session.get({ sessionID: coordinatorID }, { signal }) diff --git a/packages/server/src/server/routes/mission-content.test.ts b/packages/server/src/server/routes/mission-content.test.ts index 0dd4822f30..c9b4ba1cbf 100644 --- a/packages/server/src/server/routes/mission-content.test.ts +++ b/packages/server/src/server/routes/mission-content.test.ts @@ -24,6 +24,7 @@ async function routeFixture() { const app = Fastify({ logger: false }) registerMissionRoutes(app, { workspaceManager: { get: () => ({ id: "workspace" }), getServiceLocation: () => location, getWorktreeIdentityForPath: async (_id: string, directory: string) => directory, + requireWorkspaceCapability: () => new AbortController().signal, ownsLocation: async () => true, getSharedServiceConnection: async () => ({ client, assertCurrent() {} }), } as never, worktreeDeletionFence: new WorktreeDeletionFence() }) return { f, plugin, app, state } diff --git a/packages/server/src/server/routes/mission-creation-fence.test.ts b/packages/server/src/server/routes/mission-creation-fence.test.ts index da31885785..1ed7c4da6f 100644 --- a/packages/server/src/server/routes/mission-creation-fence.test.ts +++ b/packages/server/src/server/routes/mission-creation-fence.test.ts @@ -72,6 +72,7 @@ async function fixture(useBridge = false, drainTimeout = 2_000) { get: () => current ? { id: "workspace" } : undefined, list: () => [{ id: "workspace" }], getServiceLocation: () => ({ directory }), getSharedServiceClient: async () => client, getSharedServiceConnection: async () => connection, + requireWorkspaceCapability: () => new AbortController().signal, ownsLocation: async (_id: string, location: any) => current && location.directory === directory, getServiceDirectoryForPath: async (_id: string, path: string) => current && path === directory ? directory : undefined, getWorktreeIdentityForPath: async (_id: string, path: string) => current && path === directory ? physical : undefined, diff --git a/packages/server/src/server/routes/mission-creation-pipeline.ts b/packages/server/src/server/routes/mission-creation-pipeline.ts index 1fb72ddabc..fe602a37c3 100644 --- a/packages/server/src/server/routes/mission-creation-pipeline.ts +++ b/packages/server/src/server/routes/mission-creation-pipeline.ts @@ -21,7 +21,7 @@ export const missionCreationRequestSchema = z.object({ profiles: missionProfilesInputSchema, taskMode: missionTaskModeInputSchema.default("native"), }).strict() -export type MissionCreationPipelineManager = Pick export class MissionCreationPreparationError extends Error { @@ -43,6 +43,7 @@ export async function prepareMissionCreation(input: { const { manager, workspaceID, signal } = input const wait = input.wait ?? ((operation: Promise) => operation) signal.throwIfAborted() + if (manager.get(workspaceID)) manager.requireWorkspaceCapability(workspaceID, "missions") const parsed = missionCreationRequestSchema.safeParse(input.request) if (!parsed.success) throw new MissionCreationPreparationError(400, "Invalid mission creation request") const request = parsed.data diff --git a/packages/server/src/server/routes/mission-explicit-capabilities.test.ts b/packages/server/src/server/routes/mission-explicit-capabilities.test.ts new file mode 100644 index 0000000000..8574068364 --- /dev/null +++ b/packages/server/src/server/routes/mission-explicit-capabilities.test.ts @@ -0,0 +1,126 @@ +import assert from "node:assert/strict" +import test from "node:test" +import Fastify from "fastify" +import { registerMissionRoutes } from "./missions" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" +import { registerMissionRecurrenceSnapshot } from "./mission-recurrence-snapshot" +import { registerMissionRecurrenceCurrent } from "./mission-recurrence-current" +import { registerMissionRecurrenceControlStatus } from "./mission-recurrence-control-status" +import { registerMissionRecurrenceManual } from "./mission-recurrence-manual" +import { registerMissionRecurrenceCreate } from "./mission-recurrence-create" +import { prepareMissionCreation } from "./mission-creation-pipeline" +import { prepareMissionMapMutation } from "./mission-map-mutation" +import { prepareHumanRecurrenceControl } from "./mission-recurrence-play-preparation" +import { verifyMissionHumanAnswer } from "./mission-human-answer" +import { verifyHumanRecurrenceRequest } from "./mission-recurrence-proof" +import { admitMissionInput } from "./mission-input" +import { createManagedMissionRoot } from "./mission-root-creation" +import { prepareCoordinatorMission } from "./mission-prepare" +import { observeMissionTask, interruptMissionTask } from "./mission-task-native" +import { recurrenceControlRequestDigest } from "../../missions/recurrence-control-proof" + +const signal = new AbortController().signal +const denied = new WorkspaceCapabilityError("missions", { code: "deferred" }) +const workspace = { id: "explicit", binding: { serverId: "loopback-explicit", directory: "/repo" } } +const unexpected = () => { throw new Error("Host/native work before capability admission") } +function manager() { + const calls: string[] = [] + const value = { + get: () => workspace, list: () => [workspace], getServiceLocation: () => ({ directory: "/repo" }), + requireWorkspaceCapability: (id: string, capability: string) => { calls.push(`${id}:${capability}`); throw denied }, + getSharedServiceConnection: unexpected, getSharedServiceClient: unexpected, + getWorktreeIdentityForPath: unexpected, getServiceDirectoryForPath: unexpected, + getServiceWslDistro: unexpected, ownsLocation: unexpected, getSessionEnvironment: unexpected, + } + return { value: value as never, calls } +} +const auth = { isAuthEnabled: () => true, getSessionFromRequest: () => ({ sessionId: "cookie", username: "human" }) } + +test("Mission reads and mutations reject explicit bindings with the shared structured error", async t => { + const f = manager(), app = Fastify() + t.after(() => app.close()) + registerMissionRoutes(app, { workspaceManager: f.value } as never) + for (const request of [ + { method: "GET", url: "/api/workspaces/explicit/missions" }, + { method: "GET", url: "/api/workspaces/explicit/missions/msn_same" }, + { method: "GET", url: "/api/workspaces/explicit/missions/msn_same/admission" }, + { method: "GET", url: "/api/workspaces/explicit/missions/msn_same/content?kind=mission&field=objective&offset=0" }, + { method: "POST", url: "/api/workspaces/explicit/missions", payload: { objective: "Review", requestId: "create_1", template: "custom" } }, + { method: "PATCH", url: "/api/workspaces/explicit/missions/msn_same", payload: { objective: "Review", expectedRevision: 1, requestId: "update_1" } }, + { method: "POST", url: "/api/workspaces/explicit/missions/msn_same/control", payload: { action: "start", expectedRevision: 1, requestId: "start_1" } }, + { method: "DELETE", url: "/api/workspaces/explicit/missions/msn_same", payload: { expectedRevision: 1, requestId: "delete_1" } }, + { method: "POST", url: "/api/workspaces/explicit/missions/msn_same/recover", payload: { expectedRevision: 1, target: "coordinator" } }, + ]) { + const result = await app.inject(request as never) + assert.equal(result.statusCode, 403, `${request.url}: ${result.body}`) + assert.deepEqual(result.json(), { error: denied.code, code: denied.code, capability: "missions", reason: { code: "deferred" } }) + } + assert.equal(f.calls.length, 9) +}) + +test("creation, map mutation and human control deny before any host/native preparation", async () => { + for (const operation of [ + (m: never) => prepareMissionCreation({ manager: m, workspaceID: "explicit", signal, request: {} }), + (m: never) => prepareMissionMapMutation({ manager: m, workspaceID: "explicit", signal }), + (m: never) => prepareHumanRecurrenceControl({ raw: { socket: {} } } as never, "explicit", + { scheduleID: "daily", requestID: "play_1", action: "play", expectedRevision: 0 }, { manager: m, auth } as never, signal), + ]) { + const f = manager() + await assert.rejects(operation(f.value), error => error === denied) + assert.deepEqual(f.calls, ["explicit:missions"]) + } +}) + +test("recurrence display and exact status routes return structured capability refusal before inventory", async t => { + const f = manager(), app = Fastify() + t.after(() => app.close()) + const deps = { workspaceManager: f.value, manager: f.value, auth, fence: {}, settings: {}, bridgeToken: "fixture" } as never + registerMissionRecurrenceSnapshot(app, deps) + registerMissionRecurrenceCurrent(app, deps) + registerMissionRecurrenceControlStatus(app, deps) + registerMissionRecurrenceManual(app, deps) + registerMissionRecurrenceCreate(app, deps) + for (const request of [ + { method: "GET", url: "/api/workspaces/explicit/missions/recurrence" }, + { method: "GET", url: "/api/workspaces/explicit/missions/recurrence/daily/passages/passage" }, + { method: "GET", url: "/api/workspaces/explicit/missions/recurrence/daily/current" }, + { method: "GET", url: "/api/workspaces/explicit/missions/recurrence/daily/current/passage/content?kind=overview§ion=objective" }, + { method: "POST", url: "/api/workspaces/explicit/missions/recurrence/daily/control/status", payload: { requestID: "play_1", action: "play", expectedRevision: 0 } }, + { method: "GET", url: "/api/workspaces/explicit/missions/recurrence/daily/run-now/status?requestID=manual_1&expectedRevision=0" }, + { method: "POST", url: "/api/workspaces/explicit/missions/recurrence", payload: { requestID: "create_1", instructions: "Review", clock: { time: "12:00", zone: "UTC" }, template: "custom", watchedConversationIDs: [], taskMode: "native" } }, + ]) { + const result = await app.inject(request as never) + assert.equal(result.statusCode, 403, `${request.url}: ${result.body}`) + assert.deepEqual(result.json(), { error: denied.code, code: denied.code, capability: "missions", reason: { code: "deferred" } }) + } + assert.equal(f.calls.length, 7) +}) + +test("early human verification callbacks deny explicit owners before profile/host/native reads", async () => { + const f = manager(), deps = { manager: f.value } as never + await assert.rejects(verifyMissionHumanAnswer({ sessionID: "ses_same", formID: "frm_1", projectID: "project", + location: { directory: "/repo" }, profileID: "profile", executionHost: "local", workspaceID: "explicit", + principal: { kind: "cookie", sessionID: "cookie" }, username: "human", answer: { q0: "yes" }, issuedAt: Date.now() }, deps, signal), error => error === denied) + const identity = { sessionID: "cookie", workspaceID: "explicit", requestID: "play_1", location: { directory: "/repo" }, + scheduleID: "daily", action: "play" as const, expectedRevision: 0, issuedAt: Date.now(), + profileSource: { profileID: "profile", executionHost: "local", configYamlPath: "/host/config.yaml" } } + await assert.rejects(verifyHumanRecurrenceRequest({ ...identity, digest: recurrenceControlRequestDigest(identity) }, deps, signal), error => error === denied) + assert.deepEqual(f.calls, ["explicit:missions", "explicit:missions"]) +}) + +test("all Mission bridge owner walks filter explicit records before acquisition", async () => { + const f = manager(), fence = {} as never, coordinator = "ses_same" + const task = { missionID: "msn_same", taskKey: "task-one" } + const commands: Array<() => Promise> = [ + () => admitMissionInput(f.value, fence, coordinator, { kind: "prompt", input: { sessionID: coordinator, id: "msg_same", text: "Review", + metadata: { "codenomad.mission": { version: 1, missionID: task.missionID, kind: "assignment", taskKey: task.taskKey } }, delivery: "queue", resume: true } }, signal), + () => admitMissionInput(f.value, fence, coordinator, { kind: "lifecycle", input: { missionID: task.missionID, operationID: "op_1", sessionID: coordinator } }, signal), + () => admitMissionInput(f.value, fence, coordinator, { kind: "cleanup", input: { missionID: task.missionID, deletionID: "delete_1", sessionID: coordinator } }, signal), + () => createManagedMissionRoot(f.value, fence, coordinator, { kind: "create-root", input: task }, signal), + () => prepareCoordinatorMission(f.value, fence, coordinator, { kind: "prepare", input: { missionID: task.missionID, requestID: "prepare_1", objective: "Review", template: "custom" } }, signal), + () => observeMissionTask(f.value, coordinator, { kind: "task-sessions", input: task }, signal), + () => interruptMissionTask(f.value, fence, coordinator, { kind: "interrupt", input: task }, signal), + ] + for (const command of commands) await assert.rejects(command(), /Missing mission/) + assert.deepEqual(f.calls, []) +}) diff --git a/packages/server/src/server/routes/mission-human-answer.test.ts b/packages/server/src/server/routes/mission-human-answer.test.ts index 3f16f4bc10..a40e61e210 100644 --- a/packages/server/src/server/routes/mission-human-answer.test.ts +++ b/packages/server/src/server/routes/mission-human-answer.test.ts @@ -47,7 +47,7 @@ function harness(options: { mission?: boolean; journal?: boolean; auth: boolean; : options.auth ? { sessionId: "cookie", username: "person" } : { sessionId: "auth-disabled", username: "local" } const deps = { auth: { isAuthEnabled: () => options.auth, getSessionFromRequest: () => human }, - manager: { get: () => workspace, getServiceWslDistro: () => undefined, ownsLocation: async () => state.owned }, + manager: { requireWorkspaceCapability: () => new AbortController().signal, get: () => workspace, getServiceWslDistro: () => undefined, ownsLocation: async () => state.owned }, settings: { getProfileScope: () => ({ key: "profile", channel: "c", configIdentity: "i" }) }, bridgeToken: "token", ...(options.remoteDevices === false ? {} : { remoteDevices: { isDeviceAuthorized: (id: string) => id === "device-1" && state.authorized } }), @@ -145,7 +145,7 @@ test("the bridge verifier revalidates the exact principal kind against live auth const deps = (auth: boolean) => ({ auth: { isAuthEnabled: () => auth, getCookieName: () => "c", getSessionFromHeaders: ({ cookie }: { cookie: string }) => cookie === "c=cookie" ? { sessionId: "cookie", username: "person" } : null }, - manager: { get: () => workspace, getServiceWslDistro: () => undefined, getSharedServiceConnection: async () => connection, ownsLocation: async () => true }, + manager: { requireWorkspaceCapability: () => new AbortController().signal, get: () => workspace, getServiceWslDistro: () => undefined, getSharedServiceConnection: async () => connection, ownsLocation: async () => true }, settings: { getProfileScope: () => ({ key: "profile" }) }, remoteDevices: { isDeviceAuthorized: (id: string) => id === "device-1" && authorized }, }) as never diff --git a/packages/server/src/server/routes/mission-human-answer.ts b/packages/server/src/server/routes/mission-human-answer.ts index c7d1910a9f..149bd34719 100644 --- a/packages/server/src/server/routes/mission-human-answer.ts +++ b/packages/server/src/server/routes/mission-human-answer.ts @@ -11,7 +11,7 @@ import { sameLocation, locationRequestOptions } from "../../opencode/compatibili import { isRemoteRequest, remoteDeviceOf } from "../../remote-control/request-origin" import type { RemoteControlManager } from "../../remote-control/manager" -type Manager = Pick +type Manager = Pick type Deps = { auth: AuthManager; manager: Manager; settings: Pick; bridgeToken: string /** Live Remote Control device authorization; absent means no remote principal qualifies. */ remoteDevices?: Pick } @@ -56,6 +56,7 @@ function requestPrincipal(request: FastifyRequest, deps: Deps): { principal: Hum async function prepareMissionHumanAnswer(request: FastifyRequest, workspaceID: string, sessionID: string, formID: string, deps: Deps, connection: ServiceConnection, signal: AbortSignal) { + deps.manager.requireWorkspaceCapability(workspaceID, "missions") const workspace = deps.manager.get(workspaceID), profile = deps.settings.getProfileScope() const distro = deps.manager.getServiceWslDistro(workspaceID), client = connection.client // Without an authenticated UI principal no mark can be written: answer ordinarily. @@ -118,6 +119,7 @@ async function prepareMissionHumanAnswer(request: FastifyRequest, workspaceID: s * record or principal boolean supplied by a model. Nothing persists the cookie. */ export async function verifyMissionHumanAnswer(raw: unknown, deps: Omit, signal: AbortSignal) { const body = humanAnswerProofSchema.parse(raw) + deps.manager.requireWorkspaceCapability(body.workspaceID, "missions") assertHumanAnswerFresh(body); signal.throwIfAborted() const principal = body.principal const authenticated = () => { diff --git a/packages/server/src/server/routes/mission-input.ts b/packages/server/src/server/routes/mission-input.ts index 1969a5add6..7ba8947d35 100644 --- a/packages/server/src/server/routes/mission-input.ts +++ b/packages/server/src/server/routes/mission-input.ts @@ -1,4 +1,5 @@ import { z } from "zod" +import { localMissionWorkspaces } from "../../missions/workspace-capability" import { isDeepStrictEqual } from "node:util" import { CODENOMAD_MISSIONS_RPC } from "../../missions/rpc" import type { MissionSnapshot } from "../../missions/model" @@ -50,7 +51,7 @@ export async function admitMissionInput(manager: Manager, fence: WorktreeDeletio return cleanupMissionSession(manager, fence, coordinatorID, command, signal) } const { kind, input } = inputSchema.parse(command) - const owner = await Promise.any(manager.list().map(async workspace => { + const owner = await Promise.any(localMissionWorkspaces(manager).map(async workspace => { const connection = await manager.getSharedServiceConnection(workspace.id) if (!connection) throw new Error("Workspace is not ready") const coordinator = await connection.client.session.get({ sessionID: coordinatorID }) diff --git a/packages/server/src/server/routes/mission-lifecycle.ts b/packages/server/src/server/routes/mission-lifecycle.ts index b38c20b3a8..de1ef01253 100644 --- a/packages/server/src/server/routes/mission-lifecycle.ts +++ b/packages/server/src/server/routes/mission-lifecycle.ts @@ -1,4 +1,5 @@ import { isSessionNotFoundError } from "@opencode/client" +import { localMissionWorkspaces } from "../../missions/workspace-capability" import { z } from "zod" import { isDeepStrictEqual } from "node:util" import { CODENOMAD_MISSIONS_RPC } from "../../missions/rpc" @@ -24,7 +25,7 @@ type Manager = Pick { + const owner = await Promise.any(localMissionWorkspaces(manager).map(async workspace => { const connection = await manager.getSharedServiceConnection(workspace.id) if (!connection) throw new Error("Workspace unavailable") const coordinator = await connection.client.session.get({ sessionID: coordinatorID }, { signal }) diff --git a/packages/server/src/server/routes/mission-map-mutation.test.ts b/packages/server/src/server/routes/mission-map-mutation.test.ts index 21c07ff2c3..845c8b269e 100644 --- a/packages/server/src/server/routes/mission-map-mutation.test.ts +++ b/packages/server/src/server/routes/mission-map-mutation.test.ts @@ -34,6 +34,7 @@ function harness(hooks: { inventory?(state: State): void; dispatch?(state: State get: () => state.workspace, getServiceLocation: () => state.workspace ? { directory: "/owned/repo" } : undefined, getSharedServiceConnection: async () => ({ client, assertCurrent: () => { if (!state.current) throw new Error("Connection replaced") } }), + requireWorkspaceCapability: () => new AbortController().signal, ownsLocation: async () => state.workspace !== undefined, getServiceDirectoryForPath: async (_id: string, directory: string) => directory, getWorktreeIdentityForPath: async (_id: string, directory: string) => directory, diff --git a/packages/server/src/server/routes/mission-map-mutation.ts b/packages/server/src/server/routes/mission-map-mutation.ts index 2e0d5726f7..6c74b03c45 100644 --- a/packages/server/src/server/routes/mission-map-mutation.ts +++ b/packages/server/src/server/routes/mission-map-mutation.ts @@ -5,7 +5,7 @@ import { CODENOMAD_MISSIONS_RPC, CODENOMAD_MISSIONS_RPC_ID } from "../../mission import { locationRequestOptions, sameLocation } from "../../opencode/compatibility/location" import { admitMissionCreationLocations } from "./mission-creation-admission" -export type MissionMapMutationManager = Pick export class MissionMapMutationError extends Error { @@ -28,6 +28,7 @@ export async function prepareMissionMapMutation(input: { signal.throwIfAborted() const workspace = manager.get(workspaceID), base = manager.getServiceLocation(workspaceID) if (!workspace || !base) throw new MissionMapMutationError(404, "Workspace unavailable") + manager.requireWorkspaceCapability(workspaceID, "missions") if (!input.fence) throw new MissionMapMutationError(503, "Mission plugin unavailable") let connection: ServiceConnection | undefined try { connection = await wait(manager.getSharedServiceConnection(workspaceID)) } diff --git a/packages/server/src/server/routes/mission-prepare.ts b/packages/server/src/server/routes/mission-prepare.ts index 1b1c540514..7d3d21d1b8 100644 --- a/packages/server/src/server/routes/mission-prepare.ts +++ b/packages/server/src/server/routes/mission-prepare.ts @@ -1,4 +1,5 @@ import { z } from "zod" +import { localMissionWorkspaces } from "../../missions/workspace-capability" import { CODENOMAD_MISSIONS_RPC } from "../../missions/rpc" import type { MissionMap, MissionSnapshot } from "../../missions/model" import { MissionControlError } from "../../missions/control-error" @@ -26,7 +27,7 @@ type Manager = MissionCreationPipelineManager & Pick export async function prepareCoordinatorMission(manager: Manager, fence: WorktreeDeletionFence, coordinatorID: string, command: unknown, signal: AbortSignal): Promise<{ mission: MissionMap }> { const { input } = commandSchema.parse(command) - const owner = await Promise.any(manager.list().map(async workspace => { + const owner = await Promise.any(localMissionWorkspaces(manager).map(async workspace => { const connection = await manager.getSharedServiceConnection(workspace.id) if (!connection) throw new Error("Workspace unavailable") const coordinator = await connection.client.session.get({ sessionID: coordinatorID }, { signal }) diff --git a/packages/server/src/server/routes/mission-recurrence-control-status.ts b/packages/server/src/server/routes/mission-recurrence-control-status.ts index 2e00100909..791ffaad67 100644 --- a/packages/server/src/server/routes/mission-recurrence-control-status.ts +++ b/packages/server/src/server/routes/mission-recurrence-control-status.ts @@ -1,4 +1,5 @@ import type { FastifyInstance } from "fastify" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" import { z } from "zod" import type { AuthManager } from "../../auth/manager" import type { WorkspaceManager } from "../../workspaces/manager" @@ -17,7 +18,7 @@ import type { RemoteControlManager } from "../../remote-control/manager" * generic RPC proxy, even when a signed archive establishes prior commitment. */ export function registerMissionRecurrenceControlStatus(app: FastifyInstance, deps: { auth: Pick - manager: Pick fence: WorktreeDeletionFence remoteDevices?: Pick @@ -33,6 +34,7 @@ export function registerMissionRecurrenceControlStatus(app: FastifyInstance, dep if (!input.success) return reply.code(400).send({ error: "Invalid exact control status request" }) const lifetime = requestAdmission(request, reply), id = request.params.id try { + deps.manager.requireWorkspaceCapability(id, "missions") const workspace = deps.manager.get(id), base = deps.manager.getServiceLocation(id) if (!workspace || !base) return reply.code(404).send({ error: "Workspace unavailable" }) const directory = requestedDirectory ? await lifetime.wait(deps.manager.getServiceDirectoryForPath(id, requestedDirectory)) : base.directory @@ -71,7 +73,8 @@ export function registerMissionRecurrenceControlStatus(app: FastifyInstance, dep current() reconcileRecurrenceControlHold(deps.fence, id, location, read, result, connection, owner) return result - } catch { + } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) request.log.warn({ code: "recurrence-control-status-unavailable" }, "Mission recurrence control status unavailable") return reply.code(503).send({ error: "Exact recurrence control status unavailable" }) } finally { lifetime.dispose() } diff --git a/packages/server/src/server/routes/mission-recurrence-control.test.ts b/packages/server/src/server/routes/mission-recurrence-control.test.ts index 20c2a9bd1e..43b19c48e0 100644 --- a/packages/server/src/server/routes/mission-recurrence-control.test.ts +++ b/packages/server/src/server/routes/mission-recurrence-control.test.ts @@ -63,6 +63,7 @@ test("real cookie human Play uses exact selected YAML; lost ACK performs one rec settings: { configYamlPathForAuthority: () => yaml, getProfileScope: () => selected }, manager: { get: () => workspace, getServiceLocation: () => location, getServiceDirectoryForPath: async () => directory, getSharedServiceConnection: async () => ({ client, assertCurrent: () => {} }), ownsLocation: async () => true, + requireWorkspaceCapability: () => new AbortController().signal, getServiceWslDistro: () => undefined, getServicePathStyle: () => process.platform === "win32" ? "win32" : "posix", getWorktreeIdentityForPath: async () => canonicalWorktreeIdentity(directory), getHostPathForServicePath: async () => directory } } as never) const url = "/api/workspaces/owned/missions/recurrence/daily_review/control" diff --git a/packages/server/src/server/routes/mission-recurrence-control.ts b/packages/server/src/server/routes/mission-recurrence-control.ts index 6e4cc061be..302684e14b 100644 --- a/packages/server/src/server/routes/mission-recurrence-control.ts +++ b/packages/server/src/server/routes/mission-recurrence-control.ts @@ -1,4 +1,5 @@ import type { FastifyInstance } from "fastify" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" import { prepareHumanRecurrenceControl } from "./mission-recurrence-play-preparation" import { CODENOMAD_MISSIONS_RPC } from "../../missions/rpc" import { recurrenceControlStatusSchema, recurrenceControlRouteSchema, recurrenceControlStateMatches, recurrenceRefusalCode } from "../../missions/recurrence-control-contract" @@ -65,6 +66,7 @@ export function registerMissionRecurrenceControl(app: FastifyInstance, deps: { return reply.code(result.outcome === "committed" ? 200 : 503).send(result) } } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) // Drop only this attempt's still-preparing admission before classification. // dispose is idempotent and preserves any original partial/uncertain permit. if (!dispatched) prepared?.dispose() diff --git a/packages/server/src/server/routes/mission-recurrence-create.test.ts b/packages/server/src/server/routes/mission-recurrence-create.test.ts index bb97fbaa1b..5edc3f64ac 100644 --- a/packages/server/src/server/routes/mission-recurrence-create.test.ts +++ b/packages/server/src/server/routes/mission-recurrence-create.test.ts @@ -78,6 +78,7 @@ test("authenticated recurrence CREATE shares project identity, rejects foreign/c const workspace = { id: "workspace" } const manager: any = { get: () => workspace, getServiceLocation: () => ({ directory: active }), getSharedServiceConnection: async () => connection, + requireWorkspaceCapability: () => new AbortController().signal, ownsLocation: async (_id: string, location: any) => locations.includes(location.directory), getServiceDirectoryForPath: async (_id: string, directory: string) => locations.includes(directory) ? directory : undefined, getWorktreeIdentityForPath: async (_id: string, directory: string) => { diff --git a/packages/server/src/server/routes/mission-recurrence-create.ts b/packages/server/src/server/routes/mission-recurrence-create.ts index 9fd7052062..9ad4a9c108 100644 --- a/packages/server/src/server/routes/mission-recurrence-create.ts +++ b/packages/server/src/server/routes/mission-recurrence-create.ts @@ -1,4 +1,5 @@ import type { FastifyInstance } from "fastify" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" import { z } from "zod" import type { WorkspaceManager } from "../../workspaces/manager" import type { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" @@ -38,7 +39,7 @@ const schema = z.object({ requestID: z.string().regex(/^[A-Za-z0-9_-]{3,100}$/), profiles: missionProfilesInputSchema, taskMode: missionTaskModeInputSchema, }).strict() -type Manager = Pick type NativeSummary = { schedule: { id: string; revision: number; state: string; digest: string; projectID: string; projectCanonical: string } | null } @@ -66,6 +67,7 @@ export function registerMissionRecurrenceCreate(app: FastifyInstance, deps: { wo return reply.code(400).send({ error: "Invalid recurrence creation request" }) } const input = parsed.data, manager = deps.workspaceManager, workspaceID = request.params.id + manager.requireWorkspaceCapability(workspaceID, "missions") if (input.template === "compare") { const error = compareModelError(input.profiles) if (error) return reply.code(400).send({ error, code: error }) @@ -216,6 +218,7 @@ export function registerMissionRecurrenceCreate(app: FastifyInstance, deps: { wo admission.settled() return { schedule: created.schedule } } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) // Hold codes keep their own meaning: creation-uncertain stays held in the UI. if (error instanceof MissionCreationHoldError) { return reply.code(error.code === "creation-capacity" ? 503 : 409).send({ error: error.message, code: error.code }) diff --git a/packages/server/src/server/routes/mission-recurrence-current.test.ts b/packages/server/src/server/routes/mission-recurrence-current.test.ts index 175d1bbd78..2eed286628 100644 --- a/packages/server/src/server/routes/mission-recurrence-current.test.ts +++ b/packages/server/src/server/routes/mission-recurrence-current.test.ts @@ -62,6 +62,7 @@ async function fixture() { getWorktreeIdentityForPath: async (_id: string, directory: string) => directory, ownsLocation: async (_id: string, target: typeof location) => state.owned && target.directory === location.directory, getSharedServiceConnection: async () => state.available ? { client, assertCurrent() { if (!state.connected) throw new Error("Connection replaced") } } : undefined, + requireWorkspaceCapability: () => new AbortController().signal, } as never, worktreeDeletionFence: fence }) const url = `/api/workspaces/workspace/missions/recurrence/${scheduleID}/current` const page = async (selector: unknown) => app.inject({ method: "POST", url: `${url}/${passageID}/page`, payload: { source: envelope().source, selector } }) diff --git a/packages/server/src/server/routes/mission-recurrence-current.ts b/packages/server/src/server/routes/mission-recurrence-current.ts index c8635cf5a7..fd713ce42d 100644 --- a/packages/server/src/server/routes/mission-recurrence-current.ts +++ b/packages/server/src/server/routes/mission-recurrence-current.ts @@ -1,4 +1,5 @@ import type { FastifyInstance, FastifyRequest, FastifyReply } from "fastify" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" import { z } from "zod" import { projectMissionActivity } from "../../missions/activity" import { recurrenceIDSchema } from "../../missions/recurrence-contract" @@ -13,7 +14,7 @@ import type { WorktreeDeletionFence } from "../../workspaces/worktree-session-ev import { captureDisplayIdentities } from "../../workspaces/worktree-display-identity" import { requestAdmission } from "../request-admission" -type Deps = { workspaceManager: Pick; +type Deps = { workspaceManager: Pick; worktreeDeletionFence?: WorktreeDeletionFence } type Params = { id: string; scheduleID: string; passageID?: string } const paramsSchema = z.object({ id: z.string().trim().min(1).max(200), scheduleID: recurrenceIDSchema, passageID: recurrenceIDSchema.optional() }).strict() @@ -35,8 +36,9 @@ export function registerMissionRecurrenceCurrent(app: FastifyInstance, deps: Dep const lifetime = requestAdmission(request, reply), manager = deps.workspaceManager const workspace = manager.get(params.data.id), owned = manager.getServiceLocation(params.data.id) if (!workspace || !owned) { lifetime.dispose(); return reply.code(404).send({ error: "Workspace unavailable" }) } - const deletionCapture = captureDisplayIdentities(deps.worktreeDeletionFence, manager, params.data.id, [owned.directory]) try { + manager.requireWorkspaceCapability(params.data.id, "missions") + const deletionCapture = captureDisplayIdentities(deps.worktreeDeletionFence, manager, params.data.id, [owned.directory]) const connection = await lifetime.wait(manager.getSharedServiceConnection(params.data.id)) if (!connection) throw new Error("Mission service unavailable") const deletionCurrent = await lifetime.wait(deletionCapture) @@ -99,6 +101,7 @@ export function registerMissionRecurrenceCurrent(app: FastifyInstance, deps: Dep if (missionPanelBytes(result) > MISSION_PANEL_PAGE_BYTES) throw new Error("Current passage response capacity") return result } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) request.log.warn({ err: error, workspaceId: params.data.id }, "Current Mission passage unavailable") return reply.code(503).send({ error: "Current Mission passage unavailable" }) } finally { lifetime.dispose() } diff --git a/packages/server/src/server/routes/mission-recurrence-disconnect.test.ts b/packages/server/src/server/routes/mission-recurrence-disconnect.test.ts index eff56924b1..a3c8ac92b2 100644 --- a/packages/server/src/server/routes/mission-recurrence-disconnect.test.ts +++ b/packages/server/src/server/routes/mission-recurrence-disconnect.test.ts @@ -51,6 +51,7 @@ for (const neverResolved of [false, true]) test(`HTTP disconnect retains native let connection = originalConnection const manager = { get: () => workspace, getServiceLocation: () => location, getServiceDirectoryForPath: async () => directory, getSharedServiceConnection: async () => connection, ownsLocation: async () => true, + requireWorkspaceCapability: () => new AbortController().signal, getServiceWslDistro: () => undefined, getServicePathStyle: () => process.platform === "win32" ? "win32" : "posix", getWorktreeIdentityForPath: async () => canonicalWorktreeIdentity(directory), getHostPathForServicePath: async () => directory } app.addHook("onRequest", (request, reply, done) => { diff --git a/packages/server/src/server/routes/mission-recurrence-expired-proof.test.ts b/packages/server/src/server/routes/mission-recurrence-expired-proof.test.ts index 5fb3692309..e8de5b76a9 100644 --- a/packages/server/src/server/routes/mission-recurrence-expired-proof.test.ts +++ b/packages/server/src/server/routes/mission-recurrence-expired-proof.test.ts @@ -99,6 +99,7 @@ async function fixture() { const manager = { get: () => workspace, getServiceLocation: () => ({ directory }), getServiceDirectoryForPath: async (_id: string, requested: string) => realpathSync(requested), getSharedServiceConnection: async () => state.connection, ownsLocation: async () => true, + requireWorkspaceCapability: () => new AbortController().signal, getServiceWslDistro: () => undefined, getServicePathStyle: () => process.platform === "win32" ? "win32" : "posix", getWorktreeIdentityForPath: async () => state.checkout, getHostPathForServicePath: async (_id: string, requested: string) => requested } const fence = new WorktreeDeletionFence(200) diff --git a/packages/server/src/server/routes/mission-recurrence-manual.ts b/packages/server/src/server/routes/mission-recurrence-manual.ts index d25e9469fd..e859c33c01 100644 --- a/packages/server/src/server/routes/mission-recurrence-manual.ts +++ b/packages/server/src/server/routes/mission-recurrence-manual.ts @@ -1,4 +1,5 @@ import type { FastifyInstance } from "fastify" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" import { z } from "zod" import { CODENOMAD_MISSIONS_RPC } from "../../missions/rpc" import { recurrenceManualRequestSchema, recurrenceManualResultSchema } from "../../missions/recurrence-manual-rpc" @@ -24,6 +25,7 @@ export function registerMissionRecurrenceManual(app: FastifyInstance, deps: Para const lifetime = requestAdmission(request, reply), workspace = deps.manager.get(request.params.id), base = deps.manager.getServiceLocation(request.params.id) if (!workspace || !base) { lifetime.dispose(); return reply.code(404).send({ error: "Workspace unavailable" }) } try { + deps.manager.requireWorkspaceCapability(request.params.id, "missions") const directory = query.data.directory ? await lifetime.wait(deps.manager.getServiceDirectoryForPath(request.params.id, query.data.directory)) : base.directory const connection = await lifetime.wait(deps.manager.getSharedServiceConnection(request.params.id)) if (!directory || !connection) throw new Error("Manual status unavailable") @@ -57,7 +59,10 @@ export function registerMissionRecurrenceManual(app: FastifyInstance, deps: Para : { version: 1, ...input.data, revision: input.data.expectedRevision + 1, outcome: "committed", controlsComplete: true }, connection, owner) } return result - } catch { return reply.code(503).send({ error: "Manual status unavailable" }) } + } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + return reply.code(503).send({ error: "Manual status unavailable" }) + } finally { lifetime.dispose() } }) app.post<{ Params: { id: string; scheduleID: string } }>("/api/workspaces/:id/missions/recurrence/:scheduleID/run-now", async (request, reply) => { @@ -92,6 +97,7 @@ export function registerMissionRecurrenceManual(app: FastifyInstance, deps: Para } return reply.code(result.outcome === "unknown" ? 503 : 200).send(result) } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) if (!dispatched) prepared?.dispose() const refused = dispatched ? undefined : recurrenceNotDispatchedReply(error, { fence: deps.fence, workspaceID: request.params.id, request: { ...input.data, scheduleID: request.params.scheduleID, action: "run-now" } }) diff --git a/packages/server/src/server/routes/mission-recurrence-partial-retry.test.ts b/packages/server/src/server/routes/mission-recurrence-partial-retry.test.ts index 55c69d4232..a66e2a9c68 100644 --- a/packages/server/src/server/routes/mission-recurrence-partial-retry.test.ts +++ b/packages/server/src/server/routes/mission-recurrence-partial-retry.test.ts @@ -93,6 +93,7 @@ async function fixture() { assertCurrent() { if (!connection.current) throw new Error("Connection replaced") } } const manager = { get: () => location, getServiceLocation: () => location, getServiceDirectoryForPath: async () => directory, getSharedServiceConnection: async () => env.available ? connection : undefined, ownsLocation: async () => env.owns, + requireWorkspaceCapability: () => new AbortController().signal, getServiceWslDistro: () => undefined, getServicePathStyle: () => process.platform === "win32" ? "win32" : "posix", getWorktreeIdentityForPath: async () => checkout, getHostPathForServicePath: async () => directory } const app = Fastify({ logger: false }) diff --git a/packages/server/src/server/routes/mission-recurrence-play-preparation.ts b/packages/server/src/server/routes/mission-recurrence-play-preparation.ts index 6bf960bbbf..90f6843da9 100644 --- a/packages/server/src/server/routes/mission-recurrence-play-preparation.ts +++ b/packages/server/src/server/routes/mission-recurrence-play-preparation.ts @@ -23,11 +23,12 @@ import { recurrenceHumanSession } from "./mission-recurrence-proof" * inside the authenticated human request, never from native RPC path options. */ export async function prepareHumanRecurrenceControl(request: FastifyRequest, workspaceID: string, raw: unknown, deps: { auth: AuthManager; settings: Pick; - manager: Pick; fence: WorktreeDeletionFence; bridgeToken: string; remoteDevices?: Pick }, signal: AbortSignal) { const input = recurrenceControlHttpSchema.parse(raw), session = recurrenceHumanSession(request, deps) if (!session) throw new Error("Human authentication required") + deps.manager.requireWorkspaceCapability(workspaceID, "missions") const workspace = deps.manager.get(workspaceID), base = deps.manager.getServiceLocation(workspaceID) if (!workspace || !base) throw new Error("Workspace unavailable") const profile = deps.settings.getProfileScope(), distro = deps.manager.getServiceWslDistro(workspaceID) diff --git a/packages/server/src/server/routes/mission-recurrence-proof.test.ts b/packages/server/src/server/routes/mission-recurrence-proof.test.ts index a9356a7733..0df4a6d748 100644 --- a/packages/server/src/server/routes/mission-recurrence-proof.test.ts +++ b/packages/server/src/server/routes/mission-recurrence-proof.test.ts @@ -14,6 +14,7 @@ for (const action of ["play", "configure", "delete"] as const) test(`${action} p auth: { isAuthEnabled: () => authEnabled, getCookieName: () => "cookie", getSessionFromHeaders: () => sessionCurrent ? { username: "human", sessionId: "real-cookie" } : null }, manager: { getServiceWslDistro: () => undefined, get: () => workspace, ownsLocation: async () => owned, + requireWorkspaceCapability: () => new AbortController().signal, getSharedServiceConnection: async () => ({ assertCurrent: () => {}, client: { location: { get: async () => ({ directory: "/owned" }) }, } }) } } @@ -41,6 +42,7 @@ test("ownership finishing after the original proof deadline never acknowledges h auth: { isAuthEnabled: () => true, getCookieName: () => "cookie", getSessionFromHeaders: () => ({ username: "human", sessionId: "real-cookie" }) }, manager: { getServiceWslDistro: () => undefined, get: () => workspace, ownsLocation: async () => { now += 200; return true }, + requireWorkspaceCapability: () => new AbortController().signal, getSharedServiceConnection: async () => ({ assertCurrent: () => {}, client: { location: { get: async () => ({ directory: "/owned" }) } } }) } } await assert.rejects(verifyHumanRecurrenceRequest({ ...identity, digest: recurrenceControlRequestDigest(identity) }, deps as never, new AbortController().signal, () => now), /proof expired/) diff --git a/packages/server/src/server/routes/mission-recurrence-proof.ts b/packages/server/src/server/routes/mission-recurrence-proof.ts index aa0b27887f..cd79309555 100644 --- a/packages/server/src/server/routes/mission-recurrence-proof.ts +++ b/packages/server/src/server/routes/mission-recurrence-proof.ts @@ -43,11 +43,12 @@ const proofSchema = z.object({ sessionID: z.string().min(1).max(256), workspaceI * paired devices in the live Remote Control registry. */ export async function verifyHumanRecurrenceRequest(input: unknown, deps: { auth: Pick - manager: Pick + manager: Pick settings?: Pick remoteDevices?: HumanDeps["remoteDevices"] }, signal: AbortSignal, now: () => number = Date.now): Promise<{ admitted: true }> { const body = proofSchema.parse(input), { digest, ...identity } = body + deps.manager.requireWorkspaceCapability(body.workspaceID, "missions") signal.throwIfAborted() assertRecurrenceProofFresh(body.issuedAt, now()) if (!deps.auth.isAuthEnabled() || body.sessionID === "auth-disabled" || recurrenceControlRequestDigest(identity) !== digest) throw new Error("Recurrence human request unavailable") diff --git a/packages/server/src/server/routes/mission-recurrence-reader.test.ts b/packages/server/src/server/routes/mission-recurrence-reader.test.ts index a617ae3ab9..f74e1048e9 100644 --- a/packages/server/src/server/routes/mission-recurrence-reader.test.ts +++ b/packages/server/src/server/routes/mission-recurrence-reader.test.ts @@ -289,6 +289,7 @@ test("authenticated backend GET forwards only exact archive selectors and owned get: () => workspace, getServiceLocation: () => ({ directory: f.directory }), getWorktreeIdentityForPath: async (_id: string, directory: string) => directory, ownsLocation: async (_id: string, location: unknown) => { assert.deepEqual(location, { directory: f.directory }); return owned }, + requireWorkspaceCapability: () => new AbortController().signal, getSharedServiceConnection: async () => { connections++ return { assertCurrent: () => { if (!connected) throw new Error("Connection changed") }, client: { diff --git a/packages/server/src/server/routes/mission-recurrence-remote.test.ts b/packages/server/src/server/routes/mission-recurrence-remote.test.ts index d6584f8eef..c608116afc 100644 --- a/packages/server/src/server/routes/mission-recurrence-remote.test.ts +++ b/packages/server/src/server/routes/mission-recurrence-remote.test.ts @@ -43,6 +43,7 @@ test("recurring controls admit a local login and a live paired device; an unqual const settings = { configYamlPathForAuthority: () => yaml, getProfileScope: () => selected } const manager = { get: () => workspace, getServiceLocation: () => location, getServiceDirectoryForPath: async () => directory, getSharedServiceConnection: async () => connection, ownsLocation: async () => true, + requireWorkspaceCapability: () => new AbortController().signal, getServiceWslDistro: () => undefined, getServicePathStyle: () => process.platform === "win32" ? "win32" : "posix", getWorktreeIdentityForPath: async () => canonicalWorktreeIdentity(directory), getHostPathForServicePath: async () => directory } // The native plugin verifies through the private bridge callback before any store write. @@ -106,6 +107,7 @@ test("recurring Create refuses an unqualified device before any native read and const app = Fastify({ logger: false }) remoteIngress(app, "device-1") const manager = { get: () => undefined, getServiceLocation: () => undefined, + requireWorkspaceCapability: () => new AbortController().signal, getSharedServiceConnection: async () => { connections++; return undefined } } const auth = { isAuthEnabled: () => true, getSessionFromRequest: () => ({ username: "human", sessionId: "remote-device:device-1" }) } registerMissionRecurrenceCreate(app, { workspaceManager: manager as never, auth, bridgeToken: "token", @@ -136,6 +138,7 @@ test("the bridge verifier keeps device and cookie principals apart and follows l getSessionFromHeaders: () => ({ username: "human", sessionId: "remote-device:device-1" }) }, ...(devices ? { remoteDevices: { isDeviceAuthorized: (id: string) => id === "device-1" && authorized } } : {}), manager: { getServiceWslDistro: () => undefined, get: () => workspace, ownsLocation: async () => true, + requireWorkspaceCapability: () => new AbortController().signal, getSharedServiceConnection: async () => ({ assertCurrent: () => {}, client: { location: { get: async () => ({ directory: "/owned" }) } } }) } }) const verify = (value = identity, devices = true) => verifyHumanRecurrenceRequest(sign(value), deps(devices) as never, new AbortController().signal) assert.deepEqual(await verify(), { admitted: true }) diff --git a/packages/server/src/server/routes/mission-recurrence-replaced-partial.test.ts b/packages/server/src/server/routes/mission-recurrence-replaced-partial.test.ts index b7c5e6a848..d17f0a7237 100644 --- a/packages/server/src/server/routes/mission-recurrence-replaced-partial.test.ts +++ b/packages/server/src/server/routes/mission-recurrence-replaced-partial.test.ts @@ -94,6 +94,7 @@ async function fixture(drainTimeoutMs = 300) { const manager = { get: () => env.workspace, getServiceLocation: () => ({ directory }), getServiceDirectoryForPath: async (_id: string, requested: string) => realpathSync(requested), getSharedServiceConnection: async () => state.connection, ownsLocation: async () => true, + requireWorkspaceCapability: () => new AbortController().signal, getServiceWslDistro: () => undefined, getServicePathStyle: () => process.platform === "win32" ? "win32" : "posix", getWorktreeIdentityForPath: async (_id: string, requested: string) => canonicalWorktreeIdentity(requested), getHostPathForServicePath: async (_id: string, requested: string) => requested } diff --git a/packages/server/src/server/routes/mission-recurrence-snapshot.test.ts b/packages/server/src/server/routes/mission-recurrence-snapshot.test.ts index 166a22d946..aac7e68c7c 100644 --- a/packages/server/src/server/routes/mission-recurrence-snapshot.test.ts +++ b/packages/server/src/server/routes/mission-recurrence-snapshot.test.ts @@ -14,6 +14,7 @@ test("owned recurrence snapshots expose simple metadata; foreign, oversized and registerMissionRecurrenceSnapshot(app, { worktreeDeletionFence: fence, workspaceManager: { get: () => workspace, getServiceLocation: () => location, ownsLocation: async () => owned, getWorktreeIdentityForPath: async (_id: string, directory: string) => directory, + requireWorkspaceCapability: () => new AbortController().signal, getSharedServiceConnection: async () => ({ assertCurrent: () => { if (!connected) throw new Error("Connection changed") }, client: { location: { get: async () => ({ project: { id: "project", canonical: "/project" } }) }, plugin: { list: async () => ({ data: [{ id: "codenomad.missions", state: { status: "active" } }] }) }, @@ -47,6 +48,7 @@ test("a WSL snapshot read during its worktree identity's deletion is never publi registerMissionRecurrenceSnapshot(app, { worktreeDeletionFence: fence, workspaceManager: { get: () => workspace, getServiceLocation: () => location, ownsLocation: async () => true, getWorktreeIdentityForPath: async () => "wsl:ubuntu:/home/dev/repo", + requireWorkspaceCapability: () => new AbortController().signal, getSharedServiceConnection: async () => ({ assertCurrent: () => {}, client: { location: { get: async () => ({ project: { id: "project", canonical: "/home/dev/repo" } }) }, plugin: { list: async () => ({ data: [{ id: "codenomad.missions", state: { status: "active" } }] }) }, diff --git a/packages/server/src/server/routes/mission-recurrence-snapshot.ts b/packages/server/src/server/routes/mission-recurrence-snapshot.ts index f509b5f538..5fded70dca 100644 --- a/packages/server/src/server/routes/mission-recurrence-snapshot.ts +++ b/packages/server/src/server/routes/mission-recurrence-snapshot.ts @@ -1,4 +1,5 @@ import type { FastifyInstance, FastifyRequest, FastifyReply } from "fastify" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" import { z } from "zod" import type { MissionRecurrenceSnapshot } from "../../api-types" import { sameLocation, locationRequestOptions } from "../../opencode/compatibility/location" @@ -16,7 +17,7 @@ const pageQuery = z.object({ section: z.coerce.number().int().nonnegative().opti revision: z.coerce.number().int().positive().optional() }).strict() export function registerMissionRecurrenceSnapshot(app: FastifyInstance, deps: { - workspaceManager: Pick + workspaceManager: Pick worktreeDeletionFence?: WorktreeDeletionFence }): void { const read = async (request: FastifyRequest<{ Params: { id: string; scheduleID?: string; passageID?: string }; Querystring: unknown }>, reply: FastifyReply) => { @@ -30,8 +31,9 @@ export function registerMissionRecurrenceSnapshot(app: FastifyInstance, deps: { const workspace = parsed.success && manager.get(parsed.data) const owned = parsed.success && manager.getServiceLocation(parsed.data) if (!workspace || !owned) { lifetime.dispose(); return reply.code(404).send({ error: "Workspace unavailable" }) } - const capture = captureDisplayIdentities(deps.worktreeDeletionFence, manager, parsed.data, [owned.directory]) try { + manager.requireWorkspaceCapability(parsed.data, "missions") + const capture = captureDisplayIdentities(deps.worktreeDeletionFence, manager, parsed.data, [owned.directory]) const connection = await lifetime.wait(manager.getSharedServiceConnection(parsed.data)) if (!connection) return reply.code(503).send({ error: "Mission service unavailable" }) const current = await lifetime.wait(capture) @@ -74,7 +76,8 @@ export function registerMissionRecurrenceSnapshot(app: FastifyInstance, deps: { || !sameLocation(snapshot.location, owned)) return reply.code(502).send({ error: "Foreign Mission recurrence snapshot" }) const result: MissionRecurrenceSnapshot = { version: 1, projectID: snapshot.projectID, schedules: snapshot.schedules } return result - } catch { + } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) request.log.warn({ code: "recurrence-snapshot-unavailable" }, "Mission recurrence snapshot unavailable") return reply.code(503).send({ error: "Mission recurrence unavailable" }) } finally { lifetime.dispose() } diff --git a/packages/server/src/server/routes/mission-recurrence-stale-revision.test.ts b/packages/server/src/server/routes/mission-recurrence-stale-revision.test.ts index 3bc027f4f1..62885ec870 100644 --- a/packages/server/src/server/routes/mission-recurrence-stale-revision.test.ts +++ b/packages/server/src/server/routes/mission-recurrence-stale-revision.test.ts @@ -84,6 +84,7 @@ test("a control or Run now refused for a stale revision is a definitive conflict const fence = new WorktreeDeletionFence(), connection = { client, assertCurrent: () => {} } const manager = { get: () => workspace, getServiceLocation: () => location, getServiceDirectoryForPath: async () => directory, getSharedServiceConnection: async () => connection, ownsLocation: async () => true, + requireWorkspaceCapability: () => new AbortController().signal, getServiceWslDistro: () => undefined, getServicePathStyle: () => process.platform === "win32" ? "win32" : "posix", getWorktreeIdentityForPath: async () => canonicalWorktreeIdentity(directory), getHostPathForServicePath: async () => directory } const deps = { auth, bridgeToken: "existing-bridge-token", fence, manager, diff --git a/packages/server/src/server/routes/mission-root-creation.ts b/packages/server/src/server/routes/mission-root-creation.ts index 901912094a..8b272f8539 100644 --- a/packages/server/src/server/routes/mission-root-creation.ts +++ b/packages/server/src/server/routes/mission-root-creation.ts @@ -1,4 +1,5 @@ import { z } from "zod" +import { localMissionWorkspaces } from "../../missions/workspace-capability" import { isSessionNotFoundError } from "@opencode/client" import { isDeepStrictEqual } from "node:util" import type { WorkspaceManager } from "../../workspaces/manager" @@ -24,7 +25,7 @@ export async function createManagedMissionRoot(manager: Manager, fence: Worktree coordinatorID: string, command: unknown, signal: AbortSignal) { const { input } = schema.parse(command) signal.throwIfAborted() - const owner = await Promise.any(manager.list().map(async workspace => { + const owner = await Promise.any(localMissionWorkspaces(manager).map(async workspace => { const connection = await manager.getSharedServiceConnection(workspace.id) signal.throwIfAborted() if (!connection) throw new Error("Workspace unavailable") diff --git a/packages/server/src/server/routes/mission-schedule-activation.test.ts b/packages/server/src/server/routes/mission-schedule-activation.test.ts index 7317ddc98a..bd7377b733 100644 --- a/packages/server/src/server/routes/mission-schedule-activation.test.ts +++ b/packages/server/src/server/routes/mission-schedule-activation.test.ts @@ -51,6 +51,7 @@ async function fixture(run: (f: any) => Promise) { } } const workspace = { id: "w" }, fence = new WorktreeDeletionFence() const manager: any = { get: () => workspace, getSharedServiceConnection: async () => connection, + requireWorkspaceCapability: () => new AbortController().signal, getServiceLocation: () => ({ directory: project }), getServiceDirectoryForPath: async (_id: string, dir: string) => dir === project ? dir : undefined, ownsLocation: async () => owned, getWorktreeIdentityForPath: async () => "owned-physical-root", getServicePathStyle: () => process.platform === "win32" ? "win32" : "posix", getServiceWslDistro: () => undefined, diff --git a/packages/server/src/server/routes/mission-schedule-activation.ts b/packages/server/src/server/routes/mission-schedule-activation.ts index 5dd43fa024..8c7337d645 100644 --- a/packages/server/src/server/routes/mission-schedule-activation.ts +++ b/packages/server/src/server/routes/mission-schedule-activation.ts @@ -5,6 +5,7 @@ import { requiresMissionCalendar } from "../../missions/launch-policy" import type { NativeScheduleSettingsActivation } from "../../opencode/native-schedule-settings-activation" import { PluginControlsError } from "../../opencode/plugin-controls" import { requestAdmission } from "../request-admission" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" import { MissionMapMutationError, prepareMissionMapMutation, type MissionMapMutationManager } from "./mission-map-mutation" import { missionScheduleActivationJournal } from "./mission-schedule-activation-journal" @@ -62,6 +63,7 @@ export function registerMissionScheduleActivation(app: FastifyInstance, deps: De } }) } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) const status = error instanceof MissionMapMutationError ? error.status : error instanceof PluginControlsError ? error.kind === "forbidden" ? 403 : error.kind === "invalid" ? 400 : error.kind === "conflict" ? 409 : 503 : 503 return reply.code(status).send({ error: "Mission schedule configuration remains unconfirmed", code: "schedule-activation-pending" }) diff --git a/packages/server/src/server/routes/mission-schedule-list.test.ts b/packages/server/src/server/routes/mission-schedule-list.test.ts index 30f64e09dd..bb1d686759 100644 --- a/packages/server/src/server/routes/mission-schedule-list.test.ts +++ b/packages/server/src/server/routes/mission-schedule-list.test.ts @@ -17,6 +17,7 @@ async function fixture(t: test.TestContext) { } }) } const connection = { client, assertCurrent: () => { if (!state.active) throw new Error("Connection retired") } } const manager = { get: () => workspace, getServiceLocation: () => ({ directory: "/project" }), getSharedServiceConnection: async () => connection, + requireWorkspaceCapability: () => new AbortController().signal, ownsLocation: async () => state.owned, getServiceDirectoryForPath: async (_id: string, directory: string) => directory, getWorktreeIdentityForPath: async () => "/project" } app.addHook("preHandler", async request => { state.abort = () => request.raw.emit("aborted") }) diff --git a/packages/server/src/server/routes/mission-schedule-list.ts b/packages/server/src/server/routes/mission-schedule-list.ts index 66cf8551a4..6fe5fdaeb4 100644 --- a/packages/server/src/server/routes/mission-schedule-list.ts +++ b/packages/server/src/server/routes/mission-schedule-list.ts @@ -7,6 +7,7 @@ import type { NativeScheduleSettingsActivation } from "../../opencode/native-sch import { PluginControlsError } from "../../opencode/plugin-controls" import type { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" import { requestAdmission } from "../request-admission" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" import { MissionMapMutationError, prepareMissionMapMutation, type MissionMapMutationManager } from "./mission-map-mutation" const params = z.object({ id: z.string().min(1).max(200) }).strict() @@ -55,6 +56,7 @@ export function registerMissionScheduleList(app: FastifyInstance, deps: Deps) { return { ...view, activation } satisfies MissionScheduleCapability }) } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) const status = error instanceof MissionMapMutationError ? error.status : 503 return reply.code(status).send({ error: "Mission schedule read unavailable", code: "schedule-read-unavailable" }) } finally { lifetime.dispose() } diff --git a/packages/server/src/server/routes/mission-scheduled.test.ts b/packages/server/src/server/routes/mission-scheduled.test.ts index 3c7421dd6c..be34ef4208 100644 --- a/packages/server/src/server/routes/mission-scheduled.test.ts +++ b/packages/server/src/server/routes/mission-scheduled.test.ts @@ -10,6 +10,51 @@ import { signNativeRecurrenceControl } from "../../missions/recurrence-control-p import { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" import { registerMissionScheduled } from "./mission-scheduled" import { scheduledMissionHold } from "./mission-scheduled-holds" +import { registerMissionScheduleList } from "./mission-schedule-list" +import { registerMissionScheduleActivation } from "./mission-schedule-activation" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" + +test("scheduled Mission reads, controls and resumed requests deny before settings, holds or native work", async t => { + const app = Fastify(), denied = new WorkspaceCapabilityError("missions", { code: "deferred" }) + const unexpected = () => { throw new Error("Host/native work before capability admission") } + let admissions = 0 + const workspace = {}, manager = { get: () => workspace, getServiceLocation: () => ({ directory: "/repo" }), + requireWorkspaceCapability: () => { admissions++; throw denied }, getSharedServiceConnection: unexpected, + getServiceWslDistro: unexpected, getWorktreeIdentityForPath: unexpected, ownsLocation: unexpected } + const deps = { workspaceManager: manager, settings: { getProfileScope: unexpected, configYamlPathForAuthority: unexpected } } as never + t.after(() => app.close()) + registerMissionScheduled(app, deps) + registerMissionScheduleList(app, deps) + registerMissionScheduleActivation(app, deps) + for (const request of [ + { method: "GET", url: "/api/workspaces/explicit/missions/scheduled" }, + { method: "GET", url: "/api/workspaces/explicit/missions/scheduled/capabilities" }, + { method: "GET", url: "/api/workspaces/explicit/missions/scheduled/requests/create_request" }, + { method: "GET", url: "/api/workspaces/explicit/missions/msn_same/schedule?requestID=original_request" }, + { method: "POST", url: "/api/workspaces/explicit/missions/msn_same/schedule", payload: { requestID: "original_request", expectedRevision: 1, action: "play", retry: true } }, + { method: "GET", url: "/api/workspaces/explicit/missions/msn_same/schedule-settings?requestID=original_request&expectedDocumentRevision=1" }, + { method: "POST", url: "/api/workspaces/explicit/missions/msn_same/schedule-settings", payload: { requestID: "original_request", expectedDocumentRevision: 1 } }, + ]) { + const response = await app.inject(request as never) + assert.equal(response.statusCode, 403, `${request.url}: ${response.body}`) + assert.equal(response.json().capability, "missions") + } + assert.equal(admissions, 7) +}) + +test("missing or unpublished workspace keeps its early admission 404", async t => { + const app = Fastify() + t.after(() => app.close()) + registerMissionScheduled(app, { workspaceManager: { + requireWorkspaceCapability: () => { throw Object.assign(new Error("Workspace not found"), { statusCode: 404 }) }, + getSharedServiceConnection: () => { assert.fail("Missing workspace must never acquire a connection") }, + } } as never) + for (const method of ["GET", "POST"] as const) { + const response = await app.inject({ method, url: "/api/workspaces/missing/missions/msn_owned/schedule", + ...(method === "POST" ? { payload: { requestID: "original_request", expectedRevision: 0, action: "play" } } : {}) }) + assert.equal(response.statusCode, 404, response.body) + } +}) const control = { requestID: "original_request", expectedRevision: 0, action: "play" as const } const config = { title: "Review", objective: "Review bounded sources", template: "custom", taskMode: "native", watchedConversationIDs: [], @@ -56,6 +101,7 @@ async function fixture(t: test.TestContext) { const original = connection() let selected = original const manager = { get: () => state.workspace, getServiceLocation: () => ({ directory: root }), getSharedServiceConnection: async () => selected, + requireWorkspaceCapability: () => new AbortController().signal, ownsLocation: async (_id: string, location: { directory: string }) => state.owned && location.directory === root, getServiceDirectoryForPath: async (_id: string, directory: string) => directory === root ? root : undefined, getWorktreeIdentityForPath: async () => state.checkout, getServiceWslDistro: () => undefined, diff --git a/packages/server/src/server/routes/mission-scheduled.ts b/packages/server/src/server/routes/mission-scheduled.ts index 905d4c729a..c44fc4dfd6 100644 --- a/packages/server/src/server/routes/mission-scheduled.ts +++ b/packages/server/src/server/routes/mission-scheduled.ts @@ -11,6 +11,7 @@ import { recurrenceControlRequestDigest, signNativeRecurrenceControl } from "../ import { resolveStandingProfileSource } from "../../missions/host-authority/profile-source" import { locationRequestOptions, sameLocation } from "../../opencode/compatibility/location" import { requestAdmission } from "../request-admission" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" import { prepareMissionMapMutation, MissionMapMutationError } from "./mission-map-mutation" import { recurrenceHumanSession } from "./mission-recurrence-proof" import { readRecurrenceHoldOwner } from "./mission-recurrence-holds" @@ -59,6 +60,7 @@ export function registerMissionScheduled(app: FastifyInstance, deps: Deps) { const pending = (result: object = {}) => reply.code(503).send({ ...result, missionID, pending: true, error: "Mission schedule action remains unconfirmed", code: "schedule-pending" }) try { + deps.workspaceManager.requireWorkspaceCapability(selected.data.id, "missions") if (method === "POST" && (!human || !auth || !deps.bridgeToken || !deps.settings?.configYamlPathForAuthority)) return reply.code(401).send({ error: "Human authentication required", code: "schedule-human-required" }) const settings = deps.settings, manager = deps.workspaceManager, scope = settings?.getProfileScope() @@ -212,7 +214,9 @@ export function registerMissionScheduled(app: FastifyInstance, deps: Deps) { return result.pending ? pending(result) : result }) } catch (error) { - const status = error instanceof MissionMapMutationError || error instanceof ScheduledHoldError ? error.status : 503 + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + const status = error instanceof MissionMapMutationError || error instanceof ScheduledHoldError ? error.status + : error instanceof Error && "statusCode" in error && error.statusCode === 404 ? 404 : 503 return reply.code(status).send({ missionID, pending: true, error: "Mission schedule action remains unconfirmed", code: "schedule-unconfirmed" }) } finally { if (ownsHold) held?.dispose(); lifetime.dispose() } }, diff --git a/packages/server/src/server/routes/mission-task-native.ts b/packages/server/src/server/routes/mission-task-native.ts index 40352826e8..0438a312ae 100644 --- a/packages/server/src/server/routes/mission-task-native.ts +++ b/packages/server/src/server/routes/mission-task-native.ts @@ -1,4 +1,5 @@ import { z } from "zod" +import { localMissionWorkspaces } from "../../missions/workspace-capability" import type { OpenCodeClient, SessionInfo } from "@opencode/client" import { CODENOMAD_MISSIONS_RPC } from "../../missions/rpc" import type { MissionMap, MissionSnapshot, MissionTask } from "../../missions/model" @@ -39,7 +40,7 @@ export interface MissionTaskInterruption { async function ownedTask(manager: Manager, coordinatorID: string, command: unknown, kind: "task-sessions" | "interrupt", signal: AbortSignal) { const { input } = taskCommand(kind).parse(command) - const owner = await Promise.any(manager.list().map(async workspace => { + const owner = await Promise.any(localMissionWorkspaces(manager).map(async workspace => { const connection = await manager.getSharedServiceConnection(workspace.id) if (!connection) throw new Error("Workspace unavailable") const coordinator = await connection.client.session.get({ sessionID: coordinatorID }, { signal }) diff --git a/packages/server/src/server/routes/missions-display.test.ts b/packages/server/src/server/routes/missions-display.test.ts index b14e81f1de..1d5546771e 100644 --- a/packages/server/src/server/routes/missions-display.test.ts +++ b/packages/server/src/server/routes/missions-display.test.ts @@ -40,6 +40,7 @@ async function fixture(kind: "valid" | "no-fence" | "delete-aba" | "connection" registerMissionRoutes(app, { workspaceManager: { get: () => workspace, getServiceLocation: () => location, + requireWorkspaceCapability: () => new AbortController().signal, getSharedServiceConnection: async () => ({ client, assertCurrent() { if (!connected) throw new Error("replaced") } }), ownsLocation: async () => true, getWorktreeIdentityForPath: async (_id: string, directory: string) => directory, diff --git a/packages/server/src/server/routes/missions.test.ts b/packages/server/src/server/routes/missions.test.ts index f9ec84bd0d..1e1a927fd1 100644 --- a/packages/server/src/server/routes/missions.test.ts +++ b/packages/server/src/server/routes/missions.test.ts @@ -41,6 +41,7 @@ function manager(options: { let fakeClient: unknown const value = { get: (id: string) => options.workspace === false || id !== "workspace-1" ? undefined : workspace, + requireWorkspaceCapability: () => new AbortController().signal, getSharedServiceConnection: async () => ({ client: await value.getSharedServiceClient(), assertCurrent() {} }), getServiceLocation: (id: string) => id === "workspace-1" ? { directory: options.directory ?? "/owned/repo" } : undefined, ownsLocation: async () => true, @@ -204,6 +205,7 @@ function mutationManager(options: { owns?: boolean; error?: unknown; dropProfile }, getServiceDirectoryForPath: async (_id: string, directory: string) => directory, getWorktreeIdentityForPath: async (_id: string, directory: string) => directory, + requireWorkspaceCapability: () => new AbortController().signal, getSharedServiceConnection: async () => options.noConnection ? undefined : ({ client: await value.getSharedServiceClient(), assertCurrent() {} }), getSharedServiceClient: async () => ({ location: { get: async ({ location }: { location: { directory: string } }) => { @@ -353,6 +355,7 @@ test("damage written outside the index generation refuses admission while the di } const app = Fastify({ logger: false }) registerMissionRoutes(app, { workspaceManager: { get: () => ({ id: "workspace-1" }), getServiceLocation: () => ({ directory: "/repo" }), + requireWorkspaceCapability: () => new AbortController().signal, getSharedServiceConnection: async () => ({ client, assertCurrent() {} }) } as never }) try { const display = (await app.inject({ method: "GET", url: `/api/workspaces/workspace-1/missions/${mission.id}` })).json() diff --git a/packages/server/src/server/routes/missions.ts b/packages/server/src/server/routes/missions.ts index d81f91563e..6d64eb6a0c 100644 --- a/packages/server/src/server/routes/missions.ts +++ b/packages/server/src/server/routes/missions.ts @@ -1,5 +1,6 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify" import { z } from "zod" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" import type { OpenCodeClient } from "@opencode/client" import type { MissionActivityProjection, MissionList, MissionListResponse, MissionListUnavailableResponse, MissionMap, MissionPanelMap, @@ -38,7 +39,7 @@ import type { NativeScheduleCapabilityReader } from "../../opencode/native-sched interface MissionRouteDeps { scheduleCapability?: Pick scheduleSettingsActivation?: Pick - workspaceManager: Pick & Partial> @@ -210,6 +211,7 @@ export function registerMissionRoutes(app: FastifyInstance, deps: MissionRouteDe workspaceID: request.params.id, request: request.body, signal: lifetime.signal, wait: lifetime.wait }) return await creation.execute() } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) // Hold codes keep their own meaning: a creation-uncertain retry may follow // an earlier dispatched attempt with the same request identity. if (error instanceof MissionCreationHoldError) { @@ -289,7 +291,7 @@ interface MissionPluginRead { /** The read routes' shared path to the owned Location's active plugin. */ async function readMissionPlugin(request: FastifyRequest<{ Params: { id: string } }>, reply: FastifyReply, deps: MissionRouteDeps, - read: (plugin: MissionPluginRead) => Promise): Promise { + read: (plugin: MissionPluginRead) => Promise): Promise { const lifetime = requestAdmission(request, reply) const parsed = MissionParamsSchema.safeParse(request.params) if (!parsed.success || !deps.workspaceManager.get(parsed.data.id)) { @@ -298,6 +300,12 @@ async function readMissionPlugin(request: FastifyRequest<{ Params: { id: stri return unavailable("workspace-unavailable") } const workspaceID = parsed.data.id + try { deps.workspaceManager.requireWorkspaceCapability(workspaceID, "missions") } + catch (error) { + lifetime.dispose() + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + throw error + } const ownedLocation = deps.workspaceManager.getServiceLocation(workspaceID) if (!ownedLocation) { lifetime.dispose(); return unavailable("workspace-unavailable") } // Without its bridge this backend never provisions the plugin: reconnecting or @@ -361,6 +369,7 @@ async function mutate(request: FastifyRequest, reply: FastifyReply, deps: Missio return await prepared.run(call) } catch (error) { if (error instanceof MissionMapMutationError) return reply.code(error.status).send({ error: error.message }) + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) return mutationError(reply, error) } finally { lifetime.dispose() } } diff --git a/packages/server/src/server/routes/opencode-folders.ts b/packages/server/src/server/routes/opencode-folders.ts new file mode 100644 index 0000000000..3b000534e4 --- /dev/null +++ b/packages/server/src/server/routes/opencode-folders.ts @@ -0,0 +1,34 @@ +// prototype-1236: "Browse" on an explicit OpenCode server lists its folders through the server's +// single shared connection. Like opening a server project, it is available to paired devices. +import type { FastifyInstance } from "fastify" +import { z } from "zod" +import type { OpenCodeServerConnections } from "../../opencode/servers/connections" +import { ServerConnectionError } from "../../opencode/servers/connections" +import { listServerFolders, parseServerFolderPath, ServerFolderPathError } from "../../opencode/servers/folders" +import { LOCAL_SHARED_SERVER_ID } from "../../opencode/servers/types" +import { requestAdmission } from "../request-admission" + +const QuerySchema = z.object({ serverId: z.string().min(1).max(200), path: z.string().max(4_096).optional() }).strict() + +export function registerOpenCodeFolderRoutes(app: FastifyInstance, deps: { connections(): OpenCodeServerConnections }) { + app.get("/api/opencode-folders", async (request, reply) => { + const parsed = QuerySchema.safeParse(request.query) + if (!parsed.success || parsed.data.serverId === LOCAL_SHARED_SERVER_ID) return reply.code(400).send({ code: "invalid_request" }) + let path: string | undefined + try { path = parseServerFolderPath(parsed.data.path) } catch (error) { + if (error instanceof ServerFolderPathError) return reply.code(400).send({ code: "invalid_path" }) + throw error + } + const observer = requestAdmission(request, reply) + try { + const connection = await deps.connections().connect(parsed.data.serverId) + return await listServerFolders((input, options) => connection.client.file.list(input, options) as never, path, observer.signal) + } catch (error) { + if (observer.signal.aborted || reply.raw.destroyed) { reply.hijack(); return } + if (error instanceof ServerConnectionError) { + return reply.code(error.code === "unknown_server" ? 404 : 503).type("text/plain").send(error.code) + } + return reply.code(502).type("text/plain").send("unreachable") + } finally { observer.dispose() } + }) +} diff --git a/packages/server/src/server/routes/opencode-servers-pairing.test.ts b/packages/server/src/server/routes/opencode-servers-pairing.test.ts new file mode 100644 index 0000000000..30242e7bc4 --- /dev/null +++ b/packages/server/src/server/routes/opencode-servers-pairing.test.ts @@ -0,0 +1,168 @@ +// prototype-1236: host-only exchange of an `opencode pair` link from the Add server field. +import assert from "node:assert/strict" +import test from "node:test" +import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs" +import { createServer, request as httpRequest, type IncomingHttpHeaders } from "node:http" +import { once } from "node:events" +import { join } from "node:path" +import pino from "pino" +import { startRemoteSurface, FAKE_TUNNEL_HOST } from "../../remote-control/test-support/surface" +import { SettingsService } from "../../settings/service" +import { resolveConfigLocation } from "../../config/location" +import { explicitContractFixture } from "../../opencode/compatibility/contract-fixture" + +const TOKEN = "4102444800000.syntheticPairedTokenHmac" + +function send(target: string, path: string, method: string, headers: Record, payload?: unknown) { + return new Promise<{ status: number; headers: IncomingHttpHeaders; body: string }>((resolve, reject) => { + const request = httpRequest(`http://${target}${path}`, { method, headers: { ...(payload === undefined ? {} : { "content-type": "application/json" }), ...headers } }, response => { + let body = "" + response.setEncoding("utf8").on("data", chunk => { body += chunk }).on("end", () => resolve({ status: response.statusCode!, headers: response.headers, body })) + }) + request.on("error", reject); request.end(payload === undefined ? undefined : JSON.stringify(payload)) + }) +} + +async function fixture(t: test.TestContext) { + const root = mkdtempSync(join(process.cwd(), ".tmp-pair-")), logs: string[] = [], calls: string[] = [] + const logger = pino({ level: "trace" }, { write: text => logs.push(text) }) + const configPath = join(root, "config.yaml") + const settings = new SettingsService(resolveConfigLocation(configPath), undefined, logger) + const owner = settings.getOpenCodeServerConnections({ acquire: async () => assert.fail("local must stay untouched"), existing: () => undefined, invalidate: () => {} }) + const codes = new Set(["fresh-code", "second-code"]) + const state = { redirect: false, rejectToken: false, accepts: [] as string[] } + const upstream = createServer((request, response) => { + calls.push(`${request.method} ${request.url}`) + const connect = /^\/auth\/connect\/([^/]+)$/.exec(request.url ?? "") + if (connect) { + state.accepts.push(String(request.headers.accept)) + if (state.redirect) { response.writeHead(302, { location: "/" }); response.end(); return } + const valid = codes.delete(connect[1]!) + response.writeHead(valid ? 200 : 401, { "content-type": "application/json" }) + response.end(JSON.stringify(valid ? { token: TOKEN } : { name: "UnauthorizedError" })) + return + } + const expected = `Basic ${Buffer.from(`opencode:${TOKEN}`).toString("base64")}` + if (state.rejectToken || request.headers.authorization !== expected) { response.writeHead(401); response.end(); return } + response.setHeader("content-type", "application/json") + response.end(JSON.stringify(request.url === "/openapi.json" ? explicitContractFixture() : { version: "99.0.0" })) + }) + upstream.listen(0, "127.0.0.1"); await once(upstream, "listening") + const origin = `http://127.0.0.1:${(upstream.address() as { port: number }).port}` + const surface = await startRemoteSurface(t, { settings, logger, workspaceManager: { getServerConnections: () => owner } }) + const session = surface.authManager.createSession("codenomad") + const cookie = `${surface.authManager.getCookieName()}=${session.id}` + const add = (address: string, extra: Record = {}) => send(surface.local, "/api/opencode-servers/add", "POST", { cookie, ...extra }, { name: "Box", address }) + t.after(async () => { await owner.dispose(); upstream.closeAllConnections(); await new Promise(resolve => upstream.close(() => resolve())); rmSync(root, { recursive: true, force: true }) }) + return { ...surface, root, configPath, settings, owner, origin, calls, logs, cookie, state, add, pairings: join(root, "opencode-server-pairings.json") } +} + +test("a pasted pairing link is exchanged once and its token stays on the backend across launches", async t => { + const f = await fixture(t) + const added = await f.add(`${f.origin}/auth/connect/fresh-code`) + assert.equal(added.status, 200, added.body) + const profile = JSON.parse(added.body) + assert.deepEqual(Object.keys(profile).sort(), ["id", "label", "origin"]) + assert.equal(profile.origin, f.origin); assert.equal(profile.label, "Box") + assert.deepEqual(f.calls, ["GET /auth/connect/fresh-code"]) + assert.deepEqual(f.state.accepts, ["application/json"]) + assert.doesNotMatch(added.body, /syntheticPairedToken|fresh-code/) + // Metadata only in the config; the token lives in the backend-private pairing file. + assert.doesNotMatch(readFileSync(f.configPath, "utf8"), /syntheticPairedToken|fresh-code/) + assert.match(readFileSync(f.pairings, "utf8"), /syntheticPairedToken/) + const list = await send(f.local, "/api/opencode-servers", "GET", { cookie: f.cookie }) + assert.equal(JSON.parse(list.body).servers[1].hasCredentials, true) + assert.doesNotMatch(list.body, /syntheticPairedToken/) + // The token authenticates the API as Basic opencode:. + await f.owner.connect(profile.id) + assert.ok(f.calls.includes("GET /openapi.json")) + // A relaunch reads it again without a new link. + const restarted = new SettingsService(resolveConfigLocation(f.configPath), undefined, pino({ level: "silent" })) + assert.equal(await restarted.getOpenCodeServerCredentials().readForConnection(profile.id), JSON.stringify({ username: "opencode", password: TOKEN })) + await restarted.disposeOpenCodeServers() + assert.doesNotMatch(f.logs.join("\n"), /syntheticPairedToken|fresh-code/) +}) + +test("a spent or expired code is refused without adding a server", async t => { + const f = await fixture(t) + assert.equal((await f.add(`${f.origin}/auth/connect/fresh-code`)).status, 200) + const spent = await f.add(`${f.origin}/auth/connect/fresh-code`, {}) + assert.equal(spent.status, 400); assert.equal(JSON.parse(spent.body).code, "pairing_expired") + const unknown = await send(f.local, "/api/opencode-servers/add", "POST", { cookie: f.cookie }, { address: `${f.origin}/auth/connect/never-issued` }) + assert.equal(JSON.parse(unknown.body).code, "pairing_expired") + assert.equal(f.settings.getOpenCodeServerRegistry().list().filter(profile => profile.kind === "explicit").length, 1) +}) + +test("http outside loopback, query or fragment links are refused before any request", async t => { + const f = await fixture(t) + for (const [link, code] of [["http://192.168.1.10:4096/auth/connect/abc", "https_required"], ["http://example.test/auth/connect/abc", "https_required"], + [`${f.origin}/auth/connect/abc?x=1`, "invalid_link"], [`${f.origin}/auth/connect/abc#x`, "invalid_link"]] as const) { + const response = await f.add(link) + assert.equal(response.status, 400, link); assert.equal(JSON.parse(response.body).code, code, link) + } + assert.deepEqual(f.calls, []); assert.equal(existsSync(f.pairings), false) +}) + +test("a redirect is never followed", async t => { + const f = await fixture(t) + f.state.redirect = true + const response = await f.add(`${f.origin}/auth/connect/fresh-code`) + assert.equal(response.status, 502); assert.equal(JSON.parse(response.body).code, "unreachable") + assert.deepEqual(f.calls, ["GET /auth/connect/fresh-code"]) + assert.equal(response.headers.location, undefined) +}) + +test("a paired Remote Control device can neither exchange a link nor read the token", async t => { + const f = await fixture(t) + assert.equal((await f.add(`${f.origin}/auth/connect/fresh-code`)).status, 200) + const pair = await send(f.target(), "/api/remote-control/pair", "POST", { host: FAKE_TUNNEL_HOST, origin: `https://${FAKE_TUNNEL_HOST}` }, { code: f.code }) + assert.equal(pair.status, 200, pair.body) + const cookie = pair.headers["set-cookie"]![0]!.split(";")[0]!, headers = { host: FAKE_TUNNEL_HOST, cookie, origin: `https://${FAKE_TUNNEL_HOST}` } + const exchange = await send(f.target(), "/api/opencode-servers/add", "POST", headers, { address: `${f.origin}/auth/connect/second-code` }) + assert.equal(exchange.status, 404) + assert.deepEqual(f.calls, ["GET /auth/connect/fresh-code"]) + const config = await send(f.target(), "/api/storage/config", "GET", headers) + assert.equal(config.status, 200, config.body) + assert.match(config.body, new RegExp(f.origin.replace(/[.:/]/g, "\\$&"))) + assert.doesNotMatch(config.body, /syntheticPairedToken/) +}) + +test("a 401 after pairing leaves the server waiting for a new link", async t => { + const f = await fixture(t) + const { id } = JSON.parse((await f.add(`${f.origin}/auth/connect/fresh-code`)).body) + f.state.rejectToken = true + await assert.rejects(f.owner.connect(id), { code: "auth" }) + await new Promise(resolve => setImmediate(resolve)) + assert.equal(f.settings.getOpenCodeServerCredentials().hasCredentials(id), false) + assert.doesNotMatch(readFileSync(f.pairings, "utf8"), /syntheticPairedToken/) + f.state.rejectToken = false + assert.equal((await f.add(`${f.origin}/auth/connect/second-code`)).status, 200) + assert.equal(f.settings.getOpenCodeServerCredentials().hasCredentials(id), true) +}) + +// prototype-1236 (R17): an address with a password stays connected across launches, like a paired link. +test("a manual password is kept in the private backend file across launches, then forgotten on removal", async t => { + const f = await fixture(t) + const address = f.origin.replace("http://", `http://opencode:${encodeURIComponent(TOKEN)}@`) + const added = await f.add(address) + assert.equal(added.status, 200, added.body) + const { id } = JSON.parse(added.body) + assert.doesNotMatch(added.body, /syntheticPairedToken/) + assert.doesNotMatch(readFileSync(f.configPath, "utf8"), /syntheticPairedToken/) + assert.match(readFileSync(f.pairings, "utf8"), /syntheticPairedToken/) + const restarted = new SettingsService(resolveConfigLocation(f.configPath), undefined, pino({ level: "silent" })) + assert.equal(await restarted.getOpenCodeServerCredentials().readForConnection(id), JSON.stringify({ username: "opencode", password: TOKEN })) + await restarted.disposeOpenCodeServers() + assert.equal((await send(f.local, `/api/opencode-servers/${id}`, "DELETE", { cookie: f.cookie })).status, 204) + assert.doesNotMatch(readFileSync(f.pairings, "utf8"), /syntheticPairedToken/) + assert.doesNotMatch(f.logs.join("\n"), /syntheticPairedToken/) +}) + +test("removing a server forgets its token and profile", async t => { + const f = await fixture(t) + const { id } = JSON.parse((await f.add(`${f.origin}/auth/connect/fresh-code`)).body) + const removed = await send(f.local, `/api/opencode-servers/${id}`, "DELETE", { cookie: f.cookie }) + assert.equal(removed.status, 204, removed.body) + assert.equal(f.settings.getOpenCodeServerRegistry().get(id), undefined) + assert.doesNotMatch(readFileSync(f.pairings, "utf8"), /syntheticPairedToken/) +}) diff --git a/packages/server/src/server/routes/opencode-servers.test.ts b/packages/server/src/server/routes/opencode-servers.test.ts new file mode 100644 index 0000000000..fd17ce3eea --- /dev/null +++ b/packages/server/src/server/routes/opencode-servers.test.ts @@ -0,0 +1,339 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { mkdtempSync, rmSync, readFileSync, writeFileSync } from "node:fs" +import { createServer, request as httpRequest, type IncomingHttpHeaders } from "node:http" +import { once } from "node:events" +import { join } from "node:path" +import pino from "pino" +import dns from "node:dns/promises" +import { syncBuiltinESMExports } from "node:module" +import { setTimeout as delay } from "node:timers/promises" +import { startRemoteSurface, FAKE_TUNNEL_HOST } from "../../remote-control/test-support/surface" +import { SettingsService } from "../../settings/service" +import { resolveConfigLocation } from "../../config/location" +import { explicitContractFixture } from "../../opencode/compatibility/contract-fixture" +import { isOpenCodeServerAdminTarget } from "./opencode-servers" +import Fastify from "fastify" + +function send(target: string, path: string, method: string, headers: Record, payload: unknown) { + return new Promise<{ status: number; headers: IncomingHttpHeaders; body: string }>((resolve, reject) => { + const request = httpRequest(`http://${target}${path}`, { method, headers: { "content-type": "application/json", ...headers } }, response => { + let body = "" + response.setEncoding("utf8").on("data", chunk => { body += chunk }).on("end", () => resolve({ status: response.statusCode!, headers: response.headers, body })) + }) + request.on("error", reject); request.end(JSON.stringify(payload)) + }) +} + +async function fixture(t: test.TestContext, skipAuth = false) { + const root = mkdtempSync(join(process.cwd(), ".tmp-admin-")), logs: string[] = [], calls: string[] = [] + const logger = pino({ level: "trace" }, { write: text => logs.push(text) }) + const settings = new SettingsService(resolveConfigLocation(join(root, "config.yaml")), undefined, logger) + const local = { acquire: async () => { assert.fail("GET must not acquire local") }, existing: () => undefined, + invalidate: () => { assert.fail("admin must not invalidate local") } } + const owner = settings.getOpenCodeServerConnections(local) + const upstream = createServer((request, response) => { + calls.push(`${request.method} ${request.url}`) + response.setHeader("content-type", "application/json") + response.end(JSON.stringify(request.url === "/openapi.json" ? explicitContractFixture() : { version: "99.0.0", pid: 999, urls: [], paths: { tmp: "private" } })) + }) + upstream.listen(0, "127.0.0.1"); await once(upstream, "listening") + const origin = `http://127.0.0.1:${(upstream.address() as { port: number }).port}` + settings.getOpenCodeServerRegistry().replace([{ id: "saved", kind: "explicit", label: "Saved", origin }]) + await settings.getOpenCodeServerCredentials().set("saved", JSON.stringify({ username: "saved-user", password: "saved-password" })) + const surface = await startRemoteSurface(t, { skipAuth, settings, logger, workspaceManager: { getServerConnections: () => owner } }) + const session = surface.authManager.createSession("codenomad") + const cookie = `${surface.authManager.getCookieName()}=${session.id}` + t.after(async () => { await owner.dispose(); upstream.closeAllConnections(); await new Promise(resolve => upstream.close(() => resolve())); rmSync(root, { recursive: true, force: true }) }) + return { ...surface, root, settings, owner, origin, calls, logs, cookie } +} + +for (const skipAuth of [false, true]) test(`host guard and real CSRF admission with auth ${skipAuth ? "disabled" : "enabled"}`, async t => { + const f = await fixture(t, skipAuth) + const headers = { cookie: f.cookie, host: f.local } + const payload = { origin: f.origin, credentials: { username: "ephemeral-user", password: "ephemeral-password" } } + for (const path of ["/api/opencode-servers", "/%61pi/opencode-servers", "/api/%6fpencode-servers"]) { + for (const extra of [ + { origin: "https://foreign.test" }, { origin: "null" }, { origin: `http://${f.local}/` }, + { origin: "http://[invalid" }, { host: "rebound.attacker.test" }, + { "sec-fetch-site": "cross-site" }, { "sec-fetch-site": "same-site" }, { "sec-fetch-site": "invalid" }, + ]) { + const result = await f.app.inject({ method: "POST", url: `${path}/probe`, headers: { ...headers, ...extra }, payload, remoteAddress: "127.0.0.1" }) + assert.equal(result.statusCode, 403, JSON.stringify(extra)); assert.equal(result.headers["cache-control"], "no-store") + } + assert.equal((await f.app.inject({ method: "POST", url: `${path}/probe`, headers, payload, remoteAddress: "192.168.1.7" })).statusCode, 403) + } + assert.equal(f.calls.length, 0) + const unauthenticated = await f.app.inject({ method: "GET", url: "/api/opencode-servers", headers: { host: f.local }, remoteAddress: "127.0.0.1" }) + assert.equal(unauthenticated.statusCode, skipAuth ? 200 : 401) + for (const origin of [undefined, `http://${f.local}`, "http://localhost:3000"]) { + const result = await f.app.inject({ method: "POST", url: "/api/opencode-servers/probe", headers: { ...headers, ...(origin ? { origin } : {}) }, payload, remoteAddress: "127.0.0.1" }) + assert.equal(result.statusCode, 200, result.body) + assert.equal(result.json().version, "99.0.0") + assert.equal(result.headers["www-authenticate"], undefined) + assert.doesNotMatch(result.body, /ephemeral-|private|pid|urls/) + } + const actual = await send(f.local, "/api/opencode-servers/probe", "POST", { cookie: f.cookie }, payload) + assert.equal(actual.status, 200, actual.body) + assert.equal(JSON.parse(actual.body).version, "99.0.0") + for (const origin of [`http://localhost:${f.local.split(":")[1]}`, `http://${f.local}`]) { + assert.equal((await f.app.inject({ url: "/api/opencode-servers", headers: { ...headers, origin, "sec-fetch-site": "same-origin" }, remoteAddress: "127.0.0.1" })).statusCode, 200) + } + assert.equal((await f.app.inject({ url: "/api/test/echo", headers, remoteAddress: "127.0.0.1" })).statusCode, 200) +}) + +test("administrative GET projects live credential and connection owners with zero native work", async t => { + const f = await fixture(t), headers = { cookie: f.cookie, host: f.local } + const disk = readFileSync(join(f.root, "config.yaml"), "utf8") + f.settings.getOpenCodeServerCredentials().readForConnection = async () => { assert.fail("GET must not read secrets") } + const get = () => f.app.inject({ method: "GET", url: "/api/opencode-servers", headers, remoteAddress: "127.0.0.1" }) + let result = await get() + assert.equal(result.statusCode, 200, result.body) + assert.equal(result.json().servers[0].id, "local-shared") + assert.deepEqual(result.json().servers[1], { kind: "explicit", id: "saved", label: "Saved", origin: f.origin, hasCredentials: true, needsCredentials: false, state: "unknown" }) + assert.deepEqual(result.json().limits, { explicitActiveTargets: 4, reservedLocalTargets: 1, activeExplicitTargets: 0 }) + await f.settings.getOpenCodeServerCredentials().clear("saved") + result = await get(); assert.equal(result.json().servers[1].hasCredentials, false) + f.owner.disconnect("saved") + result = await get(); assert.equal(result.json().servers[1].state, "disconnected") + assert.equal(f.calls.length, 0); assert.equal(readFileSync(join(f.root, "config.yaml"), "utf8"), disk) + assert.doesNotMatch(result.body, /saved-user|saved-password|private|pid|binary/) + for (const [url, payload] of [["/api/storage/config", { server: { opencodeServers: [] } }], ["/api/storage/config/server", { opencodeServers: [] }]] as const) { + const response = await f.app.inject({ method: "PATCH", url, headers, payload, remoteAddress: "127.0.0.1" }) + assert.equal(response.statusCode, 400) + } + assert.equal(readFileSync(join(f.root, "config.yaml"), "utf8"), disk) +}) + +test("paired ingress cannot administer even with valid Origin and encoded route; generic PATCH stays closed", async t => { + const f = await fixture(t) + const pair = await send(f.target(), "/api/remote-control/pair", "POST", { host: FAKE_TUNNEL_HOST, origin: `https://${FAKE_TUNNEL_HOST}` }, { code: f.code }) + assert.equal(pair.status, 200, pair.body) + const cookie = pair.headers["set-cookie"]![0]!.split(";")[0]! + for (const path of ["/api/opencode-servers", "/%61pi/opencode-servers", "/api/%6fpencode-servers", "/api/opencode-servers/probe"]) { + const response = await send(f.target(), path, "POST", { host: FAKE_TUNNEL_HOST, cookie, origin: `https://${FAKE_TUNNEL_HOST}` }, { origin: f.origin }) + assert.equal(response.status, 404, path) + } + for (const [url, payload] of [["/api/storage/config", { server: { opencodeServers: [] } }], ["/api/storage/config/server", { opencodeServers: [] }]] as const) { + const response = await send(f.target(), url, "PATCH", { host: FAKE_TUNNEL_HOST, cookie, origin: `https://${FAKE_TUNNEL_HOST}` }, payload) + assert.equal(response.status, 400) + } + assert.equal(f.calls.length, 0) +}) + +test("admin URL/body/header/parser/error diagnostics are redacted completely, including invalid encoded paths", async t => { + const f = await fixture(t), sentinel = "sensitiveSentinel83" + const headers = { host: f.local, cookie: f.cookie, authorization: sentinel, username: sentinel } + for (const url of [`/api/opencode-servers/probe?${sentinel}=${sentinel}`, `/api/opencode-servers/${sentinel}`, `/%61pi/opencode-servers/%E0%A4%A?${sentinel}`]) { + const response = await f.app.inject({ method: "POST", url, headers, payload: { origin: `https://${sentinel}:${sentinel}@invalid.test`, username: sentinel, password: sentinel }, remoteAddress: "127.0.0.1" }) + assert.doesNotMatch(response.body, new RegExp(sentinel)); assert.equal(response.headers["cache-control"], "no-store") + } + const parser = await f.app.inject({ method: "POST", url: "/api/opencode-servers/probe", headers: { ...headers, "content-type": "application/json" }, payload: `{"${sentinel}":`, remoteAddress: "127.0.0.1" }) + assert.equal(parser.statusCode, 400); assert.doesNotMatch(parser.body, new RegExp(sentinel)) + assert.doesNotMatch(f.logs.join("\n"), new RegExp(sentinel)) + assert.equal(f.calls.length, 0) +}) + +test("every failed administrative boundary precedes DNS, registry writes and secret access", async t => { + const f = await fixture(t) + let resolutions = 0 + const mocked = t.mock.method(dns, "lookup", async () => { resolutions++; throw new Error("unexpected fixture DNS") }) + syncBuiltinESMExports() + t.after(() => { mocked.mock.restore(); syncBuiltinESMExports() }) + f.settings.getOpenCodeServerCredentials().readForConnection = async () => { assert.fail("candidate must not read stored credentials") } + f.settings.getOpenCodeServerCredentials().set = async () => { assert.fail("candidate must not store credentials") } + const before = readFileSync(join(f.root, "config.yaml"), "utf8") + for (const headers of [ + { host: f.local }, { host: "rebound.attacker.invalid", cookie: f.cookie, origin: "https://rebound.attacker.invalid" }, + { host: f.local, cookie: f.cookie, origin: "https://foreign.invalid" }, + ]) { + assert.ok((await f.app.inject({ method: "POST", url: "/api/opencode-servers/probe", headers, payload: { origin: "https://must-not-resolve.invalid" }, remoteAddress: "127.0.0.1" })).statusCode >= 400) + } + for (const origin of ["https://sentinel:sentinel@private.invalid", "https://private.invalid/path", "https://private.invalid?", "https://private.invalid#", "malformed"]) { + const result = await f.app.inject({ method: "POST", url: "/api/opencode-servers/probe", headers: { host: f.local, cookie: f.cookie }, payload: { origin }, remoteAddress: "127.0.0.1" }) + assert.equal(result.statusCode, 400) + } + assert.equal(resolutions, 0); assert.equal(f.calls.length, 0) + assert.equal(readFileSync(join(f.root, "config.yaml"), "utf8"), before) +}) + +test("GET distinguishes connecting, admitted, offline-retained and disconnected owners without another native read", async t => { + const f = await fixture(t), credentials = f.settings.getOpenCodeServerCredentials() + let release!: () => void + const held = new Promise(resolve => { release = resolve }) + const original = credentials.readForConnection.bind(credentials) + credentials.readForConnection = async id => { await held; return original(id) } + const pending = f.owner.connect("saved") + const get = () => f.app.inject({ url: "/api/opencode-servers", headers: { host: f.local, cookie: f.cookie }, remoteAddress: "127.0.0.1" }) + assert.equal((await get()).json().servers[1].state, "connecting") + assert.equal(f.calls.length, 0) + release(); await pending + const count = f.calls.length + assert.equal((await get()).json().servers[1].state, "connected") + f.owner.invalidateServer("saved") + const offline = (await get()).json() + assert.equal(offline.servers[1].state, "admitted_offline") + assert.equal(offline.limits.activeExplicitTargets, 1) + assert.equal(f.calls.length, count) + f.owner.disconnect("saved") + assert.equal((await get()).json().servers[1].state, "disconnected") + assert.equal(f.calls.length, count) +}) + +test("closing the real HTTP observer cancels a stalled probe and releases its lane", async t => { + const f = await fixture(t) + let abandonedDispatches = 0 + const upstream = createServer((request, response) => { + abandonedDispatches++; assert.equal(request.method, "GET"); assert.equal(request.url, "/openapi.json") + response.writeHead(200); response.write("{") + }) + upstream.listen(0, "127.0.0.1"); await once(upstream, "listening") + t.after(async () => { upstream.closeAllConnections(); await new Promise(resolve => upstream.close(() => resolve())) }) + const origin = `http://127.0.0.1:${(upstream.address() as { port: number }).port}` + const arrived = once(upstream, "request") + const request = httpRequest(`http://${f.local}/api/opencode-servers/probe`, { method: "POST", headers: { cookie: f.cookie, "content-type": "application/json" } }) + const clientErrors: string[] = [], upstreamErrors: string[] = [] + request.on("error", error => clientErrors.push((error as NodeJS.ErrnoException).code ?? "unknown")) + f.settings.getOpenCodeServerCredentials().readForConnection = async () => { assert.fail("probe must not read saved secrets") } + f.settings.getOpenCodeServerCredentials().set = async () => { assert.fail("probe must not write saved secrets") } + request.end(JSON.stringify({ origin, credentials: { username: "closed-user", password: "closed-password" } })) + const [nativeRequest] = await arrived + const closed = new Promise((resolve, reject) => { + const error = (value: NodeJS.ErrnoException) => { + upstreamErrors.push(value.code ?? "unknown") + if (value.code !== "ECONNRESET") reject(value) + } + nativeRequest.socket.on("error", error) + nativeRequest.socket.once("close", () => { nativeRequest.socket.off("error", error); resolve() }) + }) + request.destroy(); await closed + await delay(10) + const replacement = await send(f.local, "/api/opencode-servers/probe", "POST", { cookie: f.cookie }, { origin: f.origin }) + assert.equal(replacement.status, 200, replacement.body) + assert.equal(JSON.parse(replacement.body).version, "99.0.0") + assert.equal(abandonedDispatches, 1) + assert.deepEqual(f.calls, ["GET /openapi.json", "GET /api/info"]) + assert.ok(upstreamErrors.every(code => code === "ECONNRESET")) + assert.ok(clientErrors.every(code => code === "ECONNRESET")) + assert.equal(f.owner.activeExplicitTargets, 0) + assert.doesNotMatch(f.logs.join("\n"), /closed-user|closed-password/) +}) + +test("upstream authentication and malformed contract return fixed diagnostics instead of CodeNomad login or secret echoes", async t => { + const f = await fixture(t) + let auth = true + const server = createServer((_request, response) => { + response.writeHead(auth ? 401 : 200, { "www-authenticate": "Basic realm=upstream-secret", "set-cookie": "upstream-secret", "content-type": "application/json" }) + response.end("ephemeral-password upstream-secret malformed JSON") + }) + server.listen(0, "127.0.0.1"); await once(server, "listening") + t.after(async () => { server.closeAllConnections(); await new Promise(resolve => server.close(() => resolve())) }) + const origin = `http://127.0.0.1:${(server.address() as { port: number }).port}` + for (const code of ["auth", "missing_contract"]) { + const response = await send(f.local, "/api/opencode-servers/probe", "POST", { cookie: f.cookie }, { origin, credentials: { username: "ephemeral-user", password: "ephemeral-password" } }) + assert.equal(response.status, 200, response.body) + assert.deepEqual(JSON.parse(response.body).diagnostic, { code, phase: "contract" }) + assert.equal(response.headers["www-authenticate"], undefined) + assert.equal(response.headers["set-cookie"], undefined) + assert.equal(response.headers.location, undefined) + assert.doesNotMatch(response.body, /ephemeral-user|ephemeral-password|upstream-secret|malformed JSON/) + auth = false + } + assert.doesNotMatch(f.logs.join("\n"), /ephemeral-user|ephemeral-password|upstream-secret|malformed JSON/) +}) + +test("candidate probe preserves an active connection and credentials; a registered probe owns the same lane", async t => { + const f = await fixture(t), captured = await f.owner.connect("saved") + const admitted: string[][] = [] + f.owner.observeAdmitted(ids => admitted.push([...ids])) + const response = await send(f.local, "/api/opencode-servers/probe", "POST", { cookie: f.cookie }, { origin: f.origin, credentials: { username: "ephemeral-user", password: "ephemeral-password" } }) + assert.equal(response.status, 200, response.body) + assert.equal(JSON.parse(response.body).version, "99.0.0") + assert.equal(f.owner.existingForServer("saved"), captured); captured.assertCurrent() + assert.equal(f.owner.activeExplicitTargets, 1) + assert.deepEqual(admitted, [["saved"]]) + const credentials = f.settings.getOpenCodeServerCredentials() + assert.equal(await credentials.readForConnection("saved"), JSON.stringify({ username: "saved-user", password: "saved-password" })) + let release!: () => void + const held = new Promise(resolve => { release = resolve }), original = credentials.readForConnection.bind(credentials) + credentials.readForConnection = async id => { await held; return original(id) } + const registered = f.owner.probe("saved"), calls = f.calls.length + const busy = await send(f.local, "/api/opencode-servers/probe", "POST", { cookie: f.cookie }, { origin: f.origin }) + assert.equal(busy.status, 409); assert.equal(JSON.parse(busy.body).code, "probe_busy") + assert.equal(f.calls.length, calls) + release(); await registered + assert.equal(f.owner.existingForServer("saved"), captured); captured.assertCurrent() + assert.deepEqual(admitted, [["saved"]]) +}) + +for (const initial of ["connected", "connecting", "admitted_offline"] as const) { + test(`GET purely projects ${initial} reservation against current origin metadata`, async t => { + const f = await fixture(t), credentials = f.settings.getOpenCodeServerCredentials() + let release!: () => void + const held = new Promise(resolve => { release = resolve }), read = credentials.readForConnection.bind(credentials) + if (initial === "connecting") credentials.readForConnection = async id => { await held; return read(id) } + const pending = f.owner.connect("saved"); void pending.catch(() => {}) + t.after(async () => { release(); await pending.catch(() => {}) }) + const captured = initial === "connecting" ? undefined : await pending + if (initial === "admitted_offline") f.owner.invalidateServer("saved") + const get = () => f.app.inject({ url: "/api/opencode-servers", headers: { host: f.local, cookie: f.cookie }, remoteAddress: "127.0.0.1" }) + assert.equal((await get()).json().servers[1].state, initial) + const admissions: string[][] = [] + f.owner.observeAdmitted(ids => admissions.push([...ids])) + assert.equal(f.owner.administrativeState("saved", "http://127.0.0.1:1"), "unknown", "a retained summary from a different origin cannot claim this slot") + const config = join(f.root, "config.yaml"), original = readFileSync(config, "utf8") + const replaced = JSON.stringify({ server: { opencodeServers: [{ kind: "explicit", id: "saved", label: "B", origin: "http://127.0.0.1:1" }] } }) + writeFileSync(config, replaced) + credentials.readForConnection = async () => { assert.fail("GET must not read secrets") } + const count = f.calls.length, signal = (captured as { signal?: AbortSignal } | undefined)?.signal, wasAborted = signal?.aborted + for (let repeat = 0; repeat < 2; repeat++) { + const response = await get() + assert.equal(response.statusCode, 200, response.body) + assert.equal(response.json().servers[1].state, "unknown") + assert.equal(response.json().servers[1].hasCredentials, false) + assert.equal(response.json().limits.activeExplicitTargets, 1) + assert.equal(signal?.aborted, wasAborted) + assert.deepEqual(admissions, [initial === "connecting" ? [] : ["saved"]]) + assert.equal(f.calls.length, count); assert.equal(readFileSync(config, "utf8"), replaced) + } + writeFileSync(config, original) + assert.equal((await get()).json().servers[1].state, initial) + assert.equal(f.owner.activeExplicitTargets, 1) + if (initial === "connected") { + writeFileSync(config, replaced) + await assert.rejects(captured!.fetch(`${f.origin}/api/info`), { code: "stale_connection" }) + assert.equal(signal?.aborted, true); assert.equal(f.owner.activeExplicitTargets, 0) + assert.equal(f.calls.length, count) + } + }) +} + +test("privacy recognizes encoded administrative separators without granting routed authority", async t => { + const f = await fixture(t), user = "encodedSyntheticUser53", password = "encodedSyntheticPass71" + const forbidden = new RegExp(`${user}|${password}`), headers = { cookie: f.cookie, authorization: user, username: password } + const candidate = { origin: f.origin, credentials: { username: user, password } } + const profiles = readFileSync(join(f.root, "config.yaml"), "utf8"), admissions: string[][] = [] + f.owner.observeAdmitted(ids => admissions.push([...ids])) + f.settings.getOpenCodeServerCredentials().readForConnection = async () => { assert.fail("encoded target must not read secrets") } + f.settings.getOpenCodeServerCredentials().set = async () => { assert.fail("encoded target must not write secrets") } + for (const path of ["/api/opencode-servers%2Fprobe", "/api/opencode-servers%2fprobe", "/api%2Fopencode-servers/probe", `/api/opencode-servers%3B${user}`, + `/api/opencode-servers/probe%2F${user}`, "/api%252Fopencode-servers/probe", "/api%25252Fopencode-servers/probe", "/api/opencode-servers%ZZ", "/api/opencode-servers/%FF"]) { + const target = `${path}?${user}=${password}`, start = f.logs.length + const response = await send(f.local, target, "POST", headers, candidate) + assert.ok(response.status === 400 || response.status === 404 || (response.status === 200 && response.headers["content-type"]?.includes("text/html")), response.body) + assert.equal(response.headers["cache-control"], "no-store") + assert.doesNotMatch(response.body, forbidden) + assert.equal(isOpenCodeServerAdminTarget(target), true, target) + assert.doesNotMatch(f.logs.slice(start).join("\n"), forbidden, target) + assert.equal(f.calls.length, 0); assert.equal(f.owner.activeExplicitTargets, 0); assert.deepEqual(admissions, [[]]) + assert.equal(readFileSync(join(f.root, "config.yaml"), "utf8"), profiles) + const positive = await send(f.local, "/api/opencode-servers", "GET", { cookie: f.cookie }, undefined) + assert.equal(positive.status, 200) + } + const ordinary = await f.app.inject({ method: "POST", url: "/api/auth/login", headers: { "content-type": "application/json" }, payload: '{"ordinary":' }) + const native = Fastify({ logger: false }); native.post("/api/auth/login", () => ({ ok: true })) + try { + const expected = await native.inject({ method: "POST", url: "/api/auth/login", headers: { "content-type": "application/json" }, payload: '{"ordinary":' }) + assert.equal(ordinary.statusCode, expected.statusCode); assert.deepEqual(ordinary.json(), expected.json()) + } finally { await native.close() } +}) diff --git a/packages/server/src/server/routes/opencode-servers.ts b/packages/server/src/server/routes/opencode-servers.ts new file mode 100644 index 0000000000..0cf4ebf259 --- /dev/null +++ b/packages/server/src/server/routes/opencode-servers.ts @@ -0,0 +1,175 @@ +import type { FastifyInstance, FastifyRequest } from "fastify" +import type { AuthManager } from "../../auth/manager" +import type { SettingsService } from "../../settings/service" +import type { OpenCodeServerConnections } from "../../opencode/servers/connections" +import { ServerConnectionError } from "../../opencode/servers/connections" +import { initialServerCapabilities } from "../../opencode/servers/capabilities" +import { parseProbeCandidate, ServerProbeError } from "../../opencode/servers/probe" +import { ExplicitEndpointError } from "../../opencode/servers/endpoint" +import { SERVER_CONNECTION_LIMITS } from "../../opencode/servers/types" +import { isLocalRequest } from "../../remote-control/request-origin" +import { requestAdmission } from "../request-admission" +import { routedPath } from "../routed-path" +import { randomUUID } from "node:crypto" +import { z } from "zod" +import { normalizeExplicitOrigin } from "../../opencode/servers/origin" +import { OpenCodePairingError, parseOpenCodePairingLink, redeemOpenCodePairing } from "../../opencode/servers/pairing" + +const prefix = "/api/opencode-servers" +const privacyPrefix = /^\/api\/opencode-servers(?:[^a-z0-9_-]|$)/i + +/** Privacy includes non-routable encoded spellings; authority uses routedPath independently. */ +export function isOpenCodeServerAdminTarget(target: string): boolean { + let path = routedPath(target) + if (path === null) return true + // Bound decoding work; still-encoded deep nesting is conservatively private. + for (let pass = 0; pass < 3; pass++) { + if (privacyPrefix.test(path)) return true + if (!path.includes("%")) return false + try { path = decodeURIComponent(path) } catch { return true } + } + return privacyPrefix.test(path) || path.includes("%") +} + +const errorCodes = new Set(["unauthorized", "host_only", "invalid_request", "metadata_unavailable", "probe_busy", "closed", + // prototype-1236: pairing and removal outcomes. + "invalid_link", "pairing_expired", "unreachable", "https_required", "forbidden_address", "auth", "unknown_server"]) + +/** Install before the remote gate/body parser, so even early refusals are private. */ +export function registerOpenCodeServerAdminPrivacy(app: FastifyInstance) { + app.addHook("onRequest", (request, reply, done) => { + if (isOpenCodeServerAdminTarget(request.raw.url ?? request.url)) reply.header("cache-control", "no-store") + done() + }) + app.addHook("onSend", (request, reply, payload, done) => { + if (!isOpenCodeServerAdminTarget(request.raw.url ?? request.url) || reply.statusCode < 400) { done(null, payload); return } + let code = reply.statusCode === 401 ? "unauthorized" : reply.statusCode === 403 ? "host_only" : "invalid_request" + try { const value = JSON.parse(String(payload)); if (errorCodes.has(value.code)) code = value.code } catch { /* fixed diagnostic only */ } + reply.header("content-type", "application/json; charset=utf-8").removeHeader("www-authenticate") + done(null, JSON.stringify({ error: code, code })) + }) +} + +/** Authentication + loopback/non-ingress + actual Origin/Fetch Metadata admission. + * Native renderers use the ordinary backend origin; loading pages mount no admin readers. + */ +export function registerOpenCodeServerAdminGuard(app: FastifyInstance, deps: { + auth: AuthManager; selfOrigins(): Set; devOrigins: ReadonlySet; protocol: "http" | "https" +}) { + app.addHook("onRequest", (request, reply, done) => { + const path = routedPath(request.raw.url ?? request.url) + if (path === null || !(path === prefix || path.startsWith(`${prefix}/`))) { done(); return } + if (!deps.auth.getSessionFromRequest(request)) { reply.code(401).send({ code: "unauthorized" }); return } + const listener = app.server.address() + if (!isLocalRequest(request) || !trustedBrowserRequest(request, deps, typeof listener === "object" ? listener?.port : undefined)) { reply.code(403).send({ code: "host_only" }); return } + done() + }) +} + +function trustedBrowserRequest(request: FastifyRequest, deps: { selfOrigins(): Set; devOrigins: ReadonlySet; protocol: string }, listeningPort?: number): boolean { + const self = deps.selfOrigins(), port = request.raw.socket.localPort ?? listeningPort + // An ephemeral listener has its real port before public metadata is published. + if (port) for (const host of ["localhost", "127.0.0.1", "[::1]"]) self.add(`${deps.protocol}://${host}:${port}`) + if (![...self].some(origin => { try { return new URL(origin).host === request.headers.host } catch { return false } })) return false + const site = request.headers["sec-fetch-site"] + const origin = request.headers.origin + if (site !== undefined && site !== "same-origin" && site !== "none" + && !((site === "same-site" || site === "cross-site") && typeof origin === "string" && deps.devOrigins.has(origin))) return false + if (origin === undefined) return true // Authenticated host CLI/native requests have no browser Origin. + if (typeof origin !== "string") return false + try { + const url = new URL(origin) + if (url.origin !== origin || url.username || url.password || !["http:", "https:"].includes(url.protocol)) return false + } catch { return false } + return self.has(origin) || deps.devOrigins.has(origin) +} + +// prototype-1236: Add server accepts an `opencode pair` link, or `scheme://user:password@host` +// as the secondary manual form. The answer names the profile only, never a credential. +const AddSchema = z.object({ name: z.string().max(200).optional(), address: z.string().min(1).max(4_096) }).strict() + +async function addOpenCodeServer(deps: { settings: SettingsService; connections(): OpenCodeServerConnections }, + body: z.infer, signal: AbortSignal) { + const link = parseOpenCodePairingLink(body.address) + let origin: string, credentials: { username: string; password: string } | undefined, token: string | undefined + if (link) { + origin = link.origin + token = await redeemOpenCodePairing(link, signal) + } else { + let url: URL + try { url = new URL(body.address.trim()) } catch { throw new OpenCodePairingError("invalid_link") } + if (!url.password || url.search || url.hash || url.pathname !== "/") throw new OpenCodePairingError("invalid_link") + credentials = { username: decodeURIComponent(url.username) || "opencode", password: decodeURIComponent(url.password) } + try { origin = normalizeExplicitOrigin(url.origin) } catch (error) { + throw new OpenCodePairingError(error instanceof ExplicitEndpointError && (error.code === "https_required" || error.code === "forbidden_address") ? error.code : "invalid_link") + } + try { await deps.connections().probeCandidate({ origin, credentials }, signal) } + catch (error) { throw new OpenCodePairingError(error instanceof ServerProbeError && error.code === "auth" ? "pairing_expired" : "unreachable") } + } + const registry = deps.settings.getOpenCodeServerRegistry() + const explicit = registry.list().filter(profile => profile.kind === "explicit") + const existing = explicit.find(profile => profile.origin === origin) + const label = body.name?.trim() || existing?.label || new URL(origin).host + const profile = { kind: "explicit" as const, id: existing?.id ?? `oc-${randomUUID()}`, label, origin } + registry.replace(existing ? explicit.map(value => value.id === profile.id ? profile : value) : [...explicit, profile]) + const owner = deps.settings.getOpenCodeServerCredentials() + if (token !== undefined) await owner.setPaired(profile.id, token) + else await owner.set(profile.id, JSON.stringify(credentials)) + return { id: profile.id, label: profile.label, origin: profile.origin } +} + +export function registerOpenCodeServerRoutes(app: FastifyInstance, deps: { + settings: SettingsService; connections(): OpenCodeServerConnections +}) { + app.post(`${prefix}/add`, async (request, reply) => { + const parsed = AddSchema.safeParse(request.body) + if (!parsed.success || Object.keys(request.query as object).length) return reply.code(400).send({ code: "invalid_request" }) + const observer = requestAdmission(request, reply) + try { return await addOpenCodeServer(deps, parsed.data, observer.signal) } + catch (error) { + if (observer.signal.aborted || reply.raw.destroyed) { reply.hijack(); return } + return reply.code(error instanceof OpenCodePairingError && error.code !== "unreachable" ? 400 : 502) + .send({ code: error instanceof OpenCodePairingError ? error.code : "unreachable" }) + } finally { observer.dispose() } + }) + // prototype-1236: removal disconnects known attachments; the UI closes their tabs. + app.delete<{ Params: { id: string } }>(`${prefix}/:id`, async (request, reply) => { + const registry = deps.settings.getOpenCodeServerRegistry() + const explicit = registry.list().filter(profile => profile.kind === "explicit") + if (!explicit.some(profile => profile.id === request.params.id)) return reply.code(404).send({ code: "unknown_server" }) + deps.connections().disconnect(request.params.id) + await deps.settings.getOpenCodeServerCredentials().clear(request.params.id) + registry.replace(explicit.filter(profile => profile.id !== request.params.id)) + return reply.code(204).send() + }) + app.get(prefix, async (_request, reply) => { + try { + const summaries = await deps.settings.getOpenCodeServerSummaries(), owner = deps.connections() + return { servers: summaries.map(profile => ({ ...profile, state: owner.administrativeState(profile.id, profile.kind === "explicit" ? profile.origin : undefined) })), limits: { + explicitActiveTargets: SERVER_CONNECTION_LIMITS.explicitActiveTargets, + reservedLocalTargets: SERVER_CONNECTION_LIMITS.reservedLocalTargets, activeExplicitTargets: owner.activeExplicitTargets, + } } + } catch { return reply.code(503).send({ code: "metadata_unavailable" }) } + }) + app.post(`${prefix}/probe`, async (request, reply) => { + let candidate + try { + if (Object.keys(request.query as object).length) throw new Error() + candidate = parseProbeCandidate(request.body) + } catch { return reply.code(400).send({ code: "invalid_request" }) } + const observer = requestAdmission(request, reply) + try { + const result = await deps.connections().probeCandidate(candidate, observer.signal) + observer.signal.throwIfAborted() + return result + } catch (error) { + if (observer.signal.aborted || reply.raw.destroyed) { reply.hijack(); return } + if (error instanceof ServerConnectionError) return reply.code(error.code === "probe_busy" ? 409 : 503).send({ code: error.code === "probe_busy" ? "probe_busy" : "closed" }) + const diagnostic = error instanceof ServerProbeError ? { code: error.code, phase: error.phase } + : error instanceof ExplicitEndpointError ? { code: error.code, phase: "validation" } : { code: "network", phase: "contract" } + return { version: null, capabilities: (error instanceof ServerProbeError ? error.capabilities : undefined) + ?? initialServerCapabilities({ id: "candidate", kind: "explicit", label: "candidate", origin: candidate.origin }, 0).features, + checkedAt: new Date().toISOString(), diagnostic } + } finally { observer.dispose() } + }) +} diff --git a/packages/server/src/server/routes/panel-extension-api4.test.ts b/packages/server/src/server/routes/panel-extension-api4.test.ts index 399c178ef6..8d64f75613 100644 --- a/packages/server/src/server/routes/panel-extension-api4.test.ts +++ b/packages/server/src/server/routes/panel-extension-api4.test.ts @@ -73,6 +73,7 @@ async function fixture(t: TestContext, permissions: string[], options: { generation: options.generation === undefined ? { global: true, effective: true, models: [{ ref: "p/img", name: "Img" }] } : options.generation as any } } }, workspaceManager: { + requireWorkspaceCapability: () => new AbortController().signal, get: (id: string) => id === "i" ? { id, path: "/repo" } as any : undefined, getSharedServiceConnection: async (id: string) => id === "i" ? { client, assertCurrent() { if (!connection.current) throw new Error("Superseded connection") } } as any : undefined, diff --git a/packages/server/src/server/routes/panel-extension-api4.ts b/packages/server/src/server/routes/panel-extension-api4.ts index 730870f8a8..e8a4cb7f93 100644 --- a/packages/server/src/server/routes/panel-extension-api4.ts +++ b/packages/server/src/server/routes/panel-extension-api4.ts @@ -14,6 +14,7 @@ import { generationTargetSchema, imageReadResultSchema, imageReferenceResultSche import { locationRequestOptions, readLocationRef } from "../../opencode/compatibility/location" import { resolveImagesConversationAt, type ImagesConversationRouteDeps } from "./images-conversation" import { checkDesignFolderExclusion } from "../../workspaces/design-git-exclude" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" const Id = z.string().min(1).max(256) const authority = { instanceId: Id, digest: z.string().regex(/^[a-f0-9]{64}$/) } @@ -74,6 +75,15 @@ export function registerPanelExtensionApi4Routes(app: FastifyInstance, deps: Pan try { const { id } = idSchema.parse(request.params) const input = schema.parse(request.body) as z.infer> & { instanceId: string; digest: string } + if (permission && permission !== "panel.preferences") { + try { + manager.requireWorkspaceCapability(input.instanceId, "integratedImages") + manager.requireWorkspaceCapability(input.instanceId, "design") + } catch (error) { + if (error instanceof Error && "statusCode" in error && error.statusCode === 404) throw new Refused(404) + throw error + } + } // The route settles on the deadline or the caller's departure, whatever its reads still await. return await settle(signal, async () => { const entry = permission ? await deps.store.authorize(id, input.digest, permission) : undefined @@ -90,6 +100,7 @@ export function registerPanelExtensionApi4Routes(app: FastifyInstance, deps: Pan return result }) } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) const code = error instanceof Refused ? error.status : error instanceof z.ZodError ? 400 : error instanceof PanelExtensionError ? { missing: 404, disabled: 403, conflict: 409, invalid: 400, limit: 413, unavailable: 503 }[error.code] : 503 return reply.code(code).send({ error: "Panel extension request unavailable" }) diff --git a/packages/server/src/server/routes/panel-extension-assets.test.ts b/packages/server/src/server/routes/panel-extension-assets.test.ts index 8312bb0df1..27931e6492 100644 --- a/packages/server/src/server/routes/panel-extension-assets.test.ts +++ b/packages/server/src/server/routes/panel-extension-assets.test.ts @@ -14,7 +14,7 @@ test("asset routes require explicit API2 consent, exact digest and owned session const pkg=await readPanelExtensionArchive(fixtureArchive("

Assets

",{apiVersion:2,permissions:["session.context","session.assets.read"]})) let calls=0, owned=true, revoke=false, move=false, directoryNow="/repo", output:unknown={status:"page",entries:[],cursor:null} const client={session:{get:async()=>({location:{directory:directoryNow}})},rpc:{call:async()=>{calls++;if(revoke)await store.activate(pkg.manifest.id,pkg.digest,false);if(move)directoryNow="/moved";return{output}}}} - registerPanelExtensionAssetRoutes(app,{store,workspaceManager:{getSharedServiceConnection:async()=>({client,assertCurrent(){}}) as any,ownsLocation:async()=>owned,desktopPluginsReady:async()=>{}}}) + registerPanelExtensionAssetRoutes(app,{store,workspaceManager:{requireWorkspaceCapability:()=>new AbortController().signal,getSharedServiceConnection:async()=>({client,assertCurrent(){}}) as any,ownsLocation:async()=>owned,desktopPluginsReady:async()=>{}}}) const body={instanceId:"i",digest:pkg.digest,sessionID:"s"} const send=(extra={})=>app.inject({method:"POST",url:`/api/panel-extensions/${pkg.manifest.id}/assets`,payload:{...body,...extra}}) try { @@ -46,7 +46,7 @@ test("final session/ownership reads cannot return asset bytes after disable, rep if (++sessions === 2 && boundary === "session") { started(); await held } return { location: { directory: "/repo" } } } }, rpc: { call: async () => ({ output: { status: "asset", mime: "text/plain", uri: "data:text/plain;base64,c2VjcmV0" } }) } } - registerPanelExtensionAssetRoutes(app, { store, workspaceManager: { desktopPluginsReady: async () => {}, getSharedServiceConnection: async () => ({ client, assertCurrent() {} }) as any, ownsLocation: async () => { + registerPanelExtensionAssetRoutes(app, { store, workspaceManager: { requireWorkspaceCapability: () => new AbortController().signal, desktopPluginsReady: async () => {}, getSharedServiceConnection: async () => ({ client, assertCurrent() {} }) as any, ownsLocation: async () => { if (++ownership === 2 && boundary === "ownership") { started(); await held } return true } } }) @@ -79,6 +79,7 @@ test("asset bytes from a superseded OpenCode connection never reach the response return { output: { status: "asset", mime: "text/plain", uri: "data:text/plain;base64,c2VjcmV0" } } } } } registerPanelExtensionAssetRoutes(app, { store, workspaceManager: { + requireWorkspaceCapability: () => new AbortController().signal, desktopPluginsReady: async () => {}, getSharedServiceConnection: async () => ({ client, assertCurrent() { if (!current) throw new Error("OpenCode connection changed") } }) as any, ownsLocation: async () => { if (++ownership === 2 && boundary === "final ownership") { started(); await held } return true }, diff --git a/packages/server/src/server/routes/panel-extension-assets.ts b/packages/server/src/server/routes/panel-extension-assets.ts index d38f0d247d..f7aaf885bd 100644 --- a/packages/server/src/server/routes/panel-extension-assets.ts +++ b/packages/server/src/server/routes/panel-extension-assets.ts @@ -6,9 +6,10 @@ import { PanelExtensionError } from "../../panel-extensions/archive" import { PRUNING_RPC_ID } from "../../opencode/session-pruning/contract" import { assetsInputSchema, assetsResultSchema, assetReadInputSchema, assetReadResultSchema } from "../../opencode/session-pruning/assets-contract" import { locationRequestOptions, readLocationRef } from "../../opencode/compatibility/location" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" export function registerPanelExtensionAssetRoutes(app: FastifyInstance, deps: { - store: PanelExtensionStore; workspaceManager: Pick + store: PanelExtensionStore; workspaceManager: Pick }) { const authority = { instanceId: z.string().min(1).max(256), digest: z.string().regex(/^[a-f0-9]{64}$/) } const idSchema = z.object({ id: z.string().regex(/^[a-z][a-z0-9-]{1,39}\.[a-z][a-z0-9-]{1,39}$/) }).strict() @@ -19,6 +20,13 @@ export function registerPanelExtensionAssetRoutes(app: FastifyInstance, deps: { const { id } = idSchema.parse(request.params) const schema = (method === "assets" ? assetsInputSchema : assetReadInputSchema).extend(authority).strict() const { instanceId, digest, ...input } = schema.parse(request.body) + try { + deps.workspaceManager.requireWorkspaceCapability(instanceId, "integratedImages") + deps.workspaceManager.requireWorkspaceCapability(instanceId, "design") + } catch (error) { + if (error instanceof Error && "statusCode" in error && error.statusCode === 404) throw new PanelExtensionError("missing") + throw error + } await deps.store.authorize(id, digest, "session.assets.read") const connection = await deps.workspaceManager.getSharedServiceConnection(instanceId) if (!connection) throw new PanelExtensionError("unavailable") @@ -44,6 +52,7 @@ export function registerPanelExtensionAssetRoutes(app: FastifyInstance, deps: { if (output.status === "blocked") return reply.code(503).send({ error: "Assets unavailable" }) return output } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) const code = error instanceof z.ZodError ? 400 : error instanceof PanelExtensionError ? { missing: 404, disabled: 403, conflict: 409, invalid: 400, limit: 413, unavailable: 503 }[error.code] : 503 return reply.code(code).send({ error: "Assets unavailable" }) diff --git a/packages/server/src/server/routes/panel-extension-work-items-boundary.test.ts b/packages/server/src/server/routes/panel-extension-work-items-boundary.test.ts new file mode 100644 index 0000000000..df282506cc --- /dev/null +++ b/packages/server/src/server/routes/panel-extension-work-items-boundary.test.ts @@ -0,0 +1,204 @@ +import assert from "node:assert/strict" +import http from "node:http" +import { mkdtemp, rm } from "node:fs/promises" +import os from "node:os" +import path from "node:path" +import test from "node:test" +import pino from "pino" +import { EventBus } from "../../events/bus" +import { WorkspaceManager } from "../../workspaces/manager" +import { ExplicitWorkspace } from "../../workspaces/explicit-workspace" +import { ForgeWorkItems } from "../../forge/work-items" +import { FORGE_APIS } from "../../forge/providers" +import { PanelExtensionStore } from "../../panel-extensions/store" +import { readPanelExtensionArchive } from "../../panel-extensions/archive" +import { fixtureArchive } from "../../panel-extensions/archive-fixture" +import { FAKE_TUNNEL_HOST, startRemoteSurface } from "../../remote-control/test-support/surface" + +const ORIGIN = `https://${FAKE_TUNNEL_HOST}` +const METHODS = ["workItems", "workItemUrl"] as const +const DENIED = { error: "explicit_capability_unavailable", code: "explicit_capability_unavailable", capability: "git", reason: { code: "localOnly" } } + +// Real HTTP for both the local listener and the Remote Control ingress. Only +// fixture-owned loopback sockets are dialed, as the tunnel's TLS terminator does. +function send(target: string, pathname: string, body?: unknown, headers: Record = {}) { + const [hostname, port] = target.split(":") + return new Promise<{ status: number; body: any; cookie?: string }>((resolve, reject) => { + const request = http.request({ hostname, port: Number(port), path: pathname, method: body === undefined ? "GET" : "POST", + headers: { host: FAKE_TUNNEL_HOST, "content-type": "application/json", ...headers } }, response => { + let text = "" + response.setEncoding("utf8") + response.on("data", chunk => { text += chunk }) + response.on("end", () => resolve({ status: response.statusCode ?? 0, body: JSON.parse(text), + cookie: response.headers["set-cookie"]?.[0]?.split(";")[0] })) + }) + request.on("error", reject) + request.end(body === undefined ? undefined : JSON.stringify(body)) + }) +} + +test("API 3 refuses every explicit binding before host forge entry, including warm caches and paired devices", async t => { + const root = await mkdtemp(path.join(os.tmpdir(), "codenomad-api3-boundary-")) + t.after(() => rm(root, { recursive: true, force: true })) + const hostEffects: string[] = [], discoveries: string[] = [], attachmentReads: string[] = [], forgeReads: string[] = [], entries: string[] = [] + const forbidden = (label: string) => () => { hostEffects.push(label); throw new Error(`Forbidden ${label}`) } + // Safety fence BEFORE readForgeRemote: the original identify/Git, credential + // discovery and provider network must never execute, even on the positive path. + const identify = t.mock.method(ForgeWorkItems.prototype as any, "identify", async (directory: string) => { + discoveries.push(directory) + return { remote: { host: "github.com", path: "fixture/repository" }, api: FORGE_APIS.github, + transport: { access: "anonymous", request: async (url: string) => { + forgeReads.push(url) + return { status: 200, headers: new Headers(), body: JSON.stringify({ total_count: 0, items: [] }) } + } } } + }) + assert.notEqual(identify.mock.original, identify) + for (const method of ["list", "itemUrl"] as const) { + const original = ForgeWorkItems.prototype[method] + t.mock.method(ForgeWorkItems.prototype, method, function (this: ForgeWorkItems, ...args: any[]) { + entries.push(method) + return (original as Function).apply(this, args) + }) + } + const logger = pino({ level: "silent" }), directory = "/synthetic/api3/project" + let connected = true + const connection = { serverId: "explicit-fixture", generation: 1, endpoint: { url: "http://attachment.invalid" }, + assertCurrent() {}, fetch: async (input: RequestInfo | URL) => { + const pathname = new URL(String(input)).pathname + attachmentReads.push(pathname) + if (pathname === "/api/location") return Response.json({ directory, project: { id: "p" } }) + if (pathname === "/api/fs/list") return Response.json({ location: { directory }, data: [] }) + return forbidden("unexpected attachment request")() + } } + const connections = { retainProject: () => ({ acquire: async () => connection, published() {}, release() {} }), + existingForServer: (id: string) => connected && id === connection.serverId ? connection : undefined, + dispose: async () => {} } + const manager = new WorkspaceManager({ rootDir: root, logger, eventBus: new EventBus(), + binaryResolver: { resolveDefault: forbidden("binary resolution") } as never, + settings: { getOpenCodeServerConnections: () => connections, getOwner: forbidden("host settings"), + disposeOpenCodeServers: async () => {} } as never, + sharedService: { endpoint: forbidden("local endpoint"), client: forbidden("local client"), headers: forbidden("local headers"), + validateLocation: forbidden("local location"), subscribe: forbidden("local subscribe"), shutdown: async () => {} }, + }) + t.after(() => manager.shutdown()) + const workspace = (await manager.create(directory, undefined, { serverId: connection.serverId })).workspace + assert.deepEqual(workspace.binding, { serverId: connection.serverId, directory }) + // prototype-1236: native Git reads are available; host Git integrations stay refused below. + assert.throws(() => manager.requireWorkspaceCapability(workspace.id, "worktrees"), { code: "explicit_capability_unavailable" }) + // Only the positive local control is synthetic. Explicit descriptors and their + // immutable bindings still come from the real owner, online and offline. + const get = manager.get.bind(manager) + t.mock.method(manager, "get", (id: string) => id === "local-control" + ? { ...workspace, id, binding: { serverId: "local-shared", directory } } : get(id)) + const store = new PanelExtensionStore(path.join(root, "extensions")) + const pkg = await readPanelExtensionArchive(fixtureArchive("

Work items

", { + apiVersion: 3, permissions: ["session.context", "repository.workItems.read"], + })) + await store.install(pkg) + await store.activate(pkg.manifest.id, pkg.digest, true) + const surface = await startRemoteSurface(t, { panelExtensions: { store, workspaceManager: manager } }) + const login = await send(surface.local, "/api/auth/login", { username: "codenomad", password: "local-password" }) + assert.equal(login.status, 200) + assert.ok(login.cookie) + const paired = await send(surface.target(), "/api/remote-control/pair", { code: surface.code }, { origin: ORIGIN }) + assert.equal(paired.status, 200) + assert.ok(paired.cookie) + const localHeaders = { cookie: login.cookie }, remoteHeaders = { cookie: paired.cookie, origin: ORIGIN } + const invoke = (method: typeof METHODS[number], extra = {}, encoded = false, target = surface.local, headers: Record = localHeaders) => + send(target, `/${encoded ? "%61pi" : "api"}/panel-extensions/${encoded ? pkg.manifest.id.replace(".", "%2E") : pkg.manifest.id}/${method}`, + { instanceId: workspace.id, digest: pkg.digest, kind: "issue", + ...(method === "workItems" ? { query: "", page: 1, fresh: false } : { number: 7 }), ...extra }, headers) + + await t.test("local positive controls prove interception and warm both page and repository caches", async () => { + for (const method of METHODS) { + const response = await invoke(method, { instanceId: "local-control" }) + assert.equal(response.status, 200) + if (method === "workItems") assert.equal(response.body.status, "ok") + else assert.deepEqual(response.body, { url: "https://github.com/fixture/repository/issues/7" }) + assert.equal((await invoke(method, { instanceId: "local-control" }, true, surface.target(), remoteHeaders)).status, 200) + } + assert.deepEqual(entries, ["list", "list", "itemUrl", "itemUrl"]) + assert.deepEqual(discoveries, [directory], "positive control reached the pre-Git interception exactly once") + assert.equal(forgeReads.length, 1, "the real page cache reused the synthetic forge read") + entries.length = discoveries.length = forgeReads.length = 0 + }) + await t.test("auth, digest, disabled permission and missing workspace retain their refusal semantics", async () => { + for (const encoded of [false, true]) for (const method of METHODS) { + assert.equal((await invoke(method, {}, encoded, surface.local, {})).status, 401) + assert.equal((await invoke(method, { digest: "a".repeat(64) }, encoded)).status, 409) + for (const instanceId of ["missing-workspace", "global", "local-shared"]) { + assert.equal((await invoke(method, { instanceId }, encoded)).status, 404) + } + assert.equal((await invoke(method, { instanceId: undefined }, encoded)).status, 400) + await store.activate(pkg.manifest.id, pkg.digest, false) + assert.equal((await invoke(method, {}, encoded)).status, 403) + await store.activate(pkg.manifest.id, pkg.digest, true) + assert.deepEqual(entries, []) + } + }) + for (const offline of [false, true]) { + connected = !offline + for (const encoded of [false, true]) for (const method of METHODS) { + await t.test(`${method}: encoded=${encoded}, offline=${offline}, warm caches never admit explicit host access`, async () => { + for (const [target, headers] of [[surface.local, localHeaders], [surface.target(), remoteHeaders]] as const) { + for (const extra of method === "workItems" ? [{ fresh: false }, { fresh: true }] : [{}]) { + const response = await invoke(method, extra, encoded, target, headers) + assert.deepEqual({ status: response.status, body: response.body }, { status: 403, body: DENIED }) + } + assert.deepEqual(entries, [], "refuse before list/itemUrl, even their warm caches") + assert.deepEqual(discoveries, []) + assert.deepEqual(forgeReads, []) + } + }) + } + } + await t.test("native Git availability never grants host Git integration authority", async () => { + connected = true + const capabilities = ExplicitWorkspace.prototype.capabilities + t.mock.method(ExplicitWorkspace.prototype, "capabilities", function (this: ExplicitWorkspace) { + const value = capabilities.call(this) + value.features.git = { state: "available", reason: { code: "contractVerified" }, evidence: "nativeContract" } + return value + }) + assert.doesNotThrow(() => manager.requireWorkspaceCapability(workspace.id, "git")) + assert.equal(manager.get(workspace.id)?.capabilities?.features.git.state, "available") + for (const method of METHODS) { + const response = await invoke(method) + assert.deepEqual({ status: response.status, body: response.body }, { status: 403, body: DENIED }) + } + assert.deepEqual(entries, []) + }) + await t.test("Remote Control keeps pairing, Origin and host-only gates ahead of both encoded routes", async () => { + for (const encoded of [false, true]) for (const method of METHODS) { + assert.equal((await invoke(method, {}, encoded, surface.target(), { origin: ORIGIN })).status, 401) + assert.equal((await invoke(method, {}, encoded, surface.target(), { cookie: paired.cookie! })).status, 403) + assert.equal((await invoke(method, {}, encoded, surface.target(), { cookie: paired.cookie!, origin: "https://other.tunnel.test" })).status, 403) + } + assert.equal((await send(surface.target(), "/%61pi/remote-control/devices", undefined, remoteHeaders)).status, 404) + const echo = await send(surface.target(), "/api/test/echo", undefined, remoteHeaders) + assert.equal(echo.status, 200) + assert.equal(echo.body.loopbackPrivileges, false) + assert.deepEqual(entries, []) + }) + await t.test("profile metadata, API 1 context and API 4 preferences remain accessible", async () => { + const context = await readPanelExtensionArchive(fixtureArchive("

Context only

", { id: "example.context" })) + const preferences = await readPanelExtensionArchive(fixtureArchive("

Preferences

", { + id: "example.preferences", apiVersion: 4, permissions: ["session.context", "panel.preferences"], + })) + for (const entry of [context, preferences]) { + await store.install(entry) + await store.activate(entry.manifest.id, entry.digest, true) + } + assert.equal((await send(surface.local, "/api/panel-extensions", undefined, localHeaders)).status, 200) + const panel = await send(surface.local, `/api/panel-extensions/${context.manifest.id}/panel?instanceId=${workspace.id}&digest=${context.digest}`, undefined, localHeaders) + assert.deepEqual({ status: panel.status, body: panel.body }, { status: 200, body: { html: "

Context only

" } }) + const value = await send(surface.local, `/api/panel-extensions/${preferences.manifest.id}/preferencesGet`, + { instanceId: workspace.id, digest: preferences.digest }, localHeaders) + assert.deepEqual({ status: value.status, body: value.body }, { status: 200, body: { status: "ok", value: {} } }) + assert.deepEqual(entries, []) + }) + assert.deepEqual(hostEffects, []) + assert.deepEqual(discoveries, []) + assert.deepEqual(forgeReads, []) + assert.deepEqual(attachmentReads, ["/api/location", "/api/fs/list"], "routes never acquire the execution target") +}) diff --git a/packages/server/src/server/routes/panel-extension-work-items.ts b/packages/server/src/server/routes/panel-extension-work-items.ts index f00c4264be..56c61f6704 100644 --- a/packages/server/src/server/routes/panel-extension-work-items.ts +++ b/packages/server/src/server/routes/panel-extension-work-items.ts @@ -4,6 +4,7 @@ import type { WorkspaceManager } from "../../workspaces/manager" import type { PanelExtensionStore } from "../../panel-extensions/store" import { PanelExtensionError } from "../../panel-extensions/archive" import { FORGE_MAX_PAGE, type ForgeWorkItems } from "../../forge/work-items" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" const kind = z.enum(["issue", "pullRequest"]) const authority = { instanceId: z.string().min(1).max(256), digest: z.string().regex(/^[a-f0-9]{64}$/) } @@ -33,12 +34,15 @@ export function registerPanelExtensionWorkItemRoutes(app: FastifyInstance, deps: await deps.store.authorize(id, input.digest, "repository.workItems.read") const workspace = deps.workspaceManager.get(input.instanceId) if (!workspace) throw new PanelExtensionError("missing") + // This integration uses host Git and forge sign-ins, independently of native Git capabilities. + if (workspace.binding && workspace.binding.serverId !== "local-shared") throw new WorkspaceCapabilityError("git", { code: "localOnly" }) const result = await read(workspace.path, input, abandoned.signal) // Revocation, replacement or closing the project during the read fences its result. await deps.store.authorize(id, input.digest, "repository.workItems.read") if (deps.workspaceManager.get(input.instanceId)?.path !== workspace.path) throw new PanelExtensionError("unavailable") return result } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) const code = error instanceof z.ZodError ? 400 : error instanceof PanelExtensionError ? { missing: 404, disabled: 403, conflict: 409, invalid: 400, limit: 413, unavailable: 503 }[error.code] : 503 return reply.code(code).send({ error: "Work items unavailable" }) diff --git a/packages/server/src/server/routes/pending-requests-explicit.test.ts b/packages/server/src/server/routes/pending-requests-explicit.test.ts new file mode 100644 index 0000000000..26d1b46ad7 --- /dev/null +++ b/packages/server/src/server/routes/pending-requests-explicit.test.ts @@ -0,0 +1,47 @@ +import assert from "node:assert/strict" +import test from "node:test" +import Fastify from "fastify" +import pino from "pino" +import { EventBus } from "../../events/bus" +import { PermissionReceipts } from "../../permissions/receipts" +import { initialServerCapabilities, requireServerCapability } from "../../opencode/servers/capabilities" +import { registerPermissionReceiptRoutes } from "./permission-receipts" +import { registerPendingRequestRoutes } from "./pending-requests" + +test("explicit pending and receipt routes refuse structurally before acquisition, Git, filesystem, lists or store reads", async t => { + const app = Fastify(), effects: string[] = [] + t.after(() => app.close()) + const forbidden = (name: string) => () => { effects.push(name); throw new Error(`Forbidden ${name}`) } + const manager = { + get: (id: string) => ({ id, path: "/工作/100%", binding: { serverId: id, directory: "/工作/100%" } }), + requireWorkspaceCapability: (id: string, capability: "pendingRecovery" | "historyEnrichment") => { + const snapshot = initialServerCapabilities({ id, kind: "explicit", label: id, origin: "https://example.invalid" }, 1) + requireServerCapability(capability, snapshot.features[capability]) + }, + getSharedServiceConnection: forbidden("connection"), getServiceLocation: forbidden("location"), + getServicePathStyle: forbidden("path style"), getServiceDirectoryForPath: forbidden("host directory"), + getWorktreeIdentityForPath: forbidden("Git"), getHostPathForServicePath: forbidden("host path"), + ownsLocation: forbidden("ownership scan"), desktopPluginsReady: forbidden("provisioning"), + } + const receipts = new PermissionReceipts({ list: forbidden("receipt store") } as never, manager as never, new EventBus(), pino({ level: "silent" })) + registerPermissionReceiptRoutes(app, receipts) + registerPendingRequestRoutes(app, { workspaceManager: manager as never, worktreeDeletionFence: { isBlocked: forbidden("deletion fence") }, + readGitCommonDirectory: forbidden("Git common directory") as never }) + for (const id of ["A", "B"]) for (const [url, capability, reason] of [ + [`/api/workspaces/${id}/pending-requests?directories=${encodeURIComponent("/工作/100%")}`, "pendingRecovery", "liveOnly"], + [`/api/workspaces/${id}/sessions/ses_same/permission-receipts?messageId=same`, "historyEnrichment", "deferred"], + ]) { + const response = await app.inject({ method: "GET", url }) + assert.equal(response.statusCode, 403) + assert.deepEqual(response.json(), { error: "explicit_capability_unavailable", code: "explicit_capability_unavailable", capability, reason: { code: reason } }) + assert.equal(response.headers["cache-control"], "no-store") + } + assert.deepEqual(effects, []) +}) + +test("receipt route preserves ordinary internal failures instead of disguising them as capability refusals", async t => { + const app = Fastify() + t.after(() => app.close()) + registerPermissionReceiptRoutes(app, { list: async () => { throw new Error("owned failure") } } as never) + assert.equal((await app.inject("/api/workspaces/local/sessions/ses_same/permission-receipts?unanchored=true")).statusCode, 500) +}) diff --git a/packages/server/src/server/routes/pending-requests.test.ts b/packages/server/src/server/routes/pending-requests.test.ts index 21a44dcd94..0bbaeb1295 100644 --- a/packages/server/src/server/routes/pending-requests.test.ts +++ b/packages/server/src/server/routes/pending-requests.test.ts @@ -54,6 +54,7 @@ async function harness(options: Pick new AbortController().signal, get: (id) => id === "fixture" && state.present ? workspace : undefined, getSharedServiceConnection: async () => connection, getServiceLocation: () => ({ directory: state.bootstrap }), diff --git a/packages/server/src/server/routes/pending-requests.ts b/packages/server/src/server/routes/pending-requests.ts index bf344c0d36..c4891dd351 100644 --- a/packages/server/src/server/routes/pending-requests.ts +++ b/packages/server/src/server/routes/pending-requests.ts @@ -9,6 +9,8 @@ import type { WorkspaceManager } from "../../workspaces/manager" import type { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" import { readGitCommonDirectory } from "../../workspaces/git-common-directory" import { deferPendingDiscovery, markLoadedPendingSupported, PENDING_DISCOVERY_DEFERRED } from "../../workspaces/pending-discovery" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" +import { formInfoSchema as formSchema } from "../../opencode/form-contract" const directorySchema = z.string().min(1).max(4096) const directoryListSchema = z.union([directorySchema, z.array(directorySchema).min(1).max(64)]) @@ -18,28 +20,6 @@ const permissionSchema = z.object({ save: z.array(z.string()).optional(), metadata: z.record(z.unknown()).optional(), message: z.string().optional(), source: z.object({ type: z.literal("tool"), messageID: z.string(), id: z.string() }).optional(), }) -const numeric = z.union([z.number(), z.enum(["Infinity", "-Infinity", "NaN"])]) -const option = z.object({ value: z.string(), label: z.string(), description: z.string().optional() }) -const field = z.object({ - key: z.string(), title: z.string().optional(), description: z.string().optional(), - required: z.boolean().optional(), hidden: z.boolean().optional(), - when: z.array(z.object({ key: z.string(), op: z.enum(["eq", "neq"]), value: z.union([z.string(), numeric, z.boolean()]) })).optional(), -}) -const fieldSchema = z.discriminatedUnion("type", [ - field.extend({ type: z.literal("string"), format: z.enum(["email", "uri", "date", "date-time"]).optional(), - minLength: z.number().optional(), maxLength: z.number().optional(), pattern: z.string().optional(), - placeholder: z.string().optional(), default: z.string().optional(), options: z.array(option).optional(), custom: z.boolean().optional() }), - field.extend({ type: z.literal("number"), minimum: numeric.optional(), maximum: numeric.optional(), default: numeric.optional() }), - field.extend({ type: z.literal("integer"), minimum: numeric.optional(), maximum: numeric.optional(), default: numeric.optional() }), - field.extend({ type: z.literal("boolean"), default: z.boolean().optional() }), - field.extend({ type: z.literal("multiselect"), options: z.array(option), minItems: z.number().optional(), - maxItems: z.number().optional(), custom: z.boolean().optional(), default: z.array(z.string()).optional() }), - field.extend({ type: z.literal("external"), url: z.string() }), -]) -const formSchema = z.object({ - id: z.string(), sessionID: z.string(), title: z.string(), metadata: z.record(z.unknown()).optional(), - fields: z.array(fieldSchema).min(1), -}) // One backend-owned RPC; never exposed by the generic instance proxy. const snapshotSchema = z.object({ originDirectory: directorySchema, data: z.array( z.object({ directory: directorySchema, status: z.literal("complete"), locations: z.array(z.object({ @@ -66,7 +46,7 @@ async function drainOwnershipReads(reads: Promise[]): Promise { const missingHost = (host: string) => lstat(host).then(() => false, error => (error as NodeJS.ErrnoException).code === "ENOENT") export interface PendingRequestsRouteDeps { - workspaceManager: Pick + workspaceManager: Pick worktreeDeletionFence: Pick /** Test seam only; production always uses the real Git common-directory reader. */ readGitCommonDirectory?: typeof readGitCommonDirectory @@ -96,6 +76,7 @@ export function registerPendingRequestRoutes(app: FastifyInstance, deps: Pending reply.header("Server-Timing", timing.join(", ")) } try { + manager.requireWorkspaceCapability(id, "pendingRecovery") const connection = await manager.getSharedServiceConnection(id) if (!connection) return reply.code(503).send({ error: "Pending requests unavailable" }) if (deferPendingDiscovery(connection, { loadedOnly: true })) return reply.header("Retry-After", "30").code(503).send({ error: PENDING_DISCOVERY_DEFERRED, code: "deferred" }) @@ -393,7 +374,8 @@ export function registerPendingRequestRoutes(app: FastifyInstance, deps: Pending reason: deleting.has(directory) ? "deleting" as const : rejectedPlacement.get(directory) ?? "changed" as const })), ] return result - } catch { + } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) record(phase) // Keep queue contents/paths and native payloads out of diagnostic logs. request.log.warn({ workspaceId: id, phase, nativeStatus, timedOut: signal.aborted, elapsedMs: Date.now() - started }, "Pending request recovery failed") diff --git a/packages/server/src/server/routes/permission-receipts.ts b/packages/server/src/server/routes/permission-receipts.ts index 336e9cc1ff..2a4ccb3839 100644 --- a/packages/server/src/server/routes/permission-receipts.ts +++ b/packages/server/src/server/routes/permission-receipts.ts @@ -1,6 +1,7 @@ import type { FastifyInstance } from "fastify" import { z } from "zod" import type { PermissionReceipts } from "../../permissions/receipts" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" const querySchema = z.object({ messageId: z.string().min(1).max(512).optional(), @@ -16,6 +17,11 @@ export function registerPermissionReceiptRoutes(app: FastifyInstance, receipts: if (!query.success || !request.params.sessionId.startsWith("ses") || request.params.sessionId.length > 512) { return reply.code(400).send({ error: "Invalid permission receipt query" }) } - return receipts.list(request.params.id, request.params.sessionId, { ...query.data, unanchored: query.data.unanchored === "true" }) + try { + return await receipts.list(request.params.id, request.params.sessionId, { ...query.data, unanchored: query.data.unanchored === "true" }) + } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.message, code: error.code, capability: error.capability, reason: error.reason }) + throw error + } }) } diff --git a/packages/server/src/server/routes/plugin-controls.ts b/packages/server/src/server/routes/plugin-controls.ts index 2abf8167c4..63ca8d8e3e 100644 --- a/packages/server/src/server/routes/plugin-controls.ts +++ b/packages/server/src/server/routes/plugin-controls.ts @@ -2,6 +2,7 @@ import type { FastifyInstance, FastifyReply } from "fastify" import { z } from "zod" import type { PluginControls } from "../../opencode/plugin-controls" import { PluginControlsError } from "../../opencode/plugin-controls" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" type PluginControlsApi = Pick @@ -56,6 +57,7 @@ function invalidRequest(reply: FastifyReply) { } function handleError(error: unknown, workspaceId: string, logger: FastifyReply["log"], reply: FastifyReply) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) if (error instanceof PluginControlsError) { const status = error.kind === "not-found" ? 404 : error.kind === "forbidden" ? 403 diff --git a/packages/server/src/server/routes/plugin-sources.ts b/packages/server/src/server/routes/plugin-sources.ts index 4d064b5fc2..51dafe8042 100644 --- a/packages/server/src/server/routes/plugin-sources.ts +++ b/packages/server/src/server/routes/plugin-sources.ts @@ -3,6 +3,7 @@ import { z } from "zod" import { PluginControlsError } from "../../opencode/plugin-controls" import { PluginSourcesError, type PluginSources } from "../../opencode/plugin-sources" import { PLUGIN_SOURCE_MAX_SPEC_LENGTH } from "../../opencode/plugin-source-document" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" interface RouteDeps { sources: Pick @@ -51,6 +52,7 @@ function invalidRequest(reply: FastifyReply) { } function handleError(error: unknown, workspaceId: string, logger: FastifyReply["log"], reply: FastifyReply) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) if (error instanceof PluginControlsError) { const status = error.kind === "not-found" ? 404 : error.kind === "forbidden" ? 403 diff --git a/packages/server/src/server/routes/project-participation.test.ts b/packages/server/src/server/routes/project-participation.test.ts new file mode 100644 index 0000000000..7d71c9adaa --- /dev/null +++ b/packages/server/src/server/routes/project-participation.test.ts @@ -0,0 +1,194 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { request as httpRequest } from "node:http" +import { randomUUID } from "node:crypto" +import pino from "pino" +import { EventBus } from "../../events/bus" +import { ClientConnectionManager } from "../../clients/connection-manager" +import { ProjectParticipants, PARTICIPATION_HEADER } from "../../workspaces/project-participants" +import { startRemoteSurface, FAKE_TUNNEL_HOST } from "../../remote-control/test-support/surface" + +function send(target: string, path: string, headers: Record, body: unknown, raw = false) { + return new Promise<{ status: number; body: string; cookie?: string; cache?: string; challenge?: string }>((resolve, reject) => { + const request = httpRequest(`http://${target}`, { path, agent: false, method: "POST", headers: { "content-type": "application/json", ...headers } }, response => { + let text = ""; response.setEncoding("utf8").on("data", chunk => { text += chunk }).on("end", () => resolve({ + status: response.statusCode!, body: text, cookie: response.headers["set-cookie"]?.[0]?.split(";")[0], + cache: response.headers["cache-control"], challenge: response.headers["www-authenticate"], + })) + }) + request.on("error", reject); request.end(raw ? body as string : JSON.stringify(body)) + }) +} + +function stream(target: string, headers: Record, ids = randomUUID()) { + return new Promise<{ token: string; cache: string | undefined; close(): void }>((resolve, reject) => { + const request = httpRequest(`http://${target}/api/events?clientId=${ids}&connectionId=${ids}&participation=1`, { agent: false, headers }, response => { + if (response.statusCode !== 200) { response.resume(); reject(new Error(`SSE status ${response.statusCode}`)); return } + let text = "" + response.setEncoding("utf8").on("data", chunk => { + text += chunk + const match = text.match(/event: codenomad\.project\.participation\ndata: ([^\n]+)\n\n/) + if (match) resolve({ token: JSON.parse(match[1]!).token, cache: response.headers["cache-control"], close() { request.destroy(); response.destroy() } }) + }) + response.on("error", reject) + }) + request.on("error", reject); request.end() + }) +} + +async function fixture(t: test.TestContext) { + const logs: string[] = [], logger = pino({ level: "trace" }, { write: text => logs.push(text) }) + const owner = new ProjectParticipants(), connections = new ClientConnectionManager(logger) + let calls = 0 + const bindings = new Map([["same", { serverId: "A", directory: "/PARTICIPANT_PRIVATE_PATH_é " }], ["other", { serverId: "B", directory: "/PARTICIPANT_PRIVATE_PATH_é " }]]) + const surface = await startRemoteSurface(t, { logger, events: { eventBus: new EventBus(), connections }, + workspaceManager: { projectParticipants: owner, get: (id: string) => { calls++; const binding = bindings.get(id); return binding && { id, binding } } } }) + t.after(() => { connections.shutdown(); owner.dispose() }) + const session = surface.authManager.createSession("codenomad"), second = surface.authManager.createSession("codenomad") + const cookie = `${surface.authManager.getCookieName()}=${session.id}`, otherCookie = `${surface.authManager.getCookieName()}=${second.id}` + const headers = { cookie, host: surface.local, origin: `http://${surface.local}`, "sec-fetch-site": "same-origin" } + return { ...surface, owner, logs, bindings, headers, otherCookie, calls: () => calls } +} + +test("real SSE grants bind an authenticated stream, not supplied connection IDs; early guards and metadata remain private", async t => { + const f = await fixture(t), ids = randomUUID(), live = await stream(f.local, f.headers, ids) + assert.equal(live.cache, "no-store") + t.after(() => live.close()) + const payload = { revision: 1, refs: [{ tabId: randomUUID(), workspaceId: "same", serverId: "A", directory: f.bindings.get("same")!.directory }] } + const headers = { ...f.headers, [PARTICIPATION_HEADER]: live.token } + const before = f.owner.snapshot("A") + for (const extra of [{ cookie: "" }, { cookie: f.otherCookie }, { origin: "null" }, { origin: "https://foreign.test" }, + { host: "forged.test" }, { "sec-fetch-site": "cross-site" }, { [PARTICIPATION_HEADER]: ids }, { [PARTICIPATION_HEADER]: "0".repeat(64) }]) { + const response = await f.app.inject({ method: "POST", url: "/api/project-participation", headers: { ...headers, ...extra }, payload: "{PRIVATE_UNPARSED", remoteAddress: "127.0.0.1" }) + assert.equal(response.statusCode, 403) + assert.equal(response.headers["cache-control"], "no-store") + assert.equal(response.body, '{"code":"participation_unavailable"}') + assert.equal(f.calls(), 0, "guards run before body parsing and metadata/native IO") + } + assert.equal(f.owner.isCurrent(before.receipt), true, "foreign attempts cannot invalidate the other principal") + const accepted = await send(f.local, "/api/project-participation", headers, payload) + assert.equal(accepted.status, 204) + assert.equal(f.owner.snapshot("A").refs[0]!.directory, payload.refs[0]!.directory) + assert.equal(f.owner.snapshot("A").status, "unknown") + const replay = await send(f.local, "/api/project-participation", headers, payload) + assert.equal(replay.status, 409) + assert.equal((await send(f.local, "/api/project-participation", headers, { ...payload, revision: 2 })).status, 204) + const stable = f.owner.snapshot("A") + const replacement = await stream(f.local, { ...f.headers, cookie: f.otherCookie }, ids) + t.after(() => replacement.close()) + assert.equal(f.owner.isCurrent(stable.receipt), false, "the real connection manager retires the replaced response") + assert.equal((await send(f.local, "/api/project-participation", headers, { ...payload, revision: 3 })).status, 403) + assert.equal((await send(f.local, "/api/project-participation", { ...headers, cookie: f.otherCookie, [PARTICIPATION_HEADER]: replacement.token }, { ...payload, revision: 1 })).status, 204) + for (const invalid of [{ ...payload, revision: 4, profile: "/PRIVATE_CONFIG" }, { ...payload, revision: 5, refs: [{ ...payload.refs[0], serverId: "B" }] }]) { + const calls = f.calls() + const response = await send(f.local, "/api/project-participation", { ...headers, cookie: f.otherCookie, [PARTICIPATION_HEADER]: replacement.token }, invalid) + assert.equal(response.status, 409) + if ("profile" in invalid) assert.equal(f.calls(), calls) + } + assert.equal((await send(f.local, "/api/project-participation", { ...headers, cookie: f.otherCookie, [PARTICIPATION_HEADER]: replacement.token }, { ...payload, revision: 6 })).status, 204) + assert.doesNotMatch(f.logs.join(""), new RegExp(`${live.token}|${replacement.token}|PARTICIPANT_PRIVATE_PATH|PRIVATE_CONFIG|PRIVATE_UNPARSED`)) +}) + +test("paired ingress can declare only its stream's refs; revocation retires them without host/admin absence", async t => { + const f = await fixture(t), pairedHeaders = { host: FAKE_TUNNEL_HOST, origin: `https://${FAKE_TUNNEL_HOST}`, "sec-fetch-site": "same-origin" } + const paired = await send(f.target(), "/api/remote-control/pair", pairedHeaders, { code: f.code }) + assert.equal(paired.status, 200) + const headers = { ...pairedHeaders, cookie: paired.cookie! }, live = await stream(f.target(), headers) + t.after(() => live.close()) + const payload = { revision: 1, refs: [{ tabId: randomUUID(), workspaceId: "same", serverId: "A", directory: f.bindings.get("same")!.directory }] } + assert.equal((await send(f.target(), "/api/project-participation", { ...headers, [PARTICIPATION_HEADER]: live.token }, payload)).status, 204) + const captured = f.owner.snapshot("A") + assert.equal(captured.status, "unknown") + assert.equal((await send(f.target(), "/api/opencode-servers/probe", headers, { origin: "http://127.0.0.1:1" })).status, 404) + assert.equal((await send(f.target(), "/api/storage/config/server", headers, { opencodeServers: [] })).status >= 400, true) + f.manager.revokeDevice(f.manager.devices()[0]!.id) + assert.equal(f.owner.isCurrent(captured.receipt), false) + assert.equal(f.owner.snapshot("A").status, "unknown") + assert.equal(f.owner.snapshot("A").unresolvedOwners, 1) + assert.equal(f.owner.snapshot("A").refs.length, 1) + assert.equal((await send(f.target(), "/api/project-participation", { ...headers, [PARTICIPATION_HEADER]: live.token }, { ...payload, revision: 2 })).status, 401) +}) + +test("encoded publication routes, malformed and oversized bodies stay fixed/private before metadata IO", async t => { + const f = await fixture(t), live = await stream(f.local, f.headers) + t.after(() => live.close()) + const headers = { ...f.headers, [PARTICIPATION_HEADER]: live.token, "content-type": "application/json" } + let revision = 0 + for (const [url, payload, expected] of [ + ["/%61pi/project-participation", '{"revision":1,"refs":[],"profile":"PRIVATE_SELECTOR"}', 409], + ["/api/%70roject-participation", "{PRIVATE_MALFORMED", 400], + ["/api/project-participation?credential=PRIVATE_QUERY", "{PRIVATE_UNPARSED", 400], + ["/api/project-participation", JSON.stringify("PRIVATE_OVERSIZE".repeat(80_000)), 413], + ] as const) { + const response = await f.app.inject({ method: "POST", url, headers, payload, remoteAddress: "127.0.0.1" }) + assert.equal(response.statusCode, expected) + assert.equal(response.headers["cache-control"], "no-store") + assert.equal(response.body, '{"code":"participation_unavailable"}') + assert.equal(f.calls(), 0) + assert.equal((await send(f.local, "/api/project-participation", headers, { revision: ++revision, refs: [] })).status, 204) + assert.equal(f.owner.snapshot("A").status, "unknown") + } + assert.doesNotMatch(f.logs.join(""), new RegExp(`${live.token}|PRIVATE_SELECTOR|PRIVATE_MALFORMED|PRIVATE_QUERY|PRIVATE_UNPARSED|PRIVATE_OVERSIZE`)) +}) + +test("both raw query delimiters refuse before body parsing, admission and metadata IO; fresh no-query declarations still publish", async t => { + const f = await fixture(t), live = await stream(f.local, f.headers) + t.after(() => live.close()) + const headers = { ...f.headers, [PARTICIPATION_HEADER]: live.token } + const ref = { tabId: randomUUID(), workspaceId: "same", serverId: "A", directory: f.bindings.get("same")!.directory } + let revision = 0 + for (const route of ["/api/project-participation", "/%61pi/project-participation", "/api/%70roject-participation"]) { + for (const delimiter of [";", "?"]) for (const query of ["", "profile", "profile=PRIVATE_QUERY", "profile=PRIVATE_QUERY&config=PRIVATE_CONFIG"]) { + for (const body of [JSON.stringify({ revision: revision + 1, refs: [ref] }), "{PRIVATE_UNPARSED", "PRIVATE_OVERSIZE".repeat(80_000)]) { + const before = f.owner.snapshot("A"), calls = f.calls() + const url = `${route}${delimiter}${query}` + // Send only a prefix with the oversized declared length: an early refusal can close + // without racing a megabyte of unread TCP writes. Explicit path preserves bare "?". + const oversized = body.length > 1024 * 1024 + const response = await send(f.local, url, oversized ? { ...headers, "content-length": String(Buffer.byteLength(body)) } : headers, + oversized ? "{PRIVATE_UNPARSED" : body, true) + assert.equal(response.status, 400) + assert.equal(response.body, '{"code":"participation_unavailable"}') + assert.equal(response.cache, "no-store") + assert.equal(response.challenge, undefined) + assert.equal(f.calls(), calls, "no metadata resolution on refusal") + assert.equal(f.owner.isCurrent(before.receipt), true, "query refusal precedes even capability admission") + assert.deepEqual(f.owner.snapshot("A").refs, before.refs) + // An oversized declared body would produce 413 after admission; the query guard must win. + assert.equal((await send(f.local, route, headers, { revision: ++revision, refs: [ref] })).status, 204) + assert.equal(f.owner.snapshot("A").refs[0]!.directory, ref.directory) + } + } + } + assert.equal(f.owner.snapshot("A").status, "unknown") + assert.doesNotMatch(f.logs.join(""), new RegExp(`${live.token}|PRIVATE_QUERY|PRIVATE_CONFIG|PRIVATE_UNPARSED|PRIVATE_OVERSIZE|PARTICIPANT_PRIVATE_PATH`)) +}) + +test("encoded reserved separators and raw route case stay non-routable without publication or private diagnostics", async t => { + const f = await fixture(t), live = await stream(f.local, f.headers) + t.after(() => live.close()) + const headers = { ...f.headers, [PARTICIPATION_HEADER]: live.token } + let revision = 0 + for (const [route, status] of [["/API/project-participation", 200], ["/api/PROJECT-PARTICIPATION", 404], ["/api%2Fproject-participation", 200], + ["/api/project-participation%3Bprofile=PRIVATE_QUERY", 404], ["/api/project-participation%3Fprofile=PRIVATE_QUERY", 404], + ["/api/project-participation%253Bprofile=PRIVATE_QUERY", 404]] as const) { + const before = f.owner.snapshot("A"), calls = f.calls() + const response = await send(f.local, route, headers, { revision: revision + 1, refs: [] }) + assert.equal(response.status, status) + assert.equal(response.body, status === 404 ? '{"code":"participation_unavailable"}' : "CodeNomad UI") + assert.equal(response.cache, "no-store") + assert.equal(response.challenge, undefined) + assert.equal(f.calls(), calls) + assert.equal(f.owner.isCurrent(before.receipt), true) + assert.deepEqual(f.owner.snapshot("A").refs, before.refs) + assert.equal((await send(f.local, "/api/project-participation", headers, { revision: ++revision, refs: [] })).status, 204) + } + const before = f.owner.snapshot("A"), calls = f.calls() + const invalid = await send(f.local, "/api/project-participation", { ...headers, [PARTICIPATION_HEADER]: "0".repeat(64) }, "{PRIVATE_UNPARSED", true) + assert.equal(invalid.status, 403) + assert.equal(invalid.body, '{"code":"participation_unavailable"}') + assert.equal(f.calls(), calls) + assert.equal(f.owner.isCurrent(before.receipt), true) + assert.equal((await send(f.local, "/api/project-participation", headers, { revision: ++revision, refs: [] })).status, 204) + assert.doesNotMatch(f.logs.join(""), new RegExp(`${live.token}|PRIVATE_QUERY|PRIVATE_UNPARSED`)) +}) diff --git a/packages/server/src/server/routes/project-participation.ts b/packages/server/src/server/routes/project-participation.ts new file mode 100644 index 0000000000..a4c0331053 --- /dev/null +++ b/packages/server/src/server/routes/project-participation.ts @@ -0,0 +1,89 @@ +import type { FastifyInstance, FastifyRequest } from "fastify" +import type { AuthManager } from "../../auth/manager" +import type { RemoteControlManager } from "../../remote-control/manager" +import { isRemoteRequest, remoteDeviceOf } from "../../remote-control/request-origin" +import { PARTICIPATION_HEADER, type ProjectParticipants } from "../../workspaces/project-participants" +import type { WorkspaceManager } from "../../workspaces/manager" +import { routedPath } from "../routed-path" + +const path = "/api/project-participation" +export function isProjectParticipationTarget(target: string) { + let value = routedPath(target) + if (value === null) return false + for (let pass = 0; pass < 3; pass++) { + if (/^\/api\/project-participation(?:[^a-z0-9_-]|$)/i.test(value)) return true + if (!value.includes("%")) return false + try { value = decodeURIComponent(value) } catch { return false } + } + return /^\/api\/project-participation(?:[^a-z0-9_-]|$)/i.test(value) +} + +export function registerProjectParticipationPrivacy(app: FastifyInstance) { + app.addHook("onRequest", (request, reply, done) => { + if (isProjectParticipationTarget(request.raw.url ?? request.url)) reply.header("cache-control", "no-store") + done() + }) + app.addHook("onSend", (request, reply, payload, done) => { + if (!isProjectParticipationTarget(request.raw.url ?? request.url) || reply.statusCode < 400) { done(null, payload); return } + reply.header("content-type", "application/json; charset=utf-8").removeHeader("www-authenticate") + done(null, JSON.stringify({ code: "participation_unavailable" })) + }) +} +type Deps = { auth: AuthManager; remote: Pick; + owner: ProjectParticipants; manager: Pick; + selfOrigins(): Set; devOrigins: ReadonlySet; protocol: string } + +function principal(request: FastifyRequest, deps: Deps) { + const session = deps.auth.getSessionFromRequest(request) + if (!session || session.sessionId === "auth-disabled") return undefined + if (isRemoteRequest(request)) { + const device = remoteDeviceOf(request) + return device && deps.remote.isDeviceAuthorized(device) ? session.sessionId : undefined + } + return deps.auth.isAuthEnabled() ? session.sessionId : undefined +} + +function trusted(request: FastifyRequest, deps: Deps, port?: number) { + const remote = isRemoteRequest(request), origins = remote ? new Set([`https://${request.headers.host}`]) : deps.selfOrigins() + if (!remote && port) for (const host of ["localhost", "127.0.0.1", "[::1]"]) origins.add(`${deps.protocol}://${host}:${port}`) + if (![...origins].some(origin => { try { return new URL(origin).host === request.headers.host } catch { return false } })) return false + const origin = request.headers.origin, site = request.headers["sec-fetch-site"] + const dev = !remote && typeof origin === "string" && deps.devOrigins.has(origin) + if (site !== undefined && site !== "same-origin" && site !== "none" && !dev) return false + if (origin === undefined) return request.method === "GET" // EventSource same-origin GET omits Origin. + return typeof origin === "string" && (origins.has(origin) || dev) +} + +/** A publishing capability belongs to this exact authenticated response, never SSE correlation IDs. */ +export function registerProjectParticipationRoutes(app: FastifyInstance, deps: Deps) { + const admissions = new WeakMap>() + app.addHook("onRequest", (request, reply, done) => { + if (routedPath(request.raw.url ?? request.url) !== path) { done(); return } + reply.header("cache-control", "no-store") + const address = app.server.address(), port = request.raw.socket.localPort ?? (typeof address === "object" ? address?.port : undefined) + const identity = principal(request, deps) + if (!identity || !trusted(request, deps, port)) { reply.code(403).send({ code: "participation_unavailable" }); return } + if (request.method !== "POST" || /[?;]/.test(request.raw.url ?? request.url)) { reply.code(400).send({ code: "participation_unavailable" }); return } + const admitted = deps.owner.admit(request.headers[PARTICIPATION_HEADER], identity) + if (!admitted) { reply.code(403).send({ code: "participation_unavailable" }); return } + admissions.set(request, admitted); done() + }) + app.post(path, { bodyLimit: 1024 * 1024 }, (request, reply) => { + if (request.raw.aborted || reply.raw.destroyed) return reply.code(409).send({ code: "participation_unavailable" }) + const ok = admissions.get(request)?.publish(request.body, id => { + const workspace = deps.manager.get(id) + if (!workspace?.binding) return undefined + return { serverId: workspace.binding.serverId, directory: workspace.binding.directory, owner: workspace.binding } + }) + if (!ok) return reply.code(409).send({ code: "participation_unavailable" }) + return reply.code(204).send() + }) + return { + open(request: FastifyRequest, transportCurrent: () => boolean) { + const address = app.server.address(), port = request.raw.socket.localPort ?? (typeof address === "object" ? address?.port : undefined) + const identity = principal(request, deps) + if (!identity || !trusted(request, deps, port)) return undefined + return deps.owner.register(identity, () => transportCurrent() && principal(request, deps) === identity) + }, + } +} diff --git a/packages/server/src/server/routes/provider-accounts.test.ts b/packages/server/src/server/routes/provider-accounts.test.ts index 4baebf777c..c6588a4543 100644 --- a/packages/server/src/server/routes/provider-accounts.test.ts +++ b/packages/server/src/server/routes/provider-accounts.test.ts @@ -23,6 +23,7 @@ async function fixture() { } as unknown as ProviderAccountsService const fence = new WorktreeDeletionFence() registerProviderAccountsRoutes(app, { accounts, worktreeDeletionFence: fence, workspaceManager: { + requireWorkspaceCapability: () => new AbortController().signal, get: id => id === "w" && state.available ? workspace as never : undefined, getSharedServiceConnection: async () => connection as never, getServiceDirectoryForPath: async (_id, directory) => directory === "D:/project" ? "/project" : undefined, diff --git a/packages/server/src/server/routes/provider-accounts.ts b/packages/server/src/server/routes/provider-accounts.ts index cd7d0500d5..d9bbe0942e 100644 --- a/packages/server/src/server/routes/provider-accounts.ts +++ b/packages/server/src/server/routes/provider-accounts.ts @@ -3,9 +3,10 @@ import { z } from "zod" import type { WorkspaceManager } from "../../workspaces/manager" import type { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" import type { ProviderAccountsService } from "../../provider-accounts/service" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" type Deps = { - workspaceManager: Pick + workspaceManager: Pick worktreeDeletionFence: WorktreeDeletionFence accounts: ProviderAccountsService } @@ -22,7 +23,13 @@ export function registerProviderAccountsRoutes(app: FastifyInstance, deps: Deps) const input = method === "GET" ? readSchema.safeParse(request.query) : writeSchema.safeParse(request.body) if (!params.success || !input.success) return reply.code(400).send({ error: "Invalid provider accounts request" }) const { id, integrationID } = params.data - const manager = deps.workspaceManager, workspace = manager.get(id) + const manager = deps.workspaceManager + try { manager.requireWorkspaceCapability(id, "executionSettings") } + catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + throw error + } + const workspace = manager.get(id) if (!workspace) return reply.code(404).send({ error: "Workspace not found" }) const controller = new AbortController() const close = () => controller.abort() diff --git a/packages/server/src/server/routes/service-usage.ts b/packages/server/src/server/routes/service-usage.ts index cdccfbe8a8..365df8c26f 100644 --- a/packages/server/src/server/routes/service-usage.ts +++ b/packages/server/src/server/routes/service-usage.ts @@ -2,6 +2,7 @@ import type { FastifyInstance } from "fastify" import { z } from "zod" import type { ServiceUsage } from "../../opencode/service-usage" import { PluginControlsError } from "../../opencode/plugin-controls" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" const timezone = z.string().min(1).max(128).refine(value => { try { new Intl.DateTimeFormat("en", { timeZone: value }); return true } catch { return false } }) const Query = z.object({ @@ -15,19 +16,28 @@ export function registerServiceUsageRoutes(app: FastifyInstance, usage: Pick usage.close()) app.get<{ Params: { id: string } }>("/api/workspaces/:id/service-usage/owner", async (request, reply) => { try { return await usage.owner(request.params.id) } - catch { return reply.code(503).send({ error: "Stats display owner unavailable" }) } + catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + if (error instanceof PluginControlsError && error.kind === "not-found") return reply.code(404).send({ error: error.message }) + return reply.code(503).send({ error: "Stats display owner unavailable" }) + } }) app.get<{ Params: { id: string } }>("/api/workspaces/:id/service-usage/cache", async (request, reply) => { const query = z.object({ timezone, days: z.coerce.number().refine(value => [7, 30, 90, 365].includes(value)).optional() }).strict().safeParse(request.query) if (!query.success) return reply.code(400).send({ error: "Invalid Stats display cache query" }) try { return await usage.cached(request.params.id, query.data.timezone, query.data.days) } - catch { return reply.code(503).send({ error: "Stats display cache unavailable" }) } + catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + if (error instanceof PluginControlsError && error.kind === "not-found") return reply.code(404).send({ error: error.message }) + return reply.code(503).send({ error: "Stats display cache unavailable" }) + } }) app.get<{ Params: { id: string } }>("/api/workspaces/:id/service-usage", async (request, reply) => { const query = Query.safeParse(request.query) if (!query.success) return reply.code(400).send({ error: "Invalid bounded service usage query" }) try { return await usage.read(request.params.id, query.data) } catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) if (error instanceof PluginControlsError) return reply.code({ "not-found": 404, forbidden: 403, invalid: 422, conflict: 409, unavailable: 503 }[error.kind]).send({ error: error.message }) request.log.warn({ err: error }, "Service usage unavailable") return reply.code(503).send({ error: "Service usage unavailable" }) diff --git a/packages/server/src/server/routes/session-goal.test.ts b/packages/server/src/server/routes/session-goal.test.ts index f1dfa0cf74..94c1f363a0 100644 --- a/packages/server/src/server/routes/session-goal.test.ts +++ b/packages/server/src/server/routes/session-goal.test.ts @@ -12,6 +12,7 @@ function fixture() { answer: (): unknown => ({ output: goal }) } const calls: any[] = [], ownership: any[] = [] registerSessionGoalRoute(app, { workspaceManager: { + requireWorkspaceCapability: () => new AbortController().signal, ownsLocation: async (id: string, location: unknown) => { ownership.push({ id, location }); return state.owned }, getSharedServiceClient: async () => ({ session: { get: async () => { if (state.missing) throw new Error("not found"); return structuredClone(state.session) } }, diff --git a/packages/server/src/server/routes/session-goal.ts b/packages/server/src/server/routes/session-goal.ts index aa654e5b61..e91432a32d 100644 --- a/packages/server/src/server/routes/session-goal.ts +++ b/packages/server/src/server/routes/session-goal.ts @@ -3,9 +3,10 @@ import { z } from "zod" import type { WorkspaceManager } from "../../workspaces/manager" import { locationRequestOptions, readLocationRef } from "../../opencode/compatibility/location" import { GOAL_RPC_ID, goalStateSchema, type SessionGoalResponse } from "../../opencode/goal-contract" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" export interface SessionGoalRouteDeps { - workspaceManager: Pick + workspaceManager: Pick } const sessionIdSchema = z.string().min(4).max(512).regex(/^ses[A-Za-z0-9_-]*$/) @@ -31,6 +32,11 @@ export function registerSessionGoalRoute(app: FastifyInstance, deps: SessionGoal if (!parsed.success) return reply.code(400).send({ error: "Invalid session" }) const sessionID = parsed.data const manager = deps.workspaceManager + try { manager.requireWorkspaceCapability(request.params.id, "historyEnrichment") } + catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + throw error + } const controller = new AbortController() const abort = () => { if (!reply.raw.writableEnded) controller.abort() } reply.raw.once("close", abort) diff --git a/packages/server/src/server/routes/session-history-ranked.test.ts b/packages/server/src/server/routes/session-history-ranked.test.ts index bd0038daad..a76b85b6b6 100644 --- a/packages/server/src/server/routes/session-history-ranked.test.ts +++ b/packages/server/src/server/routes/session-history-ranked.test.ts @@ -31,6 +31,7 @@ function fixture(options: { root?: string; directories?: string[] } = {}) { } replace() registerSessionHistoryRoutes(app, { worktreeDeletionFence: fence, workspaceManager: { + requireWorkspaceCapability: () => new AbortController().signal, getServiceLocation: () => root ? { directory: root } : undefined, getSharedServiceConnection: async () => active, getSharedServiceClient: async () => active.client, diff --git a/packages/server/src/server/routes/session-history-ranked.ts b/packages/server/src/server/routes/session-history-ranked.ts index 5231b30d8d..0f7e8418e6 100644 --- a/packages/server/src/server/routes/session-history-ranked.ts +++ b/packages/server/src/server/routes/session-history-ranked.ts @@ -9,6 +9,7 @@ import { captureDisplayIdentities } from "../../workspaces/worktree-display-iden import { historyDirectories, ownedHistorySessions } from "./session-history-scope" import { rankedHistoryPageSchema } from "./session-history-ranked-contract" import type { HistoryRouteDeps } from "./session-history" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" const MAX_LOCATIONS = 32 const cursorSchema = z.object({ examined: z.number().int().nonnegative().safe(), @@ -26,6 +27,11 @@ export function registerRankedHistoryRoute(app: FastifyInstance, deps: HistoryRo const parsed = historyRankedInputSchema.safeParse(request.body) if (!parsed.success) return reply.code(400).send({ error: "Invalid ranked history query" }) const id = request.params.id, manager = deps.workspaceManager + try { manager.requireWorkspaceCapability(id, "historyEnrichment") } + catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + throw error + } const base = manager.getServiceLocation(id) if (!base) return reply.code(404).send({ error: "Workspace not found" }) const controller = new AbortController() diff --git a/packages/server/src/server/routes/session-history-scope.ts b/packages/server/src/server/routes/session-history-scope.ts index ce14df08fd..b4166cbd27 100644 --- a/packages/server/src/server/routes/session-history-scope.ts +++ b/packages/server/src/server/routes/session-history-scope.ts @@ -4,7 +4,8 @@ import { readLocationRef } from "../../opencode/compatibility/location" const normalized = (directory: string) => (/^[A-Za-z]:[\\/]|^\\\\/.test(directory) ? directory.replaceAll("\\", "/") : directory).replace(/\/$/, "") -export async function historyDirectories(manager: Pick, id: string, root: string) { +export async function historyDirectories(manager: Pick, id: string, root: string) { + manager.requireWorkspaceCapability(id, "historyEnrichment") return Array.from(new Set([root, ...(await manager.getWorktrees(id, "validated")).worktrees .map(worktree => worktree.serviceDirectory).filter((directory): directory is string => Boolean(directory))])) .sort().filter((directory, _index, all) => !all.some(other => other !== directory && normalized(directory).startsWith(`${normalized(other)}/`))) @@ -12,9 +13,10 @@ export async function historyDirectories(manager: Pick( - manager: Pick, id: string, client: OpenCodeClient, sessions: T[], + manager: Pick, id: string, client: OpenCodeClient, sessions: T[], sessionID?: string, current: () => void = () => {}, signal?: AbortSignal, ): Promise { + manager.requireWorkspaceCapability(id, "historyEnrichment") const ownership = new Map(), owned: T[] = [] for (const candidate of sessions) { if (sessionID && candidate.sessionID !== sessionID) throw new Error("Invalid history owner") diff --git a/packages/server/src/server/routes/session-history.test.ts b/packages/server/src/server/routes/session-history.test.ts index c1cfc42817..b813179b54 100644 --- a/packages/server/src/server/routes/session-history.test.ts +++ b/packages/server/src/server/routes/session-history.test.ts @@ -12,6 +12,7 @@ function fixture(options: { owned?: boolean; cursor?: string | null; output?: un const ownershipChecks: string[] = [] const fence = new WorktreeDeletionFence() registerSessionHistoryRoutes(app, { worktreeDeletionFence: fence, workspaceManager: { + requireWorkspaceCapability: () => new AbortController().signal, desktopPluginsReady: async () => {}, getServiceLocation: () => ({ directory: "/repo" }), getWorktrees: async () => ({ isGitRepo: true, worktrees: [ diff --git a/packages/server/src/server/routes/session-history.ts b/packages/server/src/server/routes/session-history.ts index c85afc9cc9..80de72e382 100644 --- a/packages/server/src/server/routes/session-history.ts +++ b/packages/server/src/server/routes/session-history.ts @@ -9,9 +9,10 @@ import { historyQuerySchema, historyNativeResultSchema, pruneBatchSchema, pruneB import { historyDirectories, ownedHistorySessions } from "./session-history-scope" import { registerRankedHistoryRoute } from "./session-history-ranked" import { assertOrdinaryMissionScheduleSession } from "../mission-schedule-input-guard" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" export interface HistoryRouteDeps { - workspaceManager: Pick + workspaceManager: Pick & Partial> worktreeDeletionFence: WorktreeDeletionFence } @@ -24,6 +25,11 @@ export function registerSessionHistoryRoutes(app: FastifyInstance, deps: History if (!parsed.success) return reply.code(400).send({ error: "Invalid history query" }) const input = parsed.data const manager = deps.workspaceManager + try { manager.requireWorkspaceCapability(request.params.id, "historyEnrichment") } + catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + throw error + } const root = manager.getServiceLocation(request.params.id) if (!root) return reply.code(404).send({ error: "Workspace not found" }) const client = await manager.getSharedServiceClient() @@ -76,6 +82,11 @@ export function registerSessionHistoryRoutes(app: FastifyInstance, deps: History const parsed = pruneBatchSchema.safeParse(request.body) if (!parsed.success) return reply.code(400).send({ error: "Invalid pruning batch" }) const input = parsed.data + try { deps.workspaceManager.requireWorkspaceCapability(request.params.id, "sessionPruning") } + catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + throw error + } const client = await deps.workspaceManager.getSharedServiceClient() // Before authorization: ownership checks and fence entry must stay adjacent. await deps.workspaceManager.desktopPluginsReady() diff --git a/packages/server/src/server/routes/session-media-boundary.test.ts b/packages/server/src/server/routes/session-media-boundary.test.ts new file mode 100644 index 0000000000..cd672351e5 --- /dev/null +++ b/packages/server/src/server/routes/session-media-boundary.test.ts @@ -0,0 +1,303 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { brotliCompressSync, deflateSync, gzipSync } from "node:zlib" +import { imageUri, latch, mediaFixture, nativeMessage, png } from "./session-media-fixture" + +const LIMIT = 16 * 1024 * 1024 +function envelope(size: number) { + const base = JSON.stringify({ data: nativeMessage(), padding: "" }) + return base.slice(0, -2) + " ".repeat(size - Buffer.byteLength(base)) + '"}' +} + +test("real manager + official media client: whole-envelope ceiling rejects +1 before serving even a small valid image", async t => { + const f = await mediaFixture(t) + const from = Buffer.from + let decoded = 0 + t.mock.method(Buffer, "from", ((value: any, ...args: any[]) => { + if (args[0] === "base64") decoded++ + return (from as any)(value, ...args) + }) as typeof Buffer.from) + f.respond(response => response.end(envelope(LIMIT + 1))) + const result = await f.app.inject(f.url()) + assert.equal(result.statusCode, 502) + assert.deepEqual(result.json(), { error: "Media unavailable" }) + assert.equal(decoded, 0, "overflow never reaches base64 decoding") +}) + +test("media route refuses active/unqualified images, malformed base64 and URI overflow without modifying native files", async t => { + const f = await mediaFixture(t) + for (const [mime, uri] of [ + ["image/svg+xml", "data:image/svg+xml;base64,PHN2Zy8+"], + ["image/bmp", "data:image/bmp;base64,eA=="], + ["image/png", "data:image/png;base64,eB=="], + ["image/png", "data:image/png;base64,eA="], + ["image/png", "data:image/png;base64,eA==\n"], + ["image/png", "data:image/jpeg;base64,eA=="], + ["image/png", "data:image/png;base64," + "A".repeat(8 * 1024 * 1024)], + ]) { + const message = nativeMessage(uri, mime), before = structuredClone(message) + f.message(message) + assert.equal((await f.app.inject(f.url(f.a.id, uri))).statusCode, 404, mime) + assert.deepEqual(message, before) + } +}) + +for (const size of [LIMIT - 1, LIMIT]) test(`whole decompressed envelope ${size} bytes succeeds, including unrelated metadata`, async t => { + const f = await mediaFixture(t) + f.respond(response => { response.setHeader("content-length", size); response.end(envelope(size)) }) + const result = await f.app.inject(f.url()) + assert.equal(result.statusCode, 200) + assert.deepEqual(result.rawPayload, png) +}) + +for (const [encoding, compress] of [["gzip", gzipSync], ["deflate", deflateSync], ["br", brotliCompressSync]] as const) { + test(`${encoding}: an exact-limit decoded envelope serves the intact image without double decompression`, async t => { + const f = await mediaFixture(t), compressed = compress(Buffer.from(envelope(LIMIT))) + f.respond(response => { response.setHeader("content-encoding", encoding); response.setHeader("content-length", compressed.byteLength); response.end(compressed) }) + const result = await f.app.inject(f.url()) + assert.equal(result.statusCode, 200) + assert.deepEqual(result.rawPayload, png) + }) + for (const status of [200, 500]) test(`${encoding} ${status}: a tiny compressed envelope expanding past 16 MiB fails closed`, async t => { + const f = await mediaFixture(t) + const compressed = compress(Buffer.from(envelope(LIMIT + 1))) + assert(compressed.byteLength < LIMIT / 100) + f.respond(response => { response.statusCode = status; response.setHeader("content-encoding", encoding); response.setHeader("content-length", compressed.byteLength); response.end(compressed) }) + const result = await f.app.inject(f.url()) + assert.equal(result.statusCode, 502) + assert.deepEqual(result.json(), { error: "Media unavailable" }) + }) +} + +test("real chunked success/error overflow cancels upstream while it still has a body outstanding", async t => { + const f = await mediaFixture(t) + for (const status of [200, 500]) { + const closed = latch() + f.respond(response => { + response.statusCode = status + response.once("close", closed.resolve) + response.write(envelope(LIMIT + 1)) // deliberately never end the body + }) + const result = await f.app.inject(f.url()) + assert.equal(result.statusCode, 502) + await closed.promise + } +}) + +test("malformed JSON, empty bodies and invalid HTTP errors return sanitized failures", async t => { + const f = await mediaFixture(t) + for (const [status, body] of [[200, "{"], [200, ""], [204, ""], [500, "fixture-private-body"], [500, '{"_tag":"SessionNotFoundError","message":"private"}']] as const) { + f.respond(response => { response.statusCode = status; response.end(body) }) + const result = await f.app.inject(f.url()) + assert.equal(result.statusCode, 502) + assert.deepEqual(result.json(), { error: "Media unavailable" }) + } +}) + +test("metadata reads have the same HTTP envelope ceiling", async t => { + const f = await mediaFixture(t) + f.respondSession(response => response.end(JSON.stringify({ data: { id: "s", location: { directory: f.a.path } }, pad: " ".repeat(LIMIT) }))) + assert.equal((await f.app.inject(f.url())).statusCode, 502) + assert.equal(f.calls.filter(call => call.path.includes("/message/")).length, 0) +}) + +test("canonical positions/identities, digest, exact opaque placement and revert remain authoritative", async t => { + const f = await mediaFixture(t) + assert.deepEqual((await f.app.inject(f.url())).rawPayload, png) + for (const [part, index] of [["00", "0"], ["0", "00"], ["-1", "0"], ["9999999", "0"]]) assert.equal((await f.app.inject(f.url(f.a.id, imageUri, part, index))).statusCode, 400) + assert.equal((await f.app.inject(f.url(f.b.id))).statusCode, 404, "a homonymous message on B has other bytes") + assert.equal((await f.app.inject(f.url().replace(/[^/]+$/, "0".repeat(64)))).statusCode, 404) + f.session({ id: "other", location: { directory: f.a.path } }) + assert.equal((await f.app.inject(f.url())).statusCode, 403) + f.session({ id: "s", location: { directory: f.a.path, workspaceID: "internal" } }) + assert.equal((await f.app.inject(f.url())).statusCode, 403) + f.session({ id: "s", location: { directory: f.a.path.toLowerCase() } }) + assert.equal((await f.app.inject(f.url())).statusCode, 403) + f.session({ id: "s", location: { directory: f.a.path }, revert: { messageID: "m" } }) + assert.equal((await f.app.inject(f.url())).statusCode, 404) + f.session({ id: "s", location: { directory: f.a.path } }) + f.afterMessage(() => f.session({ id: "s", location: { directory: "/moved" } })) + assert.equal((await f.app.inject(f.url())).statusCode, 409) +}) + +for (const revoke of ["rotate", "disconnect", "close"] as const) test(`stalled body: ${revoke} cancels captured transport with no replacement read or publication`, async t => { + const f = await mediaFixture(t), entered = latch(), closed = latch() + f.respond(response => { response.once("close", closed.resolve); response.write('{"data":'); entered.resolve() }) + const pending = f.app.inject(f.url()) + await entered.promise + const before = f.calls.length + if (revoke === "rotate") await f.credentials.set("A", JSON.stringify({ username: "new", password: "synthetic" })) + if (revoke === "disconnect") f.connections.disconnect("A") + if (revoke === "close") await f.manager.delete(f.a.id) + assert.equal((await pending).statusCode, 502) + await closed.promise + assert.equal(f.calls.length, before) +}) + +test("revocation before dispatch rejects before acquisition, and B/local remain readable", async t => { + const f = await mediaFixture(t) + f.connections.disconnect("A") + const before = f.calls.length + assert.equal((await f.app.inject(f.url())).statusCode, 403) + assert.equal(f.calls.length, before) + assert.equal((await f.app.inject(f.url(f.b.id, `data:image/png;base64,${Buffer.from("B").toString("base64")}`))).statusCode, 200) + assert.deepEqual((await f.app.inject(f.url(f.local.id))).rawPayload, png) +}) + +test("shared-local body has the same bound and aborts on its workspace lifetime", async t => { + const f = await mediaFixture(t), entered = latch(), closed = latch() + f.respond(response => response.end(envelope(LIMIT + 1))) + assert.equal((await f.app.inject(f.url(f.local.id))).statusCode, 502) + f.respond(response => { response.once("close", closed.resolve); response.write('{"data":'); entered.resolve() }) + const pending = f.app.inject(f.url(f.local.id)) + await entered.promise + f.localLife.abort() + assert.equal((await pending).statusCode, 502) + await closed.promise +}) + +test("client socket close cancels a stalled upstream without trying to send an error afterward", async t => { + const f = await mediaFixture(t), entered = latch(), closed = latch() + let sent = 0 + f.app.addHook("onSend", async () => { sent++ }) + f.respond(response => { response.once("close", closed.resolve); response.write('{"data":'); entered.resolve() }) + const origin = await f.app.listen({ host: "127.0.0.1", port: 0 }) + const controller = new AbortController() + const rejected = assert.rejects(fetch(origin + f.url(), { signal: controller.signal }), { name: "AbortError" }) + await entered.promise + controller.abort() + await rejected + await closed.promise + await new Promise(resolve => setImmediate(resolve)) + assert.equal(sent, 0) +}) + +test("30-second route deadline cancels a genuinely stalled body, not just its eventual publication", async t => { + const f = await mediaFixture(t), closed = latch() + f.respond(response => { response.once("close", closed.resolve); response.write('{"data":') }) + const result = await f.app.inject(f.url()) + assert.equal(result.statusCode, 502) + await closed.promise +}) + +test("missing captured transport never falls back to any shared client", async t => { + const f = await mediaFixture(t) + t.mock.method(f.manager, "getSharedServiceConnection", async () => undefined) + const before = f.calls.length + for (const id of [f.a.id, f.local.id]) assert.equal((await f.app.inject(f.url(id))).statusCode, 503) + assert.equal(f.calls.length, before) +}) + +test("cancelled acquisition releases its observer before shared work settles and cannot dispatch late", async t => { + const f = await mediaFixture(t), entered = latch() + const captured = await f.manager.getSharedServiceConnection(f.local.id) + let finish!: () => void + const held = new Promise(resolve => { finish = () => resolve(captured) }) + t.mock.method(f.manager, "getSharedServiceConnection", async () => { entered.resolve(); return held }) + const before = f.calls.length, pending = f.app.inject(f.url(f.local.id)) + await entered.promise + f.localLife.abort() + assert.equal((await pending).statusCode, 502) + finish() + await new Promise(resolve => setImmediate(resolve)) + assert.equal(f.calls.length, before) +}) + +test("client close during acquisition retires its observer while preserving shared owner work", async t => { + const f = await mediaFixture(t), entered = latch(), closed = latch() + const captured = await f.manager.getSharedServiceConnection(f.local.id) + let finish!: () => void, sent = 0 + const held = new Promise(resolve => { finish = () => resolve(captured) }) + t.mock.method(f.manager, "getSharedServiceConnection", async () => { entered.resolve(); return held }) + f.app.addHook("onSend", async () => { sent++ }) + f.app.addHook("onRequest", async (_request, reply) => { reply.raw.once("close", closed.resolve) }) + const origin = await f.app.listen({ host: "127.0.0.1", port: 0 }), controller = new AbortController() + const before = f.calls.length + const rejected = assert.rejects(fetch(origin + f.url(f.local.id), { signal: controller.signal }), { name: "AbortError" }) + await entered.promise + controller.abort() + await rejected + await closed.promise + finish() + await new Promise(resolve => setImmediate(resolve)) + assert.equal(sent, 0) + assert.equal(f.calls.length, before) +}) + +test("30-second deadline bounds an observer waiting on shared acquisition without dispatching after it settles", async t => { + const f = await mediaFixture(t) + const captured = await f.manager.getSharedServiceConnection(f.local.id) + let finish!: () => void + const held = new Promise(resolve => { finish = () => resolve(captured) }) + t.mock.method(f.manager, "getSharedServiceConnection", async () => held) + const before = f.calls.length + assert.equal((await f.app.inject(f.url(f.local.id))).statusCode, 502) + finish() + await new Promise(resolve => setImmediate(resolve)) + assert.equal(f.calls.length, before) +}) + +test("shared-local trusted image formats retain their existing sandboxed serving policy", async t => { + const f = await mediaFixture(t) + const uri = "data:image/svg+xml;base64,PHN2Zy8+" + f.message(nativeMessage(uri, "image/svg+xml")) + const local = await f.app.inject(f.url(f.local.id, uri)) + assert.equal(local.statusCode, 200) + assert.equal(local.headers["content-security-policy"], "default-src 'none'; sandbox") + assert.equal((await f.app.inject(f.url(f.a.id, uri))).statusCode, 404) +}) + +test("an already-closed downstream request cannot acquire or dispatch when its handler is admitted late", async t => { + const f = await mediaFixture(t), entered = latch(), closed = latch() + let captures = 0 + const acquire = f.manager.getSharedServiceConnection.bind(f.manager) + t.mock.method(f.manager, "getSharedServiceConnection", async (id: string) => { captures++; return acquire(id) }) + f.app.addHook("preHandler", async (_request, reply) => { + reply.raw.once("close", closed.resolve) + entered.resolve() + await closed.promise + }) + const origin = await f.app.listen({ host: "127.0.0.1", port: 0 }), controller = new AbortController() + const rejected = assert.rejects(fetch(origin + f.url(), { signal: controller.signal }), { name: "AbortError" }) + await entered.promise + controller.abort() + await rejected + await closed.promise + await new Promise(resolve => setImmediate(resolve)) + assert.equal(captures, 0) +}) + +for (const path of ["invalid-reference", "missing-workspace"]) test(`closed late handler: ${path} publishes no response or raw write`, async t => { + const f = await mediaFixture(t), entered = latch(), closed = latch(), handled = latch() + let sent = 0, ended = 0, written = 0, captures = 0 + const acquire = f.manager.getSharedServiceConnection.bind(f.manager) + t.mock.method(f.manager, "getSharedServiceConnection", async (id: string) => { captures++; return acquire(id) }) + f.app.addHook("onSend", async () => { sent++ }) + f.app.addHook("preHandler", async (_request, reply) => { + reply.raw.once("close", closed.resolve) + entered.resolve() + await closed.promise + const end = reply.raw.end.bind(reply.raw), write = reply.raw.write.bind(reply.raw) + reply.raw.end = ((...args: any[]) => { ended++; return (end as any)(...args) }) as typeof reply.raw.end + reply.raw.write = ((...args: any[]) => { written++; return (write as any)(...args) }) as typeof reply.raw.write + setImmediate(() => setImmediate(handled.resolve)) + }) + const origin = await f.app.listen({ host: "127.0.0.1", port: 0 }), controller = new AbortController() + const url = path === "invalid-reference" ? f.url().replace("/0/0/", "/00/0/") : f.url("missing") + const rejected = assert.rejects(fetch(origin + url, { signal: controller.signal }), { name: "AbortError" }) + await entered.promise + controller.abort() + await rejected + await closed.promise + await handled.promise + assert.deepEqual({ sent, ended, written, captures }, { sent: 0, ended: 0, written: 0, captures: 0 }) +}) + +test("open requests retain ordinary 400/404/capability responses and the positive local image", async t => { + const f = await mediaFixture(t) + assert.equal((await f.app.inject(f.url().replace("/0/0/", "/00/0/"))).statusCode, 400) + assert.equal((await f.app.inject(f.url("missing"))).statusCode, 404) + f.connections.disconnect("A") + assert.equal((await f.app.inject(f.url())).statusCode, 403) + assert.deepEqual((await f.app.inject(f.url(f.local.id))).rawPayload, png) +}) diff --git a/packages/server/src/server/routes/session-media-fixture.ts b/packages/server/src/server/routes/session-media-fixture.ts new file mode 100644 index 0000000000..e2cffb2bfb --- /dev/null +++ b/packages/server/src/server/routes/session-media-fixture.ts @@ -0,0 +1,95 @@ +import { once } from "node:events" +import { createServer, type ServerResponse } from "node:http" +import { OpenCode, type OpenCodeClient, type LocationRef } from "@opencode/client" +import Fastify from "fastify" +import pino from "pino" +import type { TestContext } from "node:test" +import { EventBus } from "../../events/bus" +import { explicitContractFixture } from "../../opencode/compatibility/contract-fixture" +import { OpenCodeServerConnections } from "../../opencode/servers/connections" +import { OpenCodeServerCredentials } from "../../opencode/servers/credentials" +import { OpenCodeServerRegistry } from "../../opencode/servers/registry" +import type { ServerCapability } from "../../opencode/servers/capabilities" +import { mediaDigest } from "../../opencode/session-media" +import { WorkspaceManager } from "../../workspaces/manager" +import { registerSessionMediaRoutes } from "./session-media" + +export const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=", "base64") +export const imageUri = `data:image/png;base64,${png.toString("base64")}` +export const nativeMessage = (uri = imageUri, mime = "image/png") => ({ id: "m", type: "assistant", content: [ + { type: "tool", state: { status: "completed", content: [{ type: "file", mime, uri }] } }, +] }) +export function latch() { + let resolve!: () => void + const promise = new Promise(done => { resolve = done }) + return { promise, resolve } +} + +/** Owned loopback HTTP only; real registry/credentials/transport/manager and official client. */ +export async function mediaFixture(t: TestContext) { + const directory = "/opaque Case/🦊", calls: { target: string; path: string; auth?: string; directory?: string }[] = [] + let session: Record = { id: "s", location: { directory } } + let file = nativeMessage(), responder: ((response: ServerResponse) => void) | undefined + let sessionResponder: ((response: ServerResponse) => void) | undefined + let afterMessage = () => {} + const upstreams: ReturnType[] = [], profiles: any[] = [] + let localConnection: any + for (const target of ["A", "B", "local-shared"]) { + const upstream = createServer((request, response) => { + const url = new URL(request.url!, "http://fixture") + calls.push({ target, path: url.pathname, auth: request.headers.authorization, directory: request.headers["x-opencode-directory"] as string | undefined }) + response.setHeader("content-type", "application/json") + const send = (value: unknown) => response.end(JSON.stringify(value)) + if (url.pathname === "/openapi.json") return send(explicitContractFixture()) + if (url.pathname === "/api/location") return send({ directory, project: { id: "same", directory: "/", canonical: "/" } }) + if (url.pathname === "/api/fs/list") return send({ location: { directory }, data: [] }) + if (url.pathname === "/api/session/s") return sessionResponder ? sessionResponder(response) : send({ data: session }) + if (url.pathname === "/api/session/s/message/m") { + afterMessage() + return responder ? responder(response) : send({ data: target === "B" ? nativeMessage(`data:image/png;base64,${Buffer.from("B").toString("base64")}`) : file }) + } + response.statusCode = 404; send({}) + }) + upstream.listen(0, "127.0.0.1"); await once(upstream, "listening") + upstreams.push(upstream) + const origin = `http://127.0.0.1:${(upstream.address() as { port: number }).port}` + if (target !== "local-shared") profiles.push({ id: target, kind: "explicit", label: target, origin }) + else localConnection = { endpoint: { url: origin, username: "fixture", password: "local-fixture" }, + fetch: globalThis.fetch, client: OpenCode.make({ baseUrl: origin }), assertCurrent() {}, invalidate() {}, profile: async () => "modern" } + } + const forbidden = () => { throw new Error("Host operation forbidden") } + const registry = new OpenCodeServerRegistry(() => profiles, forbidden) + const credentials = new OpenCodeServerCredentials({ profileKey: "media", configIdentity: "media" }, registry) + for (const id of ["A", "B"]) await credentials.set(id, JSON.stringify({ username: id, password: `fixture-${id}` })) + const connections = new OpenCodeServerConnections({ registry, credentials, local: { acquire: forbidden, existing: forbidden, invalidate: forbidden } }) + const manager = new WorkspaceManager({ rootDir: "C:/forbidden", eventBus: new EventBus(), logger: pino({ level: "silent" }), + binaryResolver: { resolveDefault: forbidden } as never, + settings: { getOpenCodeServerConnections: () => connections, getOwner: forbidden, readEnvironmentForAdmission: forbidden, + disposeOpenCodeServers: () => connections.dispose() } as never, + sharedService: { endpoint: forbidden, client: forbidden, headers: forbidden, validateLocation: forbidden, subscribe: forbidden, shutdown: async () => {} }, + }) + const a = (await manager.create(directory, undefined, { serverId: "A" })).workspace + const b = (await manager.create(directory, undefined, { serverId: "B" })).workspace + const local = { id: "local", path: directory, binding: { serverId: "local-shared", directory } } as typeof a + const localLife = new AbortController() + const get = manager.get.bind(manager), acquire = manager.getSharedServiceConnection.bind(manager), requireCapability = manager.requireWorkspaceCapability.bind(manager) + const owns = manager.ownsLocation.bind(manager) + t.mock.method(manager, "get", (id: string) => id === local.id ? local : get(id)) + t.mock.method(manager, "getSharedServiceConnection", (id: string) => id === local.id ? Promise.resolve(localConnection) : acquire(id)) + t.mock.method(manager, "requireWorkspaceCapability", (id: string, capability: ServerCapability) => id === local.id ? localLife.signal : requireCapability(id, capability)) + t.mock.method(manager, "ownsLocation", (id: string, location: LocationRef, client?: OpenCodeClient, signal?: AbortSignal) => id === local.id ? Promise.resolve(location.directory === directory) : owns(id, location, client, signal)) + t.mock.method(manager, "getSharedServiceClient", forbidden) + const app = Fastify() + registerSessionMediaRoutes(app, { workspaceManager: manager }) + t.after(async () => { + await manager.shutdown() + await app.close() + await Promise.all(upstreams.map(server => { server.closeAllConnections(); return new Promise(resolve => server.close(() => resolve())) })) + }) + const url = (id = a.id, uri = imageUri, part = "0", index = "0") => `/api/workspaces/${id}/session-media/s/m/${part}/${index}/${mediaDigest(uri)}` + return { app, manager, connections, credentials, calls, a, b, local, localLife, url, + message(value: typeof file) { file = value }, session(value: typeof session) { session = value }, + respond(value?: typeof responder) { responder = value }, respondSession(value?: typeof sessionResponder) { sessionResponder = value }, + afterMessage(value: () => void) { afterMessage = value }, + } +} diff --git a/packages/server/src/server/routes/session-media.test.ts b/packages/server/src/server/routes/session-media.test.ts index f4a13cf511..d5789c3998 100644 --- a/packages/server/src/server/routes/session-media.test.ts +++ b/packages/server/src/server/routes/session-media.test.ts @@ -1,6 +1,7 @@ import assert from "node:assert/strict" import { test } from "node:test" import Fastify from "fastify" +import { OpenCode } from "@opencode/client" import { mediaDigest } from "../../opencode/session-media" import { registerSessionMediaRoutes } from "./session-media" @@ -9,6 +10,7 @@ const uri = `data:image/png;base64,${bytes.toString("base64")}` function fixture() { const app = Fastify() + const workspace = { path: "/repo" } let owned = true, session: any = { id: "s", location: { directory: "/repo" } } let afterRead = () => {} const message = { id: "msg_2", type: "assistant", content: [ @@ -16,11 +18,20 @@ function fixture() { { type: "tool", id: "call", name: "read", state: { status: "completed", content: [{ type: "text", text: "ok" }, { type: "file", mime: "image/png", uri }] } }, ] } registerSessionMediaRoutes(app, { workspaceManager: { + get: () => workspace, + requireWorkspaceCapability: () => new AbortController().signal, + getSharedServiceConnection: async () => ({ endpoint: { url: "http://media.invalid" }, assertCurrent() {}, + fetch: async (input: string | URL | Request) => { + const path = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url).pathname + if (path.includes("/message/")) { + afterRead() + if (!path.endsWith(`/${message.id}`)) return new Response("{}", { status: 404 }) + return Response.json({ data: structuredClone(message) }) + } + return Response.json({ data: structuredClone(session) }) + }, client: OpenCode.make({ baseUrl: "http://unused.invalid", fetch: async () => { throw new Error("Unbounded client forbidden") } }), + }), ownsLocation: async () => owned, - getSharedServiceClient: async () => ({ session: { - get: async () => structuredClone(session), - message: { get: async ({ messageID }: any) => { afterRead(); if (messageID !== message.id) throw new Error("missing"); return structuredClone(message) } }, - } }) as any, } as any }) const url = (overrides: { message?: string; part?: string; index?: string; digest?: string } = {}) => `/api/workspaces/w/session-media/s/${overrides.message ?? "msg_2"}/${overrides.part ?? "1"}/${overrides.index ?? "1"}/${overrides.digest ?? mediaDigest(uri)}` diff --git a/packages/server/src/server/routes/session-media.ts b/packages/server/src/server/routes/session-media.ts index 0352c62222..d7dbf569bf 100644 --- a/packages/server/src/server/routes/session-media.ts +++ b/packages/server/src/server/routes/session-media.ts @@ -1,46 +1,93 @@ import type { FastifyInstance } from "fastify" +import { OpenCode } from "@opencode/client" import { readLocationRef, sameLocation } from "../../opencode/compatibility/location" import { isRenderableToolImage, mediaDigest, toolFile } from "../../opencode/session-media" -import type { HistoryRouteDeps } from "./session-history" +import type { WorkspaceManager } from "../../workspaces/manager" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" +import { boundedMediaFetch } from "../../opencode/session-media-fetch" +import { parseSessionMediaPath } from "../../opencode/session-media-contract" +import { isPassiveImageMime } from "../../opencode/embedded-asset" type MediaParams = { id: string; sessionId: string; messageId: string; part: string; index: string; digest: string } -const position = (value: string) => (/^\d{1,6}$/.test(value) ? Number(value) : undefined) - /** * Serves one tool image that a transcript page deferred (`opencode/session-media.ts`), * read from the owned session's native message and pinned by its digest. */ -export function registerSessionMediaRoutes(app: FastifyInstance, deps: Pick) { +export function registerSessionMediaRoutes(app: FastifyInstance, deps: { + workspaceManager: Pick +}) { app.get<{ Params: MediaParams }>("/api/workspaces/:id/session-media/:sessionId/:messageId/:part/:index/:digest", async (request, reply) => { - const { id, sessionId, messageId, digest } = request.params - const part = position(request.params.part), index = position(request.params.index) - if (part === undefined || index === undefined || !/^[a-f0-9]{64}$/.test(digest)) { - return reply.code(400).send({ error: "Invalid media reference" }) - } const controller = new AbortController() const abort = () => { if (!reply.raw.writableEnded) controller.abort() } reply.raw.once("close", abort) + if (request.raw.aborted || reply.raw.destroyed) controller.abort() try { - const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(30_000)]) - const client = await deps.workspaceManager.getSharedServiceClient() + controller.signal.throwIfAborted() + const { id, sessionId, messageId, digest } = request.params + const reference = parseSessionMediaPath((request.raw.url ?? "").split("?")[0]) + if (!reference) { + return reply.code(400).send({ error: "Invalid media reference" }) + } + const { part, index } = reference + const workspace = deps.workspaceManager.get(id) + if (!workspace) return reply.code(404).send({ error: "Workspace not found" }) + const workspaceSignal = deps.workspaceManager.requireWorkspaceCapability(id, "media") + const signal = AbortSignal.any([controller.signal, workspaceSignal, AbortSignal.timeout(30_000)]) + const explicit = workspace.binding?.serverId && workspace.binding.serverId !== "local-shared" + signal.throwIfAborted() + // Stop this observer's wait, leaving shared connection acquisition with its owner. + const pending = deps.workspaceManager.getSharedServiceConnection(id) + const connection = await new Promise>((resolve, reject) => { + const abort = () => { signal.removeEventListener("abort", abort); reject(signal.reason) } + signal.addEventListener("abort", abort, { once: true }) + pending.then(value => { + signal.removeEventListener("abort", abort) + if (signal.aborted) reject(signal.reason) + else resolve(value) + }, error => { signal.removeEventListener("abort", abort); reject(error) }) + if (signal.aborted) abort() + }) + if (!connection) return reply.code(503).send({ error: "Media unavailable" }) + const currentConnection = () => { + signal.throwIfAborted() + connection.assertCurrent() + const current = deps.workspaceManager.get(id) + if (explicit ? current?.binding !== workspace.binding : current !== workspace) throw new Error("Workspace changed") + deps.workspaceManager.requireWorkspaceCapability(id, "media") + } + const client = OpenCode.make({ baseUrl: connection.endpoint.url, fetch: boundedMediaFetch(connection.fetch, signal, currentConnection) }) + currentConnection() const session = await client.session.get({ sessionID: sessionId }, { signal }) - if (!await deps.workspaceManager.ownsLocation(id, session.location, client)) { + currentConnection() + const owns = async (value: typeof session) => { + currentConnection() + const owned = value.id === sessionId && (explicit + ? value.location.directory === workspace.binding!.directory && readLocationRef(value.location).workspaceID === undefined + : await deps.workspaceManager.ownsLocation(id, value.location, client, signal)) + currentConnection() + return owned + } + if (!await owns(session)) { return reply.code(403).send({ error: "Session does not belong to workspace" }) } const message = await client.session.message.get({ sessionID: sessionId, messageID: messageId }, { signal }) + currentConnection() // As for history reads: a session that moved during the read is refused, // and messages at or after an undo boundary are no longer its history. const current = await client.session.get({ sessionID: sessionId }, { signal }) + currentConnection() if (!sameLocation(readLocationRef(session.location), readLocationRef(current.location)) - || !await deps.workspaceManager.ownsLocation(id, current.location, client)) { + || !await owns(current)) { return reply.code(409).send({ error: "Session location changed" }) } const boundary = (current.revert as { messageID?: unknown } | null | undefined)?.messageID const file = toolFile(message, part, index) - if ((typeof boundary === "string" && messageId >= boundary) || !isRenderableToolImage(file) || mediaDigest(file.uri) !== digest) { + if (message.id !== messageId || (typeof boundary === "string" && messageId >= boundary) || !isRenderableToolImage(file) + || (explicit && !isPassiveImageMime(file.mime)) || mediaDigest(file.uri) !== digest) { return reply.code(404).send({ error: "Media not found" }) } + currentConnection() return reply .header("content-type", file.mime.toLowerCase()) // The digest in the path pins these bytes. @@ -48,7 +95,9 @@ export function registerSessionMediaRoutes(app: FastifyInstance, deps: Pick Promise = async () => {}) { window: () => ({ status: "window", messages: [], older: null, newer: null, resume: { kind: "latest" }, latest: true }), } registerSessionNavigationRoutes(app, { workspaceManager: { + requireWorkspaceCapability: () => new AbortController().signal, ownsLocation: async () => owned, desktopPluginsReady: pluginsReady, getSharedServiceClient: async () => ({ session: { get: async () => structuredClone(session) }, rpc: { diff --git a/packages/server/src/server/routes/session-navigation.ts b/packages/server/src/server/routes/session-navigation.ts index 8135fae194..9b405f4659 100644 --- a/packages/server/src/server/routes/session-navigation.ts +++ b/packages/server/src/server/routes/session-navigation.ts @@ -4,6 +4,7 @@ import { navigationWindowInputSchema, navigationWindowResultSchema, outlineInput import { locationRequestOptions, readLocationRef, sameLocation } from "../../opencode/compatibility/location" import { deferToolMedia, wantsDeferredMedia } from "../../opencode/session-media" import type { HistoryRouteDeps } from "./session-history" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" // The native SDK throws the declared RPC error body as the error's own fields. function isMethodNotFound(error: unknown) { @@ -19,6 +20,11 @@ export function registerSessionNavigationRoutes(app: FastifyInstance, deps: Pick app.post<{ Params: { id: string } }>(`/api/workspaces/:id/session-history/${method}`, { bodyLimit: method === "outline" ? 96 * 1024 : 8192 }, async (request, reply) => { const parsed = inputs[method].safeParse(request.body) if (!parsed.success) return reply.code(400).send({ error: "Invalid history navigation request" }) + try { deps.workspaceManager.requireWorkspaceCapability(request.params.id, "historyEnrichment") } + catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + throw error + } const client = await deps.workspaceManager.getSharedServiceClient() // The first timeline/history read after a backend start would otherwise // reach the plugin before it observed this backend and be refused. diff --git a/packages/server/src/server/routes/session-pruning.test.ts b/packages/server/src/server/routes/session-pruning.test.ts index 281384941c..61736a1553 100644 --- a/packages/server/src/server/routes/session-pruning.test.ts +++ b/packages/server/src/server/routes/session-pruning.test.ts @@ -12,6 +12,7 @@ function fixture(options: { owned?: boolean; output?: unknown; fail?: boolean; w const app = Fastify() const fence = new WorktreeDeletionFence() registerSessionPruningRoutes(app, { worktreeDeletionFence: fence, workspaceManager: { + requireWorkspaceCapability: () => new AbortController().signal, getServiceLocation: () => ({ directory: "/owned/worktree" }), getWorktrees: async () => ({ isGitRepo: false, worktrees: [] }), getSharedServiceClient: async () => ({ diff --git a/packages/server/src/server/routes/session-pruning.ts b/packages/server/src/server/routes/session-pruning.ts index c177009033..1ad92b27ec 100644 --- a/packages/server/src/server/routes/session-pruning.ts +++ b/packages/server/src/server/routes/session-pruning.ts @@ -4,6 +4,7 @@ import { locationRequestOptions, readLocationRef } from "../../opencode/compatib import { registerSessionHistoryRoutes, type HistoryRouteDeps } from "./session-history" import { registerSessionNavigationRoutes } from "./session-navigation" import { assertOrdinaryMissionScheduleSession } from "../mission-schedule-input-guard" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" export function registerSessionPruningRoutes(app: FastifyInstance, deps: HistoryRouteDeps): void { registerSessionHistoryRoutes(app, deps) @@ -12,6 +13,11 @@ export function registerSessionPruningRoutes(app: FastifyInstance, deps: History app.post<{ Params: { id: string } }>(`/api/workspaces/:id/session-pruning/${method}`, { bodyLimit: 1024 * 1024 }, async (request, reply) => { const input = (method === "prune" ? pruneRequestSchema : messageTargetSchema).safeParse(request.body) if (!input.success) return reply.code(400).send({ error: "Invalid pruning request" }) + try { deps.workspaceManager.requireWorkspaceCapability(request.params.id, "sessionPruning") } + catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + throw error + } const client = await deps.workspaceManager.getSharedServiceClient() // Before authorization: ownership checks and fence entry must stay adjacent. await deps.workspaceManager.desktopPluginsReady() diff --git a/packages/server/src/server/routes/settings.test.ts b/packages/server/src/server/routes/settings.test.ts index 1285242c05..4ee7582c98 100644 --- a/packages/server/src/server/routes/settings.test.ts +++ b/packages/server/src/server/routes/settings.test.ts @@ -2,8 +2,74 @@ import assert from "node:assert/strict" import { describe, it } from "node:test" import { enforceSpeechCredentialPairing, registerSettingsRoutes } from "./settings" import Fastify from "fastify" -import type { SettingsService } from "../../settings/service" import type { Logger } from "../../logger" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { SettingsService } from "../../settings/service" +import { resolveConfigLocation } from "../../config/location" + +it("host PATCH routes reject registry writes, ancestors and conditional/encoded variants atomically", async t => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "codenomad-settings-registry-")) + t.after(() => fs.rmSync(directory, { recursive: true, force: true })) + const location = resolveConfigLocation(path.join(directory, "config.yaml")) + const events: unknown[] = [] + const logger = { child: () => logger, warn() {}, info() {} } + const settings = new SettingsService(location, { publish: (value: unknown) => events.push(value) } as never, logger as never) + settings.mergePatchDoc("config", { server: { logLevel: "INFO" }, ui: { theme: "light" } }) + const app = Fastify() + t.after(() => app.close()) + registerSettingsRoutes(app, { settings, logger: logger as never }) + const profiles = [{ kind: "explicit", id: "remote", label: "Remote", origin: "https://example.test" }] + const legacyFile = fs.readFileSync(location.configYamlPath, "utf8") + const legacyEvents = events.length + for (const [url, payload] of [["/api/storage/config", { server: { opencodeServers: profiles } }], + ["/api/storage/config/server", { opencodeServers: profiles }]] as const) { + assert.equal((await app.inject({ method: "PATCH", url, payload })).statusCode, 400) + assert.equal(fs.readFileSync(location.configYamlPath, "utf8"), legacyFile) + assert.equal(events.length, legacyEvents) + } + // Exercise both addition to an old document and modification/removal of existing metadata. + for (const existing of [[], profiles]) { + settings.getOpenCodeServerRegistry().replace(existing) + const before = fs.readFileSync(location.configYamlPath, "utf8") + const eventCount = events.length + for (const patch of [{ opencodeServers: profiles }, { opencodeServers: [{ ...profiles[0], credentialRef: "rotation" }] }, + { opencodeServers: null }, { opencodeServers: {} }, { opencodeServers: [] }, + { opencodeServers: [], logLevel: "ERROR" }, null, [], "replace"]) { + for (const [url, body] of [ + ["/api/storage/config", { server: patch, ui: { theme: "dark" } }], + ["/api/storage/config/server", patch], + ["/%61pi/storage/config", { server: patch }], + ["/api/storage/config/%73erver", patch], + ["/api/storage/config/server?conditional=missions-v1", patch], + ["/api/storage/config/%73erver?conditional=other", patch], + ["/api/storage/config/ui?conditional=missions-v1", { patch: { server: patch }, expected: [] }], + ] as const) { + const response = await app.inject({ method: "PATCH", url, + headers: { "content-type": "application/json" }, payload: JSON.stringify(body) }) + assert.equal(response.statusCode, 400, `${url}: ${response.body}`) + assert.equal(fs.readFileSync(location.configYamlPath, "utf8"), before) + assert.equal(events.length, eventCount) + } + } + for (const body of [null, [], "replace"]) { + const response = await app.inject({ method: "PATCH", url: "/api/storage/config", + headers: { "content-type": "application/json" }, payload: JSON.stringify(body) }) + assert.equal(response.statusCode, 400) + assert.equal(fs.readFileSync(location.configYamlPath, "utf8"), before) + assert.equal(events.length, eventCount) + } + for (const [url, body] of [["/api/storage/config", { server: { logLevel: "WARN" } }], + ["/api/storage/config/server", { logLevel: "INFO" }]] as const) { + const response = await app.inject({ method: "PATCH", url, payload: body }) + assert.equal(response.statusCode, 200, response.body) + assert.doesNotMatch(response.body, /sentinel-reference|credentialRef/) + assert.deepEqual(settings.getRawConfigOwner("server").opencodeServers, existing) + } + } + assert.doesNotMatch(JSON.stringify(events), /sentinel-reference|credentialRef/) +}) describe("enforceSpeechCredentialPairing", () => { it("clears shared key when baseUrl differs from stored", () => { diff --git a/packages/server/src/server/routes/settings.ts b/packages/server/src/server/routes/settings.ts index eb39adf5be..5eff46012c 100644 --- a/packages/server/src/server/routes/settings.ts +++ b/packages/server/src/server/routes/settings.ts @@ -8,6 +8,8 @@ import { sanitizeConfigDoc, sanitizeConfigOwner } from "../../settings/public-co import { resolveDefaultInstallation } from "../../opencode-update/shared-installation" import { applyConditionalMissionPreferences, MissionPreferenceConflictError } from "../../settings/mission-preference-condition" import { SettingsReadError } from "../../settings/yaml-doc-store" +import { isPlainObject } from "../../settings/merge-patch" +import { assertOpenCodeServersPatch } from "../../settings/protected-config" interface RouteDeps { settings: SettingsService @@ -25,7 +27,7 @@ function validateBinaryPath(binaryPath: string): Promise } export function enforceSpeechCredentialPairing(body: unknown, currentSpeech?: unknown): unknown { - if (!body || typeof body !== "object") return body + if (!isPlainObject(body)) return body const patch = { ...(body as Record) } const speech = patch.speech if (!speech || typeof speech !== "object") return patch @@ -63,11 +65,12 @@ export function registerSettingsRoutes(app: FastifyInstance, deps: RouteDeps) { app.get("/api/storage/config", async () => sanitizeConfigDoc(deps.settings.getDoc("config"))) app.patch("/api/storage/config", async (request, reply) => { try { - let body = request.body ?? {} + let body = request.body === undefined ? {} : request.body + assertOpenCodeServersPatch({ server: deps.settings.getRawConfigOwner("server") }, body) if (body && typeof body === "object" && "server" in body) { const bodyObj = { ...(body as Record) } const serverPatch = bodyObj.server - if (serverPatch && typeof serverPatch === "object") { + if (isPlainObject(serverPatch)) { const currentServer = deps.settings.getOwner("config", "server") bodyObj.server = enforceSpeechCredentialPairing(serverPatch, currentServer) } @@ -98,6 +101,9 @@ export function registerSettingsRoutes(app: FastifyInstance, deps: RouteDeps) { app.patch<{ Params: { owner: string }; Querystring: { conditional?: unknown } }>("/api/storage/config/:owner", async (request, reply) => { try { + if (request.params.owner === "server") { + assertOpenCodeServersPatch(deps.settings.getRawConfigOwner("server"), request.body === undefined ? {} : request.body, "server") + } if (Object.prototype.hasOwnProperty.call(request.query, "conditional")) { if (request.query.conditional !== "missions-v1") throw new Error("Unknown conditional patch mode") return sanitizeConfigOwner( @@ -109,8 +115,8 @@ export function registerSettingsRoutes(app: FastifyInstance, deps: RouteDeps) { ? deps.settings.getOwner("config", "server") : undefined const processed = request.params.owner === "server" - ? enforceSpeechCredentialPairing(request.body ?? {}, currentOwner) - : request.body ?? {} + ? enforceSpeechCredentialPairing(request.body === undefined ? {} : request.body, currentOwner) + : request.body === undefined ? {} : request.body const saved = deps.settings.mergePatchOwner("config", request.params.owner, processed) if (request.params.owner === "server" && processed && typeof processed === "object" && "opencodeBinary" in processed) await refreshLoginStart(deps) diff --git a/packages/server/src/server/routes/subagent-depth-settings.ts b/packages/server/src/server/routes/subagent-depth-settings.ts index 857d9d268c..353b30f03e 100644 --- a/packages/server/src/server/routes/subagent-depth-settings.ts +++ b/packages/server/src/server/routes/subagent-depth-settings.ts @@ -2,6 +2,7 @@ import type { FastifyInstance, FastifyReply } from "fastify" import { z } from "zod" import { PluginControlsError } from "../../opencode/plugin-controls" import type { SubagentDepthSettings } from "../../opencode/subagent-depth-settings" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" const Location = z.object({ directory: z.string().trim().min(1).max(32_768) }).strict() const Mutation = z.object({ location: Location, depth: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).nullable(), @@ -26,6 +27,7 @@ export function registerSubagentDepthSettingsRoutes(app: FastifyInstance, settin } function fail(error: unknown, reply: FastifyReply) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) if (error instanceof PluginControlsError) { const status = { "not-found": 404, forbidden: 403, invalid: 422, conflict: 409, unavailable: 503 }[error.kind] return reply.code(status).send({ error: error.message }) diff --git a/packages/server/src/server/routes/temporary-workspaces.test.ts b/packages/server/src/server/routes/temporary-workspaces.test.ts new file mode 100644 index 0000000000..bd1581c70d --- /dev/null +++ b/packages/server/src/server/routes/temporary-workspaces.test.ts @@ -0,0 +1,81 @@ +import assert from "node:assert/strict" +import { mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises" +import os from "node:os" +import path from "node:path" +import { test } from "node:test" +import Fastify from "fastify" +import type { EventBus } from "../../events/bus" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" +import type { WorkspaceManager } from "../../workspaces/manager" +import { TemporaryFolderRegistry } from "../../workspaces/temporary-workspaces" +import { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" +import { registerTemporaryWorkspaceRoutes } from "./temporary-workspaces" + +test("temporary routes refuse explicit intents and host registry collisions before side effects", async () => { + const base = await mkdtemp(path.join(os.tmpdir(), "codenomad-temp-routes-")) + const registry = await TemporaryFolderRegistry.open(path.join(base, "folders"), path.join(base, "registry.json")) + const effects: string[] = [] + const workspaces = new Map() + const manager = { + temporaryFolders: registry, + get: (id: string) => workspaces.get(id), + requireWorkspaceCapability(id: string, capability: string) { + assert.equal(capability, "worktrees") + if (id !== "local") throw new WorkspaceCapabilityError("worktrees", { code: "deferred" }) + return new AbortController().signal + }, + clearTemporary: () => effects.push("clear"), + list: () => { effects.push("list"); return [...workspaces.values()] }, + getSharedServiceClient: () => { throw new Error("native acquisition forbidden") }, + } as unknown as WorkspaceManager + const app = Fastify() + registerTemporaryWorkspaceRoutes(app, { + workspaceManager: manager, worktreeDeletionFence: new WorktreeDeletionFence(), + eventBus: { publish: () => effects.push("publish") } as unknown as EventBus, + }) + try { + const created = await app.inject({ method: "POST", url: "/api/workspaces/temporary", payload: {} }) + assert.equal(created.statusCode, 201) + const folder = created.json().path + await writeFile(path.join(folder, "sentinel"), "local") + for (const id of ["local", "A", "B"]) workspaces.set(id, { id, path: folder }) + effects.length = 0 + for (const id of ["A", "B", "unknown"]) { + for (const [url, payload] of [ + ["/api/workspaces/temporary", { serverId: id }], + ["/api/workspaces/temporary/abandon", { serverId: id, path: folder }], + ...(id === "unknown" ? [] : [ + [`/api/workspaces/${id}/keep`, {}], [`/api/workspaces/${id}/discard`, {}], + ]), + ] as Array<[string, object]>) { + const response = await app.inject({ method: "POST", url, payload }) + assert.equal(response.statusCode, 403) + assert.deepEqual(response.json(), { error: "explicit_capability_unavailable", code: "explicit_capability_unavailable", capability: "worktrees", reason: { code: "deferred" } }) + } + } + for (const intent of [ + { binding: { serverId: "A", directory: folder } }, + { binding: { serverId: "B", directory: folder }, serverId: "local-shared" }, + { workspace: "A" }, + { target: { serverId: "B" } }, + ]) { + for (const [url, payload] of [ + ["/api/workspaces/temporary", intent], + ["/api/workspaces/temporary/abandon", { ...intent, path: folder }], + ] as Array<[string, object]>) { + const response = await app.inject({ method: "POST", url, payload }) + assert.equal(response.statusCode, 400, response.body) + } + } + assert.deepEqual(effects, []) + assert.deepEqual(registry.list(), [folder]) + assert.deepEqual(await readdir(registry.root), [path.basename(folder)]) + assert.equal(await readFile(path.join(folder, "sentinel"), "utf8"), "local") + assert.equal((await app.inject({ method: "POST", url: "/api/workspaces/local/keep" })).statusCode, 204) + assert.deepEqual(registry.list(), []) + assert.ok((await stat(folder)).isDirectory()) + } finally { + await app.close() + await rm(base, { recursive: true, force: true }) + } +}) diff --git a/packages/server/src/server/routes/temporary-workspaces.ts b/packages/server/src/server/routes/temporary-workspaces.ts index 8bee57cac6..ddaaa51d8e 100644 --- a/packages/server/src/server/routes/temporary-workspaces.ts +++ b/packages/server/src/server/routes/temporary-workspaces.ts @@ -1,9 +1,11 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify" import { z } from "zod" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" import type { EventBus } from "../../events/bus" import type { WorkspaceManager } from "../../workspaces/manager" import type { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" import { TemporaryWorkspaceError, TemporaryWorkspaces } from "../../workspaces/temporary-workspaces" +import { hostOnlyQuery } from "./host-only-query" interface RouteDeps { workspaceManager: WorkspaceManager @@ -11,9 +13,16 @@ interface RouteDeps { eventBus: EventBus } -const AbandonSchema = z.object({ path: z.string().min(1) }) +const TargetSchema = z.object({ serverId: z.string().optional() }).strict() +const AbandonSchema = TargetSchema.extend({ path: z.string().min(1) }) const DiscardSchema = z.object({ onlyIfEmpty: z.boolean().optional() }) +function requireLocalTarget({ serverId }: z.infer) { + if (serverId !== undefined && serverId !== "local-shared") { + throw new WorkspaceCapabilityError("worktrees", { code: "deferred" }) + } +} + export function registerTemporaryWorkspaceRoutes(app: FastifyInstance, deps: RouteDeps) { const registry = deps.workspaceManager.temporaryFolders const temporary = registry @@ -28,6 +37,10 @@ export function registerTemporaryWorkspaceRoutes(app: FastifyInstance, deps: Rou // `error` carries a stable code the client localizes; `message` is diagnostic. const fail = (request: FastifyRequest, reply: FastifyReply, error: unknown, message: string) => { request.log.error({ err: error }, message) + if (error instanceof WorkspaceCapabilityError) { + return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + } + if (error instanceof z.ZodError) return reply.code(400).send({ error: "Invalid temporary workspace request" }) if (error instanceof TemporaryWorkspaceError) { return reply.code(error.statusCode).send({ error: error.code, message: error.message }) } @@ -38,9 +51,10 @@ export function registerTemporaryWorkspaceRoutes(app: FastifyInstance, deps: Rou app.get("/api/workspaces/temporary", async () => ({ folders: temporary?.list() ?? [] })) // Only the folder is created here; the client opens it like any other folder. - app.post("/api/workspaces/temporary", async (request, reply) => { + app.post("/api/workspaces/temporary", { preHandler: hostOnlyQuery("worktrees") }, async (request, reply) => { if (!temporary) return unavailable(reply) try { + requireLocalTarget(TargetSchema.parse(request.body ?? {})) reply.code(201) return { path: await temporary.createFolder() } } catch (error) { @@ -48,10 +62,12 @@ export function registerTemporaryWorkspaceRoutes(app: FastifyInstance, deps: Rou } }) - app.post("/api/workspaces/temporary/abandon", async (request, reply) => { + app.post("/api/workspaces/temporary/abandon", { preHandler: hostOnlyQuery("worktrees") }, async (request, reply) => { if (!temporary) return unavailable(reply) try { - await temporary.abandonFolder(AbandonSchema.parse(request.body ?? {}).path) + const body = AbandonSchema.parse(request.body ?? {}) + requireLocalTarget(body) + await temporary.abandonFolder(body.path) return reply.code(204).send() } catch (error) { return fail(request, reply, error, "Unable to remove the unused temporary folder") diff --git a/packages/server/src/server/routes/usage.test.ts b/packages/server/src/server/routes/usage.test.ts index 8d777f6b0b..4a9d236642 100644 --- a/packages/server/src/server/routes/usage.test.ts +++ b/packages/server/src/server/routes/usage.test.ts @@ -57,6 +57,7 @@ function harness() { } }) const connection = { client, assertCurrent: () => { if (state.stale) throw new Error("stale connection") } } as ServiceConnection const manager: UsageRouteDeps["workspaceManager"] = { + requireWorkspaceCapability: () => new AbortController().signal, get: id => id === "instance" ? workspace : undefined, getSharedServiceConnection: async () => connection, ownsLocation: async (_id, location) => location.directory === "/wsl/repo", diff --git a/packages/server/src/server/routes/usage.ts b/packages/server/src/server/routes/usage.ts index 18f4e19402..5ace5d1498 100644 --- a/packages/server/src/server/routes/usage.ts +++ b/packages/server/src/server/routes/usage.ts @@ -8,6 +8,9 @@ import { readUsageCredentials } from "../../usage/native-credentials" import { getProviderUsage, resolveUsageProvider } from "../../usage/service" import { estimateOpenCodeFreeUsage, isOpenCodeFreeModel, openCodeFreeWindow } from "../../usage/opencode-free-estimate" import type { ServiceConnection } from "../../workspaces/opencode-service" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" +import { readJson } from "../../opencode/servers/remote-workspace" +import type { ProviderUsageResponse } from "../../api-types" const UsageParamsSchema = z.object({ providerId: z.string().trim().min(1) }) const UsageQuerySchema = z.object({ @@ -17,7 +20,8 @@ const UsageQuerySchema = z.object({ export interface UsageRouteDeps { workspaceManager: Pick + | "getSessionEnvironment" | "getServiceWslDistro" | "getHostPathForServicePath" | "requireWorkspaceCapability"> + & Partial> } // opencode-claude and OpenCode's Claude Agent run Claude Code inside the daemon, @@ -45,6 +49,11 @@ export function registerUsageRoutes(app: FastifyInstance, deps: UsageRouteDeps) if (!params.success || !query.success) return reply.code(400).send({ error: "Invalid usage request" }) const { instanceId, sessionId, modelId } = query.data const manager = deps.workspaceManager + try { manager.requireWorkspaceCapability(instanceId, "providerUsage") } + catch (error) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + throw error + } const workspace = manager.get(instanceId) if (!workspace) return reply.code(404).send({ error: "Workspace not found" }) const controller = new AbortController() @@ -67,6 +76,20 @@ export function registerUsageRoutes(app: FastifyInstance, deps: UsageRouteDeps) signal.throwIfAborted() connection.assertCurrent() const free = isOpenCodeFreeModel(params.data.providerId, modelId) + // prototype-1236: an explicit server publishes only its own quotas; its credentials are never read. + if (manager.isExplicitWorkspace?.(instanceId)) { + const usage = free ? await openCodeFreeUsage(connection, params.data.providerId, modelId, signal) + : await publishedServerUsage(connection, params.data.providerId, location.directory, modelId, signal) + const current = await connection.client.session.get({ sessionID: sessionId }, { signal }) + connection.assertCurrent() + signal.throwIfAborted() + // Explicit descriptors are fresh snapshots; their frozen binding is the occurrence identity. + if (manager.get(instanceId)?.binding !== workspace.binding || readLocationRef(current.location).directory !== location.directory + || !await manager.ownsLocation(instanceId, readLocationRef(current.location), connection.client)) { + return reply.code(403).send({ error: "Session does not belong to workspace" }) + } + return usage + } const provider = free ? null : resolveUsageProvider(params.data.providerId) const native = free ? await openCodeFreeUsage(connection, params.data.providerId, modelId, signal) : !provider || provider.id === "codex" @@ -121,6 +144,25 @@ export function registerUsageRoutes(app: FastifyInstance, deps: UsageRouteDeps) ) } +// prototype-1236: OpenCode Go meters the server publishes for its Console workspace; nothing else is supported. +async function publishedServerUsage(connection: ServiceConnection, providerId: string, directory: string, modelId: string | undefined, signal: AbortSignal): Promise { + const base = { requestedProviderId: providerId, providerId: null, providerName: providerId, ...(modelId ? { modelId } : {}), windows: {}, fetchedAt: Date.now() } + const provider = resolveUsageProvider(providerId) + if (provider?.id !== "opencode-go") return { ...base, supported: false, configured: false, ok: false } + const named = { ...base, providerId: provider.id, providerName: provider.name } + const limits = await readJson(connection, "/api/experimental/usage/limits", {}, directory, signal).catch(() => undefined) + if (!limits) return { ...named, supported: true, configured: true, ok: false } + const go = limits.data?.go + if (!go) return { ...named, supported: true, configured: false, ok: false } + const windows: ProviderUsageResponse["windows"] = {} + for (const [label, seconds, meter] of [["5h", 18_000, go.rolling], ["weekly", 604_800, go.weekly], ["monthly", 2_592_000, go.monthly]] as const) { + if (!meter || typeof meter.percent !== "number") continue + const used = meter.limited ? 100 : Math.max(0, Math.min(100, meter.percent)) + windows[label] = { usedPercent: used, remainingPercent: 100 - used, windowSeconds: seconds, resetAt: Number.isFinite(meter.resetsAt) ? meter.resetsAt : null } + } + return { ...named, supported: true, configured: true, ok: Object.keys(windows).length > 0, windows } +} + async function openCodeFreeUsage(connection: ServiceConnection, providerId: string, modelId: string | undefined, signal: AbortSignal) { const now = Date.now(), { from, to } = openCodeFreeWindow(now) const stats = to === from ? { models: [] } : await connection.client.session.stats({ from, to, timezone: "UTC", tools: "none" }, { signal }) diff --git a/packages/server/src/server/routes/websearch-settings.ts b/packages/server/src/server/routes/websearch-settings.ts index 69969162ed..98e84c88e7 100644 --- a/packages/server/src/server/routes/websearch-settings.ts +++ b/packages/server/src/server/routes/websearch-settings.ts @@ -2,6 +2,7 @@ import type { FastifyInstance, FastifyReply } from "fastify" import { z } from "zod" import { PluginControlsError } from "../../opencode/plugin-controls" import type { WebSearchSettings } from "../../opencode/websearch-settings" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" const Location = z.object({ directory: z.string().trim().min(1).max(32_768) }).strict() const Mutation = z.object({ location: Location, scope: z.enum(["global", "project"]), @@ -26,6 +27,7 @@ export function registerWebSearchSettingsRoutes(app: FastifyInstance, settings: } function fail(error: unknown, reply: FastifyReply) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) if (error instanceof PluginControlsError) { const code = { "not-found": 404, forbidden: 403, invalid: 422, conflict: 409, unavailable: 503 }[error.kind] return reply.code(code).send({ error: error.message }) diff --git a/packages/server/src/server/routes/workspaces.test.ts b/packages/server/src/server/routes/workspaces.test.ts index 21609c7aa0..85be9ae4c8 100644 --- a/packages/server/src/server/routes/workspaces.test.ts +++ b/packages/server/src/server/routes/workspaces.test.ts @@ -9,6 +9,24 @@ import { registerWorkspaceRoutes } from "./workspaces" import { WorkspaceSearchBusyError } from "../../filesystem/search-cache" describe("workspace routes", () => { + // prototype-1236: explicit targets reach the manager's ExplicitWorkspace owner, which refuses unknown servers. + it("hands explicit targets to the manager and keeps local opening unchanged", async () => { + const app = Fastify() + const calls: Array = [] + const workspaceManager = { create: async (_path: string, _name: string, options: { serverId?: string }) => { + calls.push(options.serverId) + if (options.serverId === "unknown") throw new Error("unknown_server") + return { created: true, workspace: { id: "workspace" } } + } } as unknown as WorkspaceManager + registerWorkspaceRoutes(app, { workspaceManager, worktreeDeletionFence: new WorktreeDeletionFence() }) + try { + assert.equal((await app.inject({ method: "POST", url: "/api/workspaces", payload: { path: "/remote", serverId: "explicit-loopback" } })).statusCode, 201) + assert.equal((await app.inject({ method: "POST", url: "/api/workspaces", payload: { path: "/remote", serverId: "unknown" } })).statusCode, 400) + assert.equal((await app.inject({ method: "POST", url: "/api/workspaces", payload: { path: "/local", serverId: "local-shared" } })).statusCode, 201) + assert.equal((await app.inject({ method: "POST", url: "/api/workspaces", payload: { path: "/local" } })).statusCode, 201) + assert.deepEqual(calls, ["explicit-loopback", "unknown", undefined, undefined]) + } finally { await app.close() } + }) it("awaits file writes and reports bounded search admission as retryable", async () => { const app = Fastify() let release!: () => void @@ -16,6 +34,7 @@ describe("workspace routes", () => { const gate = new Promise((resolve) => { release = resolve }) const entered = new Promise((resolve) => { started = resolve }) const workspaceManager = { + requireWorkspaceCapability: () => new AbortController().signal, get: () => ({ id: "test", path: "/private/root" }), getWorktreeIdentityForPath: async () => "/private/root", writeFile: async () => { started(); await gate; throw new Error("disk write failed") }, @@ -47,6 +66,7 @@ describe("workspace routes", () => { let writes = 0 const identities: string[] = [] const workspaceManager = { + requireWorkspaceCapability: () => new AbortController().signal, get: (id: string) => id === "test" ? { id, path: "/private/root" } : undefined, getWorktreeIdentityForPath: async (_id: string, directory: string) => { identities.push(directory); return directory }, writeFile: async () => { writes++ }, @@ -77,6 +97,7 @@ describe("workspace routes", () => { const gate = new Promise(resolve => { release = resolve }) const entered = new Promise(resolve => { started = resolve }) const workspaceManager = { + requireWorkspaceCapability: () => new AbortController().signal, get: () => ({ id: "test", path: "/private/root" }), getWorktreeIdentityForPath: async () => "/private/root", writeFile: async () => { started(); await gate }, @@ -111,6 +132,7 @@ describe("workspace routes", () => { updatedAt: "2026-01-01T00:00:00.000Z", } const workspaceManager = { + requireWorkspaceCapability: () => new AbortController().signal, create: async (...args: unknown[]) => { calls.push(args) return { workspace: descriptor, created: true } @@ -172,6 +194,7 @@ describe("workspace routes", () => { const started = new Promise((resolve) => { cancellationStarted = resolve }) const deletion = new Promise((resolve) => { finishDeletion = resolve }) const workspaceManager = { + requireWorkspaceCapability: () => new AbortController().signal, cancelCreationRequest: async () => { state = "cancelled" cancellationStarted() @@ -220,6 +243,7 @@ describe("workspace routes", () => { } let ownerRequestId: string | undefined const workspaceManager = { + requireWorkspaceCapability: () => new AbortController().signal, create: async (_path: string, _name: string | undefined, options: { requestId?: string }) => { const owner = ownerRequestId === undefined ownerRequestId ??= options.requestId diff --git a/packages/server/src/server/routes/workspaces.ts b/packages/server/src/server/routes/workspaces.ts index 1b916a5194..fc73e01c45 100644 --- a/packages/server/src/server/routes/workspaces.ts +++ b/packages/server/src/server/routes/workspaces.ts @@ -14,6 +14,10 @@ import { UnsupportedOpenCodeError } from "../../opencode/runtime-support" import { GitRequiredError } from "../../workspaces/git-requirement" import { getGitHistory, getGitCommit, getGitCommitDiff } from "../../workspaces/git-history" import { getLocalGitBranches } from "../../workspaces/git-branches" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" +import { + listRemoteFiles, readRemoteFile, remoteGitDiff, remoteGitStatus, RemoteWorkspaceError, searchRemoteFiles, +} from "../../opencode/servers/remote-workspace" interface RouteDeps { workspaceManager: WorkspaceManager @@ -22,15 +26,17 @@ interface RouteDeps { const WorkspaceCreateSchema = z.object({ path: z.string(), + serverId: z.string().min(1).optional(), name: z.string().optional(), requestId: z.string().trim().min(1).max(128).optional(), }) const WorkspaceCloneSchema = z.object({ + serverId: z.string().optional(), repositoryUrl: z.string().trim().min(1, "Repository URL is required"), destinationPath: z.string().trim().min(1, "Destination path is required"), cleanup: z.boolean().optional(), -}) +}).strict() const WorkspaceCreationReleaseSchema = z.object({ requestId: z.string().trim().min(1).max(128), @@ -77,12 +83,25 @@ const WorkspaceFileSearchQuerySchema = z.object({ .transform((value) => (value === undefined ? undefined : value === "true")), }) +// prototype-1236: an explicit project reads Files and Changes through its server, never the host disk or Git. +async function explicitScope(deps: RouteDeps, id: string, capability: "files" | "git", directory?: string) { + const scope = await deps.workspaceManager.explicitReadScope?.(id, capability) + if (!scope) return undefined + if (directory !== undefined && directory !== scope.directory) throw new WorkspaceCapabilityError(capability, { code: "deferred" }) + return { ...scope, signal: AbortSignal.any([scope.signal, AbortSignal.timeout(20_000)]) } +} + +function refuseExplicit(deps: RouteDeps, id: string, capability: "files" | "git") { + if (deps.workspaceManager.isExplicitWorkspace?.(id)) throw new WorkspaceCapabilityError(capability, { code: "deferred" }) +} + export function registerWorkspaceRoutes(app: FastifyInstance, deps: RouteDeps) { app.get<{ Params: { id: string } }>("/api/workspaces/:id/git-branches", async (request, reply) => { try { const { directory } = z.object({ directory: z.string().min(1).max(4096) }).strict().parse(request.query) const id = request.params.id, workspace = deps.workspaceManager.get(id) if (!workspace) return reply.code(404).send({ error: "Workspace not found" }) + refuseExplicit(deps, id, "git") const owned = await deps.workspaceManager.getServiceDirectoryForPath(id, directory) const host = owned && await deps.workspaceManager.getHostPathForServicePath(id, owned) const identity = host && await deps.workspaceManager.getWorktreeIdentityForPath(id, host) @@ -100,6 +119,8 @@ export function registerWorkspaceRoutes(app: FastifyInstance, deps: RouteDeps) { app.get<{ Params: { id: string } }>("/api/workspaces/:id/files/preview", async (request, reply) => { try { const query = z.object({ path: z.string().min(1), directory: z.string().min(1).optional() }).parse(request.query) + const remote = await explicitScope(deps, request.params.id, "files", query.directory) + if (remote) return await readRemoteFile(remote.connection, request.params.id, remote.directory, query.path, "base64", remote.signal) return await deps.workspaceManager.previewFile(request.params.id, query.path, query.directory) } catch (error) { return handleWorkspaceError(error, reply) } }) @@ -129,8 +150,10 @@ export function registerWorkspaceRoutes(app: FastifyInstance, deps: RouteDeps) { app.post("/api/workspaces", async (request, reply) => { try { const body = WorkspaceCreateSchema.parse(request.body ?? {}) + // prototype-1236: explicit opening reaches the existing ExplicitWorkspace owner. const result = await deps.workspaceManager.create(body.path, body.name, { requestId: body.requestId, + ...(body.serverId !== undefined && body.serverId !== "local-shared" ? { serverId: body.serverId } : {}), }) reply.code(201) return result.created ? result.workspace : { ...result.workspace, reused: true as const } @@ -199,6 +222,8 @@ export function registerWorkspaceRoutes(app: FastifyInstance, deps: RouteDeps) { }>("/api/workspaces/:id/files", async (request, reply) => { try { const query = WorkspaceFilesQuerySchema.parse(request.query ?? {}) + const remote = await explicitScope(deps, request.params.id, "files", query.directory) + if (remote) return await listRemoteFiles(remote.connection, remote.directory, query.path ?? ".", remote.signal) return await deps.workspaceManager.listFiles(request.params.id, query.path ?? ".", query.directory) } catch (error) { return handleWorkspaceError(error, reply) @@ -211,6 +236,8 @@ export function registerWorkspaceRoutes(app: FastifyInstance, deps: RouteDeps) { }>("/api/workspaces/:id/files/search", async (request, reply) => { try { const query = WorkspaceFileSearchQuerySchema.parse(request.query ?? {}) + const remote = await explicitScope(deps, request.params.id, "files", query.directory) + if (remote) return await searchRemoteFiles(remote.connection, remote.directory, query.q, { limit: query.limit, type: query.type }, remote.signal) return await deps.workspaceManager.searchFiles(request.params.id, query.q, { limit: query.limit, type: query.type, @@ -231,6 +258,10 @@ export function registerWorkspaceRoutes(app: FastifyInstance, deps: RouteDeps) { }>("/api/workspaces/:id/files/content", async (request, reply) => { try { const query = WorkspaceFileContentQuerySchema.parse(request.query ?? {}) + deps.workspaceManager.requireWorkspaceCapability(request.params.id, "files") + if (query.worktree && query.worktree !== "root") refuseExplicit(deps, request.params.id, "files") + const remote = await explicitScope(deps, request.params.id, "files", query.directory) + if (remote) return await readRemoteFile(remote.connection, request.params.id, remote.directory, query.path, query.encoding ?? "utf-8", remote.signal) if (query.worktree && query.worktree !== "root") { const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, query.worktree, request.log, reply) if (!directory) return @@ -249,6 +280,8 @@ export function registerWorkspaceRoutes(app: FastifyInstance, deps: RouteDeps) { try { const query = WorkspaceFileContentQuerySchema.parse(request.query ?? {}) const body = WorkspaceFileContentBodySchema.parse(request.body ?? {}) + deps.workspaceManager.requireWorkspaceCapability(request.params.id, "files") + refuseExplicit(deps, request.params.id, "files") if (query.directory) { const directory = query.directory const mutation = await runWorktreeMutation(deps, request.params.id, directory, reply, async () => { @@ -285,6 +318,8 @@ export function registerWorkspaceRoutes(app: FastifyInstance, deps: RouteDeps) { Querystring: { hideWhitespace?: string } }>("/api/workspaces/:id/worktrees/:slug/git-status", async (request, reply) => { try { + const remote = request.params.slug === "root" ? await explicitScope(deps, request.params.id, "git") : undefined + if (remote) return await remoteGitStatus(remote.connection, remote.directory, remote.signal) const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, request.params.slug, request.log, reply) if (!directory) return @@ -300,6 +335,8 @@ export function registerWorkspaceRoutes(app: FastifyInstance, deps: RouteDeps) { }>("/api/workspaces/:id/worktrees/:slug/git-diff", async (request, reply) => { try { const query = WorktreeGitDiffQuerySchema.parse(request.query ?? {}) + const remote = request.params.slug === "root" && query.scope === "unstaged" ? await explicitScope(deps, request.params.id, "git") : undefined + if (remote) return await remoteGitDiff(remote.connection, remote.directory, query.path, remote.signal) const directory = await resolveGitWorktreeDirectory(deps.workspaceManager, request.params.id, request.params.slug, request.log, reply) if (!directory) return @@ -382,6 +419,8 @@ export function registerWorkspaceRoutes(app: FastifyInstance, deps: RouteDeps) { const body = z.object({ directory: z.string().trim().min(1) }).parse(request.body ?? {}) const workspace = deps.workspaceManager.get(request.params.id) if (!workspace) return reply.code(404).send({ error: "Workspace not found" }) + deps.workspaceManager.requireWorkspaceCapability(workspace.id, "git") + refuseExplicit(deps, workspace.id, "git") const [target, root] = await Promise.all([realpath(body.directory).catch(() => undefined), realpath(workspace.path).catch(() => undefined)]) if (!target || target !== root) { return reply.code(409).send({ error: "Only the opened folder can be initialized", code: "git_init_directory_mismatch" }) @@ -439,6 +478,9 @@ async function resolveGitWorktreeDirectory( return null } + workspaceManager.requireWorkspaceCapability(workspaceId, "git") + // prototype-1236: no host Git for an explicit project; its native reads are handled above. + if (workspaceManager.isExplicitWorkspace?.(workspaceId)) throw new WorkspaceCapabilityError("git", { code: "deferred" }) const gitAvailable = await isGitAvailable(workspace.path) if (!gitAvailable) { const error = new GitRequiredError() @@ -471,6 +513,8 @@ async function resolveGitWorktreeDirectory( function handleWorkspaceError(error: unknown, reply: FastifyReply) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + if (error instanceof RemoteWorkspaceError) return reply.code(error.status).send({ error: error.code, code: error.code }) if (error instanceof GitRequiredError || error instanceof GitInitError) return reply.code(error.statusCode).send({ error: error.message, code: error.code }) if (isGitCloneError(error)) { reply.code(error.statusCode) diff --git a/packages/server/src/server/routes/worktrees.test.ts b/packages/server/src/server/routes/worktrees.test.ts index 353219fd3c..c9e5d2b1c6 100644 --- a/packages/server/src/server/routes/worktrees.test.ts +++ b/packages/server/src/server/routes/worktrees.test.ts @@ -17,7 +17,7 @@ describe("worktree routes", () => { it("keeps ordinary worktree reads cached and exposes explicit fresh recovery validation", async () => { const app = Fastify({ logger: false }) const modes: string[] = [] - const manager = { get: () => ({ id: "workspace" }), getWorktrees: async (_id: string, mode: string) => { + const manager = { requireWorkspaceCapability: () => new AbortController().signal, get: () => ({ id: "workspace" }), getWorktrees: async (_id: string, mode: string) => { modes.push(mode) return { worktrees: [] } } } as unknown as WorkspaceManager @@ -93,6 +93,7 @@ it("reserves the physical worktree and rejects a same-HEAD replacement before de let reserved = "" let released = false const manager = { + requireWorkspaceCapability: () => new AbortController().signal, getWorktrees: () => fixtureCatalogue(workspacePath), get: () => ({ id: "workspace", @@ -183,6 +184,7 @@ it("fails a direct delete call closed when session evacuation fails", async () = }, } as unknown as OpenCodeClient const manager = { + requireWorkspaceCapability: () => new AbortController().signal, getWorktrees: () => fixtureCatalogue(temp), get: () => workspace, getSharedServiceClient: async () => client, diff --git a/packages/server/src/server/routes/worktrees.ts b/packages/server/src/server/routes/worktrees.ts index 5f93a8743d..be9878ef4e 100644 --- a/packages/server/src/server/routes/worktrees.ts +++ b/packages/server/src/server/routes/worktrees.ts @@ -22,6 +22,7 @@ import { } from "../../workspaces/project-session-families" import type { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" import { locationRequestOptions, readLocationRef } from "../../opencode/compatibility/location" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" interface RouteDeps { workspaceManager: WorkspaceManager @@ -49,6 +50,7 @@ export function registerWorktreeRoutes(app: FastifyInstance, deps: RouteDeps) { } try { + deps.workspaceManager.requireWorkspaceCapability(workspace.id, "worktrees") const response: WorktreeListResponse = await deps.workspaceManager.getWorktrees(workspace.id, query.data.fresh === "true" ? "fresh" : "cached") return response } catch (error) { @@ -64,6 +66,7 @@ export function registerWorktreeRoutes(app: FastifyInstance, deps: RouteDeps) { } try { + deps.workspaceManager.requireWorkspaceCapability(workspace.id, "worktrees") const body = WorktreeCreateSchema.parse(request.body ?? {}) const slug = body.slug if (!isValidWorktreeSlug(slug) || slug === "root") { @@ -118,6 +121,7 @@ export function registerWorktreeRoutes(app: FastifyInstance, deps: RouteDeps) { } try { + deps.workspaceManager.requireWorkspaceCapability(workspace.id, "worktrees") const { worktreeSlug } = WorktreeSessionMoveSchema.parse(request.body ?? {}) const { isGitRepo } = await resolveRepoRoot(workspace.path, request.log) if (!isGitRepo) throw new ProjectSessionError("Workspace is not a Git repository", 409) @@ -172,21 +176,22 @@ export function registerWorktreeRoutes(app: FastifyInstance, deps: RouteDeps) { return { error: "Workspace not found" } } - const slug = (request.params.slug ?? "").trim() - if (!isValidWorktreeSlug(slug) || slug === "root") { - reply.code(400) - return { error: "Invalid worktree slug" } - } + try { + deps.workspaceManager.requireWorkspaceCapability(workspace.id, "worktrees") + const slug = (request.params.slug ?? "").trim() + if (!isValidWorktreeSlug(slug) || slug === "root") { + reply.code(400) + return { error: "Invalid worktree slug" } + } - const { isGitRepo } = await resolveRepoRoot(workspace.path, request.log) - if (!isGitRepo) { - reply.code(400) - return { error: "Workspace is not a Git repository" } - } + const { isGitRepo } = await resolveRepoRoot(workspace.path, request.log) + if (!isGitRepo) { + reply.code(400) + return { error: "Workspace is not a Git repository" } + } - const force = (request.query?.force ?? "").toString().toLowerCase() === "true" + const force = (request.query?.force ?? "").toString().toLowerCase() === "true" - try { const worktrees = await strictWorktrees(deps.workspaceManager, workspace.id) const match = worktrees.find((wt) => wt.slug === slug) if (!match || match.kind === "root") { @@ -352,6 +357,7 @@ async function assertNoWorktreeBlockers( } function handleError(error: unknown, reply: FastifyReply) { + if (error instanceof WorkspaceCapabilityError) return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) if (error instanceof GitRequiredError) return reply.code(error.statusCode).send({ error: error.message, code: error.code }) reply.code(error instanceof ProjectSessionError ? error.statusCode : 400) return { error: error instanceof Error ? error.message : "Unable to fulfill request" } diff --git a/packages/server/src/server/routes/yolo.ts b/packages/server/src/server/routes/yolo.ts index 423414314f..29abc51fa1 100644 --- a/packages/server/src/server/routes/yolo.ts +++ b/packages/server/src/server/routes/yolo.ts @@ -1,13 +1,25 @@ -import { FastifyInstance } from "fastify" +import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify" import type { AutoAcceptManager } from "../../permissions/auto-accept-manager" +import { WorkspaceCapabilityError } from "../../opencode/servers/capabilities" interface RouteDeps { yoloManager: AutoAcceptManager } export function registerYoloRoutes(app: FastifyInstance, deps: RouteDeps) { + const admit = async (request: FastifyRequest, reply: FastifyReply) => { + const id = (request.params as { id?: string }).id + if (!id) return + try { + deps.yoloManager.requireCapability(id) + } catch (error) { + if (!(error instanceof WorkspaceCapabilityError)) throw error + return reply.code(403).send({ error: error.code, code: error.code, capability: error.capability, reason: error.reason }) + } + } app.get<{ Params: { id: string; sessionId: string } }>( "/workspaces/:id/yolo/sessions/:sessionId", + { preHandler: admit }, async (request) => { const { id, sessionId } = request.params await deps.yoloManager.hydrateInstance(id) @@ -17,6 +29,7 @@ export function registerYoloRoutes(app: FastifyInstance, deps: RouteDeps) { app.post<{ Params: { id: string; sessionId: string } }>( "/workspaces/:id/yolo/sessions/:sessionId/toggle", + { preHandler: admit }, async (request, reply) => { const { id, sessionId } = request.params const enabled = await deps.yoloManager.toggle(id, sessionId) diff --git a/packages/server/src/settings/protected-config.ts b/packages/server/src/settings/protected-config.ts new file mode 100644 index 0000000000..5188d94c8d --- /dev/null +++ b/packages/server/src/settings/protected-config.ts @@ -0,0 +1,22 @@ +import { isDeepStrictEqual } from "node:util" +import { applyMergePatch, isPlainObject } from "./merge-patch" + +const has = (value: object, key: string) => Object.prototype.hasOwnProperty.call(value, key) + +/** Generic config writes reserve this subtree for the internal server registry. */ +export function assertOpenCodeServersPatch(current: unknown, patch: unknown, owner?: string): void { + if (owner !== undefined && owner !== "server") return + const before = owner === "server" ? current : isPlainObject(current) ? current.server : undefined + const change = owner === "server" ? patch : isPlainObject(patch) ? patch.server : patch + if (isPlainObject(change) && has(change, "opencodeServers")) { + throw new Error("OpenCode server profiles require the server registry") + } + const candidate = applyMergePatch(current, patch) + const after = owner === "server" ? candidate : isPlainObject(candidate) ? candidate.server : undefined + const present = (value: unknown) => isPlainObject(value) && has(value, "opencodeServers") + if (present(before) !== present(after) + || !isDeepStrictEqual(isPlainObject(before) ? before.opencodeServers : undefined, + isPlainObject(after) ? after.opencodeServers : undefined)) { + throw new Error("OpenCode server profiles require the server registry") + } +} diff --git a/packages/server/src/settings/public-config.test.ts b/packages/server/src/settings/public-config.test.ts index afe6664094..5569547b34 100644 --- a/packages/server/src/settings/public-config.test.ts +++ b/packages/server/src/settings/public-config.test.ts @@ -1,6 +1,18 @@ import assert from "node:assert/strict" import { describe, it } from "node:test" -import { sanitizeConfigOwner } from "./public-config" +import { sanitizeConfigDoc, sanitizeConfigOwner } from "./public-config" + +it("sanitizes registry metadata in document, owner and full-document events without mutating private data", () => { + const server = { opencodeServers: [{ kind: "explicit", id: "remote", label: "Remote", origin: "https://example.test", + credentialMode: "keychain", credentialRef: "secret-ref-sentinel", password: "password-sentinel" }] } + const original = structuredClone(server) + for (const value of [sanitizeConfigOwner("server", server), sanitizeConfigDoc({ server }), sanitizeConfigOwner("*", { server })]) { + assert.doesNotMatch(JSON.stringify(value), /secret-ref-sentinel|password-sentinel|credentialRef|password/) + assert.match(JSON.stringify(value), /"hasCredentials":false/) + assert.match(JSON.stringify(value), /"needsCredentials":true/) + } + assert.deepEqual(server, original) +}) describe("sanitizeConfigOwner server speech", () => { it("strips shared apiKey and sets hasApiKey", () => { diff --git a/packages/server/src/settings/public-config.ts b/packages/server/src/settings/public-config.ts index a3eb26a712..777066c045 100644 --- a/packages/server/src/settings/public-config.ts +++ b/packages/server/src/settings/public-config.ts @@ -1,4 +1,5 @@ import type { SettingsDoc } from "./yaml-doc-store" +import { summarizeOpenCodeServers } from "../opencode/servers/registry" function isPlainObject(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value) @@ -6,6 +7,7 @@ function isPlainObject(value: unknown): value is Record { function sanitizeServerOwner(value: SettingsDoc): SettingsDoc { const next: SettingsDoc = { ...value } + if ("opencodeServers" in next) next.opencodeServers = summarizeOpenCodeServers(next.opencodeServers) const speech = isPlainObject(next.speech) ? { ...next.speech } : null if (!speech) { @@ -39,6 +41,7 @@ function sanitizeServerOwner(value: SettingsDoc): SettingsDoc { } export function sanitizeConfigOwner(owner: string, value: SettingsDoc): SettingsDoc { + if (owner === "*") return sanitizeConfigDoc(value) if (owner !== "server") { return value } diff --git a/packages/server/src/settings/service.test.ts b/packages/server/src/settings/service.test.ts index 3585fdc663..73c7892fb2 100644 --- a/packages/server/src/settings/service.test.ts +++ b/packages/server/src/settings/service.test.ts @@ -12,6 +12,49 @@ function serviceWithStore(store: Record) { } describe("SettingsService config persistence", () => { + it("normalizes development server metadata without reading a credential provider", () => { + const profile = { kind: "explicit", id: "one", label: "One", origin: "https://example.test" } + let doc = { server: { opencodeServers: [{ ...profile, credentialMode: "keychain", credentialRef: "private-ref" }] } } + let writes = 0 + const service = serviceWithStore({ + get: () => doc, + replace: (value: typeof doc) => { writes++; doc = value; return doc }, + }) + assert.deepEqual(service.getDoc("config"), { server: { opencodeServers: [profile] } }) + assert.equal(writes, 1) + assert.deepEqual(service.getDoc("config"), { server: { opencodeServers: [profile] } }) + assert.equal(writes, 1) + }) + it("reserves registry writes and ancestor removals before persistence or publication", () => { + const profiles = [{ kind: "explicit", id: "one", label: "One", origin: "https://example.test" }] + let doc = { server: { opencodeServers: profiles, logLevel: "INFO" }, ui: { theme: "light" } } + const events: unknown[] = [] + let writes = 0 + const service = serviceWithStore({ + get: () => doc, getOwner: () => doc.server, getAuthoritativeOwner: () => doc.server, + replace: (value: typeof doc) => { writes++; doc = value; return doc }, + replaceOwner: (_owner: string, value: typeof doc.server) => { writes++; doc.server = value; return value }, + }) + Object.assign(service as any, { eventBus: { publish: (value: unknown) => events.push(value) } }) + for (const patch of [{ opencodeServers: [] }, { opencodeServers: null }, { opencodeServers: {} }, + { opencodeServers: profiles }, { opencodeServers: [], logLevel: "ERROR" }, null, [], "replace"]) { + assert.throws(() => service.mergePatchOwner("config", "server", patch)) + assert.throws(() => service.mergePatchDoc("config", { server: patch, ui: { theme: "dark" } })) + } + assert.equal(writes, 0) + assert.deepEqual(events, []) + service.mergePatchOwner("config", "server", { logLevel: "WARN" }) + service.mergePatchDoc("config", { ui: { theme: "dark" } }) + assert.deepEqual(doc.server.opencodeServers, profiles) + assert.equal(writes, 2) + assert.equal(events.length, 2) + assert.match(JSON.stringify(events[1]), /"owner":"\*"/) + assert.match(JSON.stringify(events[1]), /"hasCredentials":false/) + service.getOpenCodeServerRegistry().replace([]) + assert.deepEqual(doc.server.opencodeServers, []) + assert.equal(writes, 3) + assert.equal(events.length, 3) + }) it("preserves Tauri's ASCII-folded Unicode Windows identity without moving profile state", () => { if (process.platform !== "win32") return const service = serviceWithStore({}) diff --git a/packages/server/src/settings/service.ts b/packages/server/src/settings/service.ts index 8d8af0666a..79da9b2110 100644 --- a/packages/server/src/settings/service.ts +++ b/packages/server/src/settings/service.ts @@ -11,6 +11,12 @@ import { readAdmissionEnvironment } from "./admission-environment" import { canonicalScope } from "../host-lifetime/protocol" import { createHash } from "node:crypto" import path from "node:path" +import { assertOpenCodeServersPatch } from "./protected-config" +import { OpenCodeServerRegistry, summarizeOpenCodeServers } from "../opencode/servers/registry" +import { OpenCodeServersSchema } from "../config/schema" +import { OpenCodeServerCredentials } from "../opencode/servers/credentials" +import { PairingTokenStore } from "../opencode/servers/pairing-store" +import { OpenCodeServerConnections } from "../opencode/servers/connections" export type DocKind = "config" | "state" @@ -38,6 +44,10 @@ function normalizeServerConfigOwner(value: SettingsDoc): SettingsDoc { } const next: SettingsDoc = { ...value } + if (next.opencodeServers !== undefined) { + const profiles = OpenCodeServersSchema.safeParse(next.opencodeServers) + if (profiles.success) next.opencodeServers = profiles.data + } const parsedLogLevel = CanonicalLogLevelSchema.safeParse(next.logLevel) if (parsedLogLevel.success) { next.logLevel = parsedLogLevel.data @@ -72,6 +82,9 @@ function normalizeConfigDoc(doc: SettingsDoc): SettingsDoc { export class SettingsService { private readonly configStore: YamlDocStore private readonly stateStore: YamlDocStore + private serverRegistry?: OpenCodeServerRegistry + #serverCredentials?: OpenCodeServerCredentials + #serverConnections?: OpenCodeServerConnections constructor( private readonly location: ConfigLocation, @@ -131,7 +144,49 @@ export class SettingsService { return this.location.configYamlPath } + getOpenCodeServerRegistry(): OpenCodeServerRegistry { + return this.serverRegistry ??= new OpenCodeServerRegistry( + () => this.configStore.getAuthoritativeOwner("server").opencodeServers, + profiles => { + const current = this.configStore.getAuthoritativeOwner("server") + const updated = this.configStore.replaceOwner("server", { ...current, opencodeServers: profiles }) + this.publish("config", "server", updated) + }, + ) + } + + /** One backend/config owner, shared by all windows and transports. */ + getOpenCodeServerCredentials(): OpenCodeServerCredentials { + const scope = this.getProfileScope() + return this.#serverCredentials ??= new OpenCodeServerCredentials( + { profileKey: scope.key, configIdentity: scope.configIdentity }, this.getOpenCodeServerRegistry(), + // prototype-1236: paired tokens persist beside the profile's config, never inside it. + new PairingTokenStore(path.join(path.dirname(this.location.configYamlPath), "opencode-server-pairings.json")), + ) + } + + getOpenCodeServerConnections(local: ConstructorParameters[0]["local"]): OpenCodeServerConnections { + return this.#serverConnections ??= new OpenCodeServerConnections({ + registry: this.getOpenCodeServerRegistry(), credentials: this.getOpenCodeServerCredentials(), local, + }) + } + + async getOpenCodeServerSummaries() { + const summaries = summarizeOpenCodeServers(this.getRawConfigOwner("server").opencodeServers) + return summaries.map(profile => { + if (profile.kind !== "explicit") return profile + const hasCredentials = this.getOpenCodeServerCredentials().hasCredentials(profile.id) + return { ...profile, hasCredentials, needsCredentials: !hasCredentials } + }) + } + + async disposeOpenCodeServers(): Promise { + if (this.#serverConnections) await this.#serverConnections.dispose() + else await this.#serverCredentials?.dispose() + } + mergePatchDoc(kind: DocKind, patch: unknown): SettingsDoc { + if (kind === "config") assertOpenCodeServersPatch(this.configStore.get(), patch) if (!isPlainObject(patch)) { throw new Error("Patch must be a JSON object") } @@ -161,6 +216,9 @@ export class SettingsService { } mergePatchOwner(kind: DocKind, owner: string, patch: unknown): SettingsDoc { + if (kind === "config" && owner === "server") { + assertOpenCodeServersPatch(this.configStore.getOwner(owner), patch, owner) + } if (!isPlainObject(patch)) { throw new Error("Patch must be a JSON object") } @@ -180,7 +238,7 @@ export class SettingsService { private publish(kind: DocKind, owner: string, value?: SettingsDoc) { if (!this.eventBus) return const type = kind === "config" ? "storage.configChanged" : "storage.stateChanged" - const nextValue = value ?? this.getOwner(kind, owner) + const nextValue = value ?? (owner === "*" ? this.getDoc(kind) : this.getOwner(kind, owner)) const payload: WorkspaceEventPayload = { type, owner, diff --git a/packages/server/src/shutdown.ts b/packages/server/src/shutdown.ts index 607c8eb94e..d7955c46b5 100644 --- a/packages/server/src/shutdown.ts +++ b/packages/server/src/shutdown.ts @@ -1,3 +1,5 @@ +import { nativeStdinFramer } from "./native-response" + type ShutdownLogger = Pick type ShutdownOperation = () => void | Promise @@ -28,19 +30,17 @@ export function installShutdownStdinHandler( source: ShutdownStdinSource, shutdown: (signal: ServerShutdownTrigger) => Promise, handleLine?: (line: string) => boolean, + onOverflow?: (id: string) => void, ): void { - let buffer = "" let requested = false + let shutdownRequested = false + const frame = nativeStdinFramer(line => { + if (line.trim() === STDIN_SHUTDOWN_COMMAND) shutdownRequested = true + else handleLine?.(line) + }, onOverflow) const onData = (chunk: Buffer | string) => { if (requested) return - buffer += chunk.toString() - const lines = buffer.split(/\r?\n/) - buffer = lines.pop() ?? "" - let shutdownRequested = false - for (const line of lines) { - if (line.trim() === STDIN_SHUTDOWN_COMMAND) shutdownRequested = true - else handleLine?.(line) - } + frame(chunk) if (!shutdownRequested) return requested = true diff --git a/packages/server/src/workspaces/explicit-workspace.test.ts b/packages/server/src/workspaces/explicit-workspace.test.ts new file mode 100644 index 0000000000..ddabcef8be --- /dev/null +++ b/packages/server/src/workspaces/explicit-workspace.test.ts @@ -0,0 +1,683 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { createServer, type ServerResponse } from "node:http" +import { once } from "node:events" +import fs from "node:fs/promises" +import childProcess from "node:child_process" +import { syncBuiltinESMExports } from "node:module" +import pino from "pino" +import Fastify from "fastify" +import { explicitContractFixture } from "../opencode/compatibility/contract-fixture" +import { OpenCodeServerConnections, type ServerConnection } from "../opencode/servers/connections" +import { OpenCodeServerCredentials } from "../opencode/servers/credentials" +import { OpenCodeServerRegistry } from "../opencode/servers/registry" +import { EventBus } from "../events/bus" +import { ExplicitWorkspace } from "./explicit-workspace" +import { WorkspaceManager } from "./manager" +import { createInstanceClient } from "./instance-client" +import { registerWorkspaceRoutes } from "../server/routes/workspaces" +import { registerWorktreeRoutes } from "../server/routes/worktrees" +import { registerPendingRequestRoutes } from "../server/routes/pending-requests" +import { WorktreeDeletionFence } from "./worktree-session-evacuation" +import { cloneGitRepository } from "./git-clone" + +function deferred() { + let resolve!: () => void + const promise = new Promise(done => { resolve = done }) + return { promise, resolve } +} + +async function fixture(platform: NodeJS.Platform = "win32", allowLocal = false) { + const calls: { path: string; directory?: string; method?: string }[] = [] + const entered = deferred() + let hold: "location" | "list" | "contract" | undefined + let contract: unknown = explicitContractFixture() + const held: (() => void)[] = [] + let locationOverride: string | undefined, listingOverride: string | undefined, oversized = false + let listingResponse: { value: unknown } | undefined + let moved = false, stopped = false + const server = createServer((request, response: ServerResponse) => { + const url = new URL(request.url!, "http://fixture") + const directory = url.searchParams.get("location[directory]") ?? undefined + calls.push({ path: url.pathname, directory, method: request.method }) + response.setHeader("content-type", "application/json") + const send = (value: unknown) => response.end(JSON.stringify(value)) + if (url.pathname === "/openapi.json") { + const captured = contract + if (hold === "contract") { held.push(() => send(captured)); entered.resolve() } + else send(captured) + return + } + const result = () => { + if (directory === "/absent" && url.pathname === "/api/location") { + // Deliberately accept absent paths here: the independent listing must still refuse. + send({ directory, project: { id: "same-project", directory: "/", canonical: "/" } }); return + } + if (url.pathname === "/api/location") { + send({ directory: locationOverride ?? directory, project: { id: "same-project", directory: "/", canonical: "/" } }); return + } + if (url.pathname === "/api/fs/list") { + if (listingResponse) { send(listingResponse.value); return } + if (directory === "/absent" || directory === "/inaccessible") { response.statusCode = 500; send({}); return } + send({ location: { directory: listingOverride ?? directory }, data: oversized ? ["x".repeat(8 * 1024 * 1024)] : [] }); return + } + if (url.pathname === "/api/session/same-session") { + send({ data: { id: "same-session", parentID: "foreign-parent", projectID: "same-project", location: { directory: moved ? "/sibling" : "/exact" } } }); return + } + response.statusCode = 404; send({}) + } + if ((hold === "location" && url.pathname === "/api/location") || (hold === "list" && url.pathname === "/api/fs/list")) { + held.push(result); entered.resolve(); return + } + result() + }) + server.listen(0, "127.0.0.1") + await once(server, "listening") + const origin = `http://127.0.0.1:${(server.address() as { port: number }).port}` + let profiles: any[] = ["A", "B"].map(id => ({ id, kind: "explicit", label: id, origin })) + const registry = new OpenCodeServerRegistry(() => profiles, next => { profiles = next }) + const credentials = new OpenCodeServerCredentials({ profileKey: "test", configIdentity: "test" }, registry) + for (const id of ["A", "B"]) await credentials.set(id, JSON.stringify({ username: "test", password: "fixture-only" })) + const forbidden = () => { throw new Error("Host operation forbidden") } + const connections = new OpenCodeServerConnections({ registry, credentials, local: { acquire: forbidden, existing: forbidden, invalidate: forbidden } }) + const events = new EventBus() + const manager = new WorkspaceManager({ rootDir: "C:/host", platform, eventBus: events, logger: pino({ level: "silent" }), + binaryResolver: { resolveDefault: allowLocal ? () => ({ path: process.execPath, label: "isolated local adapter" }) : forbidden } as never, + settings: { getOpenCodeServerConnections: () => connections, getOwner: allowLocal ? () => ({ environmentVariables: {} }) : forbidden, readEnvironmentForAdmission: forbidden, + disposeOpenCodeServers: async () => { stopped = true; await connections.dispose() } } as never, + sharedService: { endpoint: forbidden, client: forbidden, headers: allowLocal ? async () => undefined : forbidden, + validateLocation: allowLocal ? async location => ({ ...location, project: { id: "local", directory: location.directory, canonical: location.directory } }) : forbidden, + subscribe: forbidden, shutdown: async () => {} }, + wslHostDirectoryResolver: forbidden, wslServiceDirectoryResolver: forbidden, + }) + return { manager, connections, credentials, registry, calls, events, entered: entered.promise, + block(operation: "location" | "list" | "contract") { hold = operation }, finish() { hold = undefined; for (const result of held.splice(0)) result() }, + contract(value: unknown) { contract = value }, + location(value: string) { locationOverride = value }, listing(value: string) { listingOverride = value }, + listResponse(value: unknown) { listingResponse = { value } }, + oversize() { oversized = true }, move() { moved = true }, + async close() { if (!stopped) await manager.shutdown(); server.closeAllConnections(); await new Promise(resolve => server.close(() => resolve())) }, + } +} + +test("explicit manager preserves cross-host namespace, immutable bindings and exact authority without host operations", async t => { + const f = await fixture() + t.after(() => f.close()) + const hostCalls: string[] = [] + const mocks = [ + ...(["realpath", "stat", "lstat", "readdir", "readFile", "writeFile"] as const).map(method => + t.mock.method(fs, method, () => { hostCalls.push(method); throw new Error("Host FS forbidden") })), + ...(["spawn", "spawnSync", "execFile", "execFileSync"] as const).map(method => + t.mock.method(childProcess, method, () => { hostCalls.push(method); throw new Error("Host Git/shell forbidden") })), + ] + syncBuiltinESMExports() + t.after(() => { for (const mock of mocks) mock.mock.restore(); syncBuiltinESMExports() }) + for (const directory of ["/Case/Project", "Z:\\Case\\Project", "//opaque/alias", "/exact"]) { + const { workspace } = await f.manager.create(directory, undefined, { serverId: "A" }) + assert.equal(workspace.path, directory) + assert.deepEqual(workspace.binding, { serverId: "A", directory }) + assert.equal(workspace.binaryId, undefined) + assert.equal(workspace.pid, undefined) + assert.equal(workspace.port, undefined) + assert.equal(workspace.capabilities?.features.worktrees.state, "unavailable") + const record = f.manager.get(workspace.id)! + assert.throws(() => { (record.binding as { directory: string }).directory = "/changed" }) + assert.throws(() => { record.binding = { serverId: "B", directory } }) + assert.equal(await f.manager.ownsLocation(workspace.id, { directory }), true) + for (const outside of ["/", "/Case", "/Case/Project2", directory + "/child", directory.toLowerCase(), "/alias"]) { + if (outside !== directory) assert.equal(await f.manager.ownsDirectory(workspace.id, outside), false) + } + assert.equal(await f.manager.ownsLocation(workspace.id, { directory, workspaceID: "retired" }), false) + assert.equal(await f.manager.getServiceDirectoryForPath(workspace.id, directory), directory) + for (const operation of [ + () => f.manager.getWorktrees(workspace.id), () => f.manager.getSessionEnvironment(workspace.id), + () => f.manager.readFile(workspace.id, "secret"), () => f.manager.writeFile(workspace.id, "secret", "data"), + () => f.manager.listFiles(workspace.id), () => f.manager.searchFiles(workspace.id, "secret"), + () => f.manager.getHostPathForServicePath(workspace.id, directory), () => f.manager.createWorktree(workspace.id, "branch"), + ]) await assert.rejects(async () => operation(), { code: "explicit_capability_unavailable" }) + await f.manager.delete(workspace.id) + assert.equal(f.connections.activeExplicitTargets, 0) + } + assert.deepEqual(hostCalls, []) + assert(f.calls.every(call => ["/openapi.json", "/api/location", "/api/fs/list"].includes(call.path))) +}) + +test("real Files/Git/worktree routes and manager calls refuse explicit A/B before host IO or RPC", async t => { + const f = await fixture(); t.after(() => f.close()) + const owners = await Promise.all(["A", "B"].map(serverId => f.manager.create("/exact", undefined, { serverId }))) + const app = Fastify(); t.after(() => app.close()) + const deps = { workspaceManager: f.manager, worktreeDeletionFence: new WorktreeDeletionFence() } + registerWorkspaceRoutes(app, deps); registerWorktreeRoutes(app, deps) + registerPendingRequestRoutes(app, deps) + await app.ready() + const callsBefore = f.calls.length, hostCalls: string[] = [] + const mocks = [ + ...(["realpath", "stat", "lstat", "readdir", "readFile", "writeFile"] as const).map(method => + t.mock.method(fs, method, () => { hostCalls.push(method); throw new Error("Host FS forbidden") })), + ...(["spawn", "spawnSync", "execFile", "execFileSync"] as const).map(method => + t.mock.method(childProcess, method, () => { hostCalls.push(method); throw new Error("Host process forbidden") })), + ] + syncBuiltinESMExports() + t.after(() => { for (const mock of mocks) mock.mock.restore(); syncBuiltinESMExports() }) + for (const { workspace } of owners) { + const base = `/api/workspaces/${encodeURIComponent(workspace.id)}` + // prototype-1236: native read-only Files/Changes reads are covered by explicit-panels.test.ts; + // every write, history, other folder or host Git path is still refused before host IO. + const requests = [ + ["GET", "/files?directory=%2Fother", undefined, "files"], + ["GET", "/files/search?q=secret&directory=%2Fother", undefined, "files"], + ["GET", "/files/preview?path=secret&directory=%2Fother", undefined, "files"], + ["GET", "/files/content?path=secret&worktree=other", undefined, "files"], + ["PUT", "/files/content?path=secret&directory=%2Fexact", { contents: "forbidden" }, "files"], + ["PUT", "/files/content?path=secret", { contents: "forbidden" }, "files"], + ["POST", "/git-init", { directory: "/exact" }, "git"], + ["GET", "/worktrees/other/git-status", undefined, "git"], + ["GET", "/worktrees/root/git-diff?path=secret&scope=staged", undefined, "git"], + ["GET", "/worktrees/root/git-history", undefined, "git"], + ["POST", "/worktrees/root/git-stage", { paths: ["secret"] }, "git"], + ["POST", "/worktrees/root/git-unstage", { paths: ["secret"] }, "git"], + ["POST", "/worktrees/root/git-commit", { message: "forbidden" }, "git"], + ["GET", "/worktrees?fresh=true", undefined, "worktrees"], + ["POST", "/worktrees", { slug: "branch" }, "worktrees"], + ["DELETE", "/worktrees/branch?force=true", undefined, "worktrees"], + ["POST", "/sessions/same-session/worktree", { worktreeSlug: "branch" }, "worktrees"], + ["GET", "/pending-requests?directories=%2Fexact", undefined, "pendingRecovery"], + ] as const + for (const [method, suffix, payload, capability] of requests) { + const response = await app.inject({ method, url: base + suffix, payload }) + assert.equal(response.statusCode, 403, `${method} ${suffix}: ${response.body}`) + assert.deepEqual(response.json(), { error: "explicit_capability_unavailable", code: "explicit_capability_unavailable", capability, reason: { code: capability === "pendingRecovery" ? "liveOnly" : "deferred" } }) + } + for (const operation of [ + () => f.manager.previewFile(workspace.id, "secret", "/exact"), + () => f.manager.readFileInDirectory(workspace.id, "/exact", "secret"), + () => f.manager.writeFileInDirectory(workspace.id, "/exact", "secret", "forbidden"), + () => f.manager.removeWorktree(workspace.id, "/exact", true), + () => f.manager.initializeGit(workspace.id), + () => f.manager.getWorktreeIdentityForPath(workspace.id, "/exact"), + ]) await assert.rejects(async () => operation(), { code: "explicit_capability_unavailable" }) + } + for (const serverId of ["A", "B", ""]) { + const payload = { serverId, repositoryUrl: "https://example.invalid/repo", destinationPath: "/exact" } + assert.equal((await app.inject({ method: "POST", url: "/api/workspaces/clone", payload })).statusCode, 403) + await assert.rejects(cloneGitRepository(payload), { code: "explicit_capability_unavailable", capability: "git" }) + } + assert.equal((await app.inject({ method: "POST", url: "/api/workspaces/clone", payload: { + binding: { serverId: "B", directory: "/exact" }, repositoryUrl: "https://example.invalid/repo", destinationPath: "/exact", + } })).statusCode, 400) + assert.deepEqual(hostCalls, []) + assert.equal(f.calls.length, callsBefore) +}) + +test("POSIX backend keeps native Windows paths and case byte-for-byte", async t => { + const f = await fixture("linux"); t.after(() => f.close()) + const directory = "Z:\\Remote Case\\Project" + const { workspace } = await f.manager.create(directory, undefined, { serverId: "A" }) + assert.equal(workspace.path, directory) + assert.equal(f.manager.getServiceDirectory(workspace.id), directory) + assert.equal(f.manager.getServicePathStyle(workspace.id), "win32") + assert.equal(await f.manager.ownsDirectory(workspace.id, directory.toLowerCase()), false) + assert.equal(await f.manager.ownsDirectory(workspace.id, "Z:/Remote Case/Project"), false) +}) + +test("same paths/session IDs on A and B and independent window occurrences never share client authority", async t => { + const f = await fixture(); t.after(() => f.close()) + const a = await f.manager.create("/exact", "window-1", { serverId: "A" }) + const a2 = await f.manager.create("/exact", "window-2", { serverId: "A" }) + const b = await f.manager.create("/exact", "window-1", { serverId: "B" }) + assert.notEqual(a.workspace.id, a2.workspace.id) + assert.equal(f.connections.activeExplicitTargets, 2) + assert.equal(f.calls.filter(call => call.path === "/openapi.json").length, 2) + const ca = await createInstanceClient(f.manager, a.workspace.id), cb = await createInstanceClient(f.manager, b.workspace.id) + assert.notEqual(ca, cb) + assert.equal(await createInstanceClient(f.manager, a2.workspace.id), ca) + assert.equal(await f.manager.ownsLocation(a.workspace.id, { directory: "/exact" }, cb!), false) + await f.manager.delete(a.workspace.id) + assert.equal(f.connections.activeExplicitTargets, 2) + await f.manager.delete(a2.workspace.id) + assert.equal(f.connections.activeExplicitTargets, 1) + await assert.rejects(f.connections.acquireForWorkspace({ serverId: "A", directory: "/exact" }), { code: "disconnected" }) + assert.equal(await f.manager.ownsLocation(b.workspace.id, { directory: "/exact" }, cb!), true) +}) + +test("native placement alone authorizes each session, including descendants; moving out removes authority", async t => { + const f = await fixture(); t.after(() => f.close()) + const owner = new ExplicitWorkspace(f.connections, { serverId: "A", directory: "/exact" }) + t.after(() => owner.release()) + await owner.validate(new AbortController().signal) + assert.equal(await owner.ownsSession("same-session"), true) + f.move() + assert.equal(await owner.ownsSession("same-session"), false) +}) + +for (const directory of ["/absent", "/inaccessible"]) test(`native ${directory} rejects attachment and releases its slot even when location.get accepts`, async t => { + const f = await fixture(); t.after(() => f.close()) + await assert.rejects(f.manager.create(directory, undefined, { serverId: "A" }), { code: "explicit_location_unavailable" }) + assert.equal(f.manager.list().length, 0) + assert.equal(f.connections.activeExplicitTargets, 0) +}) + +const listing = (data: unknown) => ({ location: { directory: "/exact" }, data }) +for (const [kind, response] of Object.entries({ + "null entry (QA reproduction)": listing([null]), + "invalid path and type (QA reproduction)": listing([{ path: 42, type: "invalid" }]), + "null root": null, + "array root": [], + "scalar root": "untrusted-response", + "missing location": { data: [] }, + "null location": { location: null, data: [] }, + "missing data": { location: { directory: "/exact" } }, + "null data": listing(null), + "object data": listing({}), + "scalar data": listing("untrusted-response"), + "scalar entry": listing(["untrusted-entry"]), + "array entry": listing([[]]), + "missing entry path": listing([{ type: "file" }]), + "null entry path": listing([{ path: null, type: "file" }]), + "numeric entry path": listing([{ path: 42, type: "file" }]), + "missing entry type": listing([{ path: "proof.txt" }]), + "null entry type": listing([{ path: "proof.txt", type: null }]), + "numeric entry type": listing([{ path: "proof.txt", type: 42 }]), + "unknown entry type": listing([{ path: "proof.txt", type: "symlink" }]), + "invalid trailing entry": listing([{ path: "proof.txt", type: "file" }, {}]), +})) test(`malformed native listing ${kind} rejects without publication or mutation and releases its lease`, async t => { + const f = await fixture(); t.after(() => f.close()) + f.listResponse(response) + const publications: string[] = [] + f.events.on("workspace.created", () => { publications.push("created") }) + f.events.on("workspace.started", () => { publications.push("started") }) + await assert.rejects(f.manager.create("/exact", undefined, { serverId: "A" }), { + name: "ExplicitWorkspaceError", code: "explicit_location_unavailable", message: "explicit_location_unavailable", + }) + assert.deepEqual(publications, []) + assert.equal(f.manager.list().length, 0) + assert.equal(f.connections.activeExplicitTargets, 0) + assert.deepEqual(f.calls.map(call => [call.method, call.path]), [ + ["GET", "/openapi.json"], ["GET", "/api/location"], ["GET", "/api/fs/list"], + ]) +}) + +for (const [kind, data] of Object.entries({ + empty: [], + native: [{ path: "proof.txt", type: "file" }, { path: "nested folder", type: "directory" }], + extensible: [{ path: "opaque\\Path", type: "file", futureMetadata: null }, { path: "", type: "directory", futureFlag: true }], +})) test(`valid native listing ${kind} admits without host path rules or extra-field restrictions`, async t => { + const f = await fixture(); t.after(() => f.close()) + f.listResponse({ ...listing(data), futureMetadata: { supported: true } }) + const { workspace } = await f.manager.create("/exact", undefined, { serverId: "A" }) + assert.equal(workspace.status, "ready") + await f.manager.delete(workspace.id) + assert.equal(f.connections.activeExplicitTargets, 0) +}) + +for (const stage of ["location", "list"] as const) { + for (const revoke of ["cancel", "rotate", "disconnect", "shutdown"] as const) test(`${stage}: ${revoke} fences late results, releases leases and never publishes ready`, async t => { + const f = await fixture(); t.after(() => f.close()) + f.block(stage) + let publications = 0 + f.events.on("workspace.started", () => { publications++ }) + const creation = f.manager.create("/exact", undefined, { serverId: "A", requestId: "opening" }) + const rejected = assert.rejects(creation) + await f.entered + assert.equal(f.connections.activeExplicitTargets, 1) + if (revoke === "cancel") await f.manager.cancelCreationRequest("opening") + if (revoke === "rotate") await f.credentials.set("A", JSON.stringify({ username: "new", password: "new" })) + if (revoke === "disconnect") f.connections.disconnect("A") + if (revoke === "shutdown") await f.manager.shutdown() + f.finish() + await rejected + assert.equal(publications, 0) + assert.equal(f.manager.list().length, 0) + assert.equal(f.connections.activeExplicitTargets, 0) + assert(f.calls.every(call => !/delete|evict|move/i.test(call.path))) + }) +} + +test("native mismatch, huge validation response and unknown target fail closed", async t => { + for (const kind of ["location", "listing", "oversize", "unknown"] as const) { + const f = await fixture() + try { + if (kind === "location") f.location("/sibling") + if (kind === "listing") f.listing("/sibling") + if (kind === "oversize") f.oversize() + await assert.rejects(f.manager.create("/exact", undefined, { serverId: kind === "unknown" ? "missing" : "A" })) + assert.equal(f.connections.activeExplicitTargets, 0) + assert.equal(f.manager.list().length, 0) + } finally { await f.close() } + } +}) + +test("pending same-target occurrences share admission; cancelling one retains the other's lease", async t => { + const f = await fixture(); t.after(() => f.close()) + f.block("location") + const first = f.manager.create("/exact", undefined, { serverId: "A", requestId: "first" }) + const rejected = assert.rejects(first) + await f.entered + const second = f.manager.create("/exact", undefined, { serverId: "A", requestId: "second" }) + await f.manager.cancelCreationRequest("first") + await rejected + assert.equal(f.connections.activeExplicitTargets, 1) + f.finish() + const result = await second + assert.equal(f.manager.list().length, 1) + assert.equal(f.calls.filter(call => call.path === "/openapi.json").length, 1) + f.manager.releaseCreationRequest(result.workspace.id, "second") + await f.manager.cancelCreationRequest("second") + assert.equal(f.manager.list().length, 1) + await f.manager.delete(result.workspace.id) + assert.equal(f.connections.activeExplicitTargets, 0) +}) + +test("shared native project and alias metadata never extend exact authority", async t => { + const f = await fixture(); t.after(() => f.close()) + const { workspace } = await f.manager.create("/alias", undefined, { serverId: "A" }) + assert.equal(await f.manager.ownsDirectory(workspace.id, "/"), false) + assert.equal(await f.manager.ownsDirectory(workspace.id, "/exact"), false) + const other = await f.manager.create("/exact", undefined, { serverId: "A" }) + assert.equal(await f.manager.ownsDirectory(other.workspace.id, "/alias"), false) + assert.equal(await f.manager.ownsDirectory(workspace.id, "/exact"), false) +}) + +test("retarget and close during publication release leases and fence unpublished/late ready records", async t => { + for (const kind of ["retarget", "publication"] as const) { + const f = await fixture() + try { + let ready = 0 + f.events.on("workspace.started", () => { ready++ }) + if (kind === "publication") f.events.on("workspace.created", event => { void f.manager.delete(event.workspace.id) }) + else f.block("list") + const creation = f.manager.create("/exact", undefined, { serverId: "A" }) + const rejected = assert.rejects(creation) + if (kind === "retarget") { + await f.entered + await f.registry.replace([{ id: "A", kind: "explicit", label: "New URL", origin: "http://127.0.0.1:1" }]) + f.finish() + } + await rejected + await new Promise(resolve => setImmediate(resolve)) + assert.equal(ready, 0) + assert.equal(f.manager.list().length, 0) + assert.equal(f.connections.activeExplicitTargets, 0) + } finally { await f.close() } + } +}) + +test("published bindings trust reconnect at the same URL, reject held clients and never reacquire after Disconnect", async t => { + const f = await fixture(); t.after(() => f.close()) + const { workspace } = await f.manager.create("/exact", undefined, { serverId: "A" }) + const previous = (await f.manager.acquireForWorkspace(workspace.id))! + await f.credentials.set("A", JSON.stringify({ username: "rotated", password: "fixture-only" })) + assert.throws(() => previous.assertCurrent(), { code: "stale_connection" }) + const current = (await f.manager.acquireForWorkspace(workspace.id))! + assert.notEqual(previous.client, current.client) + assert.deepEqual(f.manager.get(workspace.id)!.binding, { serverId: "A", directory: "/exact" }) + assert.equal(await f.manager.ownsLocation(workspace.id, { directory: "/exact" }, previous.client), false) + assert.equal(await f.manager.ownsLocation(workspace.id, { directory: "/exact" }, current.client), true) + f.connections.disconnect("A") + await assert.rejects(f.manager.acquireForWorkspace(workspace.id), { code: "disconnected" }) + assert.equal(f.connections.activeExplicitTargets, 0) + assert.equal(f.manager.list().length, 1) + await f.connections.connect("A") + assert.equal(await f.manager.ownsDirectory(workspace.id, "/exact"), true) +}) + +test("empty target IDs fail internally without local fallback", async t => { + const f = await fixture(); t.after(() => f.close()) + await assert.rejects(f.manager.create("/exact", undefined, { serverId: "" }), { code: "explicit_location_unavailable" }) + assert.equal(f.calls.length, 0) +}) + +test("manager metadata follows the validated current connection without acquisition and retains historical snapshots", async t => { + const f = await fixture("win32", true); t.after(() => f.close()) + const emptyLocal = f.manager.attachmentReservations("local-shared") + const creatingLocal = f.manager.create(process.cwd()) + assert.equal(f.manager.attachmentReceiptCurrent(emptyLocal.receipt), false) + assert.equal(f.manager.attachmentReservations("local-shared").inFlight, true) + assert.deepEqual(f.manager.attachmentReservations("local-shared").reservations, []) + const local = (await creatingLocal).workspace + assert.equal(f.manager.attachmentReservations("local-shared").inFlight, false) + assert.equal(f.manager.attachmentReservations("local-shared").reservations[0]!.state, "published") + const stableLocal = f.manager.get(local.id)! + const a = (await f.manager.create("/exact", "one", { serverId: "A" })).workspace + const a2 = (await f.manager.create("/other", "two", { serverId: "A" })).workspace + const b = (await f.manager.create("/exact", "one", { serverId: "B" })).workspace + const previous = (await f.manager.acquireForWorkspace(a.id))! + const old = f.manager.get(a.id)!, stableB = f.manager.get(b.id)!.capabilities + const inspect = (available: boolean, generation?: number) => { + const before = f.calls.length + const acquire = t.mock.method(f.connections, "acquireForServer", () => { throw new Error("Metadata must not acquire") }) + const workspaceAcquire = t.mock.method(f.connections, "acquireForWorkspace", () => { throw new Error("Metadata must not reconnect") }) + const worktrees = t.mock.method(f.manager, "getWorktrees", () => { throw new Error("Metadata must not discover worktrees") }) + const hostCalls: string[] = [] + const mocks = [ + ...(["realpath", "stat", "lstat", "readdir", "readFile", "writeFile"] as const).map(method => + t.mock.method(fs, method, () => { hostCalls.push(method); throw new Error("Metadata must not access host files") })), + ...(["spawn", "spawnSync", "execFile", "execFileSync"] as const).map(method => + t.mock.method(childProcess, method, () => { hostCalls.push(method); throw new Error("Metadata must not provision/discover services") })), + ] + syncBuiltinESMExports() + try { + for (const id of [a.id, a2.id]) { + const descriptor = f.manager.get(id)! + assert.deepEqual(descriptor.capabilities, f.manager.list().find(value => value.id === id)!.capabilities) + for (const feature of ["sessions", "chat", "media", "permissions", "questions", "events"] as const) { + assert.equal(descriptor.capabilities!.features[feature].state, available ? "available" : "unknown") + } + if (generation !== undefined) assert.equal(descriptor.capabilities!.generation, generation) + if (available) assert.doesNotThrow(() => f.manager.requireWorkspaceCapability(id, "chat")) + else assert.throws(() => f.manager.requireWorkspaceCapability(id, "chat"), { code: "explicit_capability_unavailable" }) + // prototype-1236: native read-only panels follow the current connection like chat. + for (const feature of ["files", "git", "backgroundShells", "yolo", "providerUsage", "plugins"] as const) { + assert.equal(descriptor.capabilities!.features[feature].state, available ? "available" : "unavailable") + } + for (const feature of ["worktrees", "terminal", "missions", "automation", "executionSettings"] as const) { + assert.equal(descriptor.capabilities!.features[feature].state, "unavailable") + assert.throws(() => f.manager.requireWorkspaceCapability(id, feature), { code: "explicit_capability_unavailable" }) + } + } + assert.deepEqual(f.manager.get(b.id)!.capabilities, stableB) + assert.equal(f.manager.get(local.id), stableLocal) + assert.equal(f.manager.list().find(value => value.id === local.id), stableLocal) + assert.doesNotThrow(() => f.manager.requireWorkspaceCapability(local.id, "executionSettings")) + assert.equal(f.calls.length, before) + assert.equal(acquire.mock.callCount(), 0) + assert.equal(workspaceAcquire.mock.callCount(), 0) + assert.equal(worktrees.mock.callCount(), 0) + assert.deepEqual(hostCalls, []) + } finally { + acquire.mock.restore(); workspaceAcquire.mock.restore(); worktrees.mock.restore() + for (const mock of mocks) mock.mock.restore() + syncBuiltinESMExports() + } + } + inspect(true) + f.connections.invalidateServer("A") + inspect(false) + f.contract({}) + await assert.rejects(f.manager.acquireForWorkspace(a.id)) + inspect(false) + f.contract(explicitContractFixture()) + const current = (await f.manager.acquireForWorkspace(a2.id))! + inspect(true, (current as ServerConnection).generation) + assert.notEqual(old.capabilities!.generation, f.manager.get(a.id)!.capabilities!.generation) + assert.equal(old.capabilities!.features.chat.state, "available") + assert.equal(old.capabilities!.generation, a.capabilities!.generation) + const untrusted = f.manager.get(a.id)! + untrusted.capabilities!.features.worktrees = { state: "available", evidence: "nativeContract", reason: { code: "contractVerified" } } + assert.throws(() => f.manager.requireWorkspaceCapability(a.id, "worktrees"), { code: "explicit_capability_unavailable" }) + inspect(true) + const before = f.calls.length + await assert.rejects(previous.client.session.get({ sessionID: "same-session" })) + assert.equal(f.calls.length, before) + await f.credentials.set("A", JSON.stringify({ username: "rotated", password: "fixture-only" })) + inspect(false) + await f.manager.acquireForWorkspace(a.id) + inspect(true) + await f.credentials.clear("A") + inspect(false) + await assert.rejects(f.manager.acquireForWorkspace(a.id), { code: "needs_credentials" }) + inspect(false) + await f.credentials.set("A", JSON.stringify({ username: "reentered", password: "fixture-only" })) + await f.manager.acquireForWorkspace(a.id) + inspect(true) + f.connections.disconnect("A") + inspect(false) + await assert.rejects(f.manager.acquireForWorkspace(a.id), { code: "disconnected" }) + await f.connections.connect("A") + inspect(true) + await f.manager.delete(a.id) + assert.equal(f.connections.activeExplicitTargets, 2) + await f.manager.delete(a2.id) + assert.equal(f.connections.activeExplicitTargets, 1) +}) + +test("pending replacement and late superseded negotiation cannot restore capability authority", async t => { + const f = await fixture(); t.after(() => { f.finish(); return f.close() }) + const { workspace } = await f.manager.create("/exact", undefined, { serverId: "A" }) + const old = f.manager.get(workspace.id)! + f.connections.invalidateServer("A") + f.block("contract") + const pending = f.manager.acquireForWorkspace(workspace.id) + const rejected = assert.rejects(pending) + await f.entered + assert.equal(f.manager.get(workspace.id)!.capabilities!.features.chat.state, "unknown") + await f.credentials.set("A", JSON.stringify({ username: "new", password: "fixture-only" })) + f.finish() + const current = (await f.manager.acquireForWorkspace(workspace.id))! + await rejected + assert.equal(f.manager.get(workspace.id)!.capabilities!.generation, (current as ServerConnection).generation) + assert.notEqual(old.capabilities!.generation, f.manager.get(workspace.id)!.capabilities!.generation) +}) + +test("attachment inventory observes real unpublished reservations and never equates a browser or retained shell with full coverage", async t => { + const f = await fixture(); t.after(() => { f.finish(); return f.close() }) + const before = f.manager.attachmentReservations("A") + f.block("list") + const pending = f.manager.create("/exact", undefined, { serverId: "A" }) + await f.entered + assert.deepEqual(f.manager.list(), []) + assert.equal(f.manager.attachmentReceiptCurrent(before.receipt), false) + const during = f.manager.attachmentReservations("A") + assert.equal(during.reservations.length, 1) + assert.equal(during.reservations[0]!.state, "reserved") + assert.equal(f.connections.attachmentReservations("A").reservations.length, 1) + assert.equal(f.connections.attachmentReservations("A").inFlight, true) + const browser = await f.manager.readServerAttachments({ available: false, request: async () => { throw new Error("no parent") } }, "A") + assert.equal(browser.status, "unknown") + assert.equal(browser.backend!.leases.reservations.length, 1) + assert.equal(await browser.isCurrent(), false) + f.finish() + const { workspace } = await pending + assert.equal(f.manager.attachmentReceiptCurrent(during.receipt), false) + assert.equal(f.manager.attachmentReservations("A").reservations[0]!.state, "published") + assert.equal(f.connections.attachmentReservations("A").reservations[0]!.instanceId, workspace.id) + await f.manager.delete(workspace.id) + assert.equal(f.manager.attachmentReservations("A").reservations.length, 0) + assert.equal(f.connections.attachmentReservations("A").reservations.length, 0) +}) + +test("inventory captures before private transport await; an old zero reader never adopts a newly attached occurrence", async t => { + const f = await fixture(); t.after(() => f.close()) + let release!: (value: unknown) => void + const held = new Promise(resolve => { release = resolve }) + const receipt = "11111111-1111-4111-8111-111111111111", ownerId = "22222222-2222-4222-8222-222222222222" + const metadata = { receipt, status: "unknown", retainedStatus: "complete", owners: [{ ownerId, live: true, retained: true }], + refs: [{ ownerId, tabId: "33333333-3333-4333-8333-333333333333", source: "retained", serverId: "orphan", directory: "/Saved/Case " }] } + const parent = { available: true, request: async (method: string): Promise => (method.endsWith(".read") ? held : true) as Promise } + const old = f.manager.readServerAttachments(parent, "A") + const { workspace } = await f.manager.create("/exact", undefined, { serverId: "A" }) + release(metadata) + const stale = await old + assert.equal(stale.status, "unknown") + assert.equal(stale.backend, undefined) + assert.deepEqual(stale.refs, []) + assert.equal(await stale.isCurrent(), false) + const fresh = await f.manager.readServerAttachments(parent, "orphan") + assert.equal(await fresh.isCurrent(), true) + assert.equal(fresh.status, "unknown") + assert.equal(fresh.refs[0]!.directory, "/Saved/Case ") + const before = f.calls.length + await f.manager.delete(workspace.id) + assert.equal(await fresh.isCurrent(), false) + assert.equal(f.calls.length, before) +}) + +const inventoryCorruption = { credential: "PRIVATE_INVENTORY_CREDENTIAL_SENTINEL", directory: "PRIVATE_INVENTORY_CORRUPT_DIRECTORY\0path" } +function assertNoInventoryCorruption(value: unknown) { + const serialized = JSON.stringify(value) + for (const marker of Object.values(inventoryCorruption)) assert.equal(serialized.includes(JSON.stringify(marker).slice(1, -1)), false) +} + +test("inventory privacy oracle accepts legitimate UUIDs and detects every exact injected corruption marker", () => { + const safe = { receipt: "427bad92-e7e1-4f22-bf05-45c9dd5b2fb6", status: "unknown", refs: [] } + assertNoInventoryCorruption(safe) + for (const [field, marker] of Object.entries(inventoryCorruption)) { + assert.throws(() => assertNoInventoryCorruption({ ...safe, [field]: marker }), { code: "ERR_ASSERTION" }) + } +}) + +test("private inventory refuses unsupported, oversized and forged host projections without granting absence", async t => { + const f = await fixture(); t.after(() => f.close()) + const receipt = "11111111-1111-4111-8111-111111111111", ownerId = "22222222-2222-4222-8222-222222222222" + const base = { receipt, status: "unknown", retainedStatus: "complete", owners: [{ ownerId, live: true, retained: true }], refs: [] } + const ref = { ownerId, tabId: "33333333-3333-4333-8333-333333333333", source: "retained", serverId: "A", directory: "/exact" } + for (const value of [null, { ...base, status: "complete" }, { ...base, credential: inventoryCorruption.credential }, + { ...base, refs: [{ ...ref, ownerId: "44444444-4444-4444-8444-444444444444" }] }, + { ...base, owners: [base.owners[0], base.owners[0]] }, { ...base, refs: Array(513).fill(ref) }, + { ...base, refs: [{ ...ref, directory: inventoryCorruption.directory }] }, { ...base, refs: [ref, ref] }, + { ...base, refs: [{ ...ref, directory: "x".repeat(8 * 1024 * 1024) }] }]) { + const parent = { available: true, request: async (): Promise => value as T } + const result = await f.manager.readServerAttachments(parent, "A") + assert.equal(result.status, "unknown") + assert.deepEqual(result.refs, []) + assert.equal(await result.isCurrent(), false) + assertNoInventoryCorruption(result) + } + const parent = { available: true, request: async (method: string): Promise => (method.endsWith(".read") ? { ...base, refs: [ref] } : true) as T } + const fresh = await f.manager.readServerAttachments(parent, "A") + assert.equal(fresh.status, "unknown") + assert.deepEqual(fresh.refs, [ref]) + assert.equal(await fresh.isCurrent(), true) + assertNoInventoryCorruption(fresh) + assert.deepEqual(f.calls, []) +}) + +test("real manager captures participant admission before private awaits and preserves independent unknown coverage", async t => { + const f = await fixture(); t.after(() => f.close()) + let release!: (value: unknown) => void + const held = new Promise(resolve => { release = resolve }) + const parent = { available: true, request: async (method: string): Promise => (method.endsWith(".read") ? held : true) as Promise } + const pending = f.manager.readServerAttachments(parent, "A") + const participant = f.manager.projectParticipants.register("private-principal", () => true)! + const declaration = { revision: 1, refs: [{ tabId: "33333333-3333-4333-8333-333333333333", serverId: "A", directory: "Z:\\Opaque\\é/שלום " }] } + assert.equal(f.manager.projectParticipants.admit(participant.grant.token, "private-principal")!.publish(declaration, () => { assert.fail("no workspace selector") }), true) + release({ receipt: "11111111-1111-4111-8111-111111111111", status: "unknown", retainedStatus: "unknown", owners: [], refs: [] }) + const stale = await pending + assert.equal(stale.backend, undefined) + assert.equal(stale.participants, undefined) + assert.equal(await stale.isCurrent(), false) + const fresh = await f.manager.readServerAttachments(parent, "A") + assert.equal(fresh.status, "unknown") + assert.equal(fresh.coverage.participants, "unknown") + assert.equal(fresh.participants!.refs[0]!.directory, declaration.refs[0]!.directory) + assert.equal(await fresh.isCurrent(), true, "current declarations retain their narrower metadata scope") + participant.close() + assert.equal(await fresh.isCurrent(), false) + assert.deepEqual(f.calls, []) + assert.doesNotMatch(JSON.stringify(fresh), new RegExp(`${participant.grant.token}|private-principal`)) +}) + +test("native and participant observations share the original owner ceiling without dropping source membership", async t => { + const f = await fixture(); t.after(() => f.close()) + const participants = Array.from({ length: 32 }, () => f.manager.projectParticipants.register("principal", () => true)!) + const metadata = { receipt: "11111111-1111-4111-8111-111111111111", status: "unknown", retainedStatus: "unknown", + owners: [{ ownerId: "22222222-2222-4222-8222-222222222222", live: true, retained: false }], refs: [] } + const parent = { available: true, request: async (method: string): Promise => (method.endsWith(".read") ? metadata : true) as T } + const observed = await f.manager.readServerAttachments(parent, "A") + assert.equal(observed.status, "unknown") + assert.equal(observed.observationOverflow, true) + assert.equal(observed.participants, undefined) + assert.deepEqual(observed.owners, []) + assert.equal(f.manager.projectParticipants.snapshot("A").owners.length, participants.length) + assert.deepEqual(f.calls, []) +}) diff --git a/packages/server/src/workspaces/explicit-workspace.ts b/packages/server/src/workspaces/explicit-workspace.ts new file mode 100644 index 0000000000..b2f8400796 --- /dev/null +++ b/packages/server/src/workspaces/explicit-workspace.ts @@ -0,0 +1,136 @@ +import { OpenCode, type LocationRef, type OpenCodeClient } from "@opencode/client" +import { FileSystem } from "@opencode/schema/filesystem" +import { Schema } from "effect" +import type { OpenCodeServerConnections, ServerConnection, ServerProjectLease } from "../opencode/servers/connections" +import { initialServerCapabilities, requireServerCapability, type ServerCapability } from "../opencode/servers/capabilities" +import type { ProjectExecutionBinding } from "../opencode/servers/types" +import type { ServiceConnection } from "./opencode-service" +import { readLocationRef } from "../opencode/compatibility/location" + +const isNativeListing = Schema.is(Schema.Array(FileSystem.Entry)) + +export class ExplicitWorkspaceError extends Error { + constructor(readonly code: "explicit_open_not_ready" | "explicit_location_unavailable" | "explicit_capability_unavailable") { + super(code) + this.name = "ExplicitWorkspaceError" + } +} + +/** One logical occurrence: no host paths, environment, discovery or session mutations. */ +export class ExplicitWorkspace { + readonly binding: Readonly + readonly #lease: ServerProjectLease + #released = false + #connection?: ServiceConnection + + constructor(private readonly connections: OpenCodeServerConnections, binding: ProjectExecutionBinding) { + if (!binding.serverId || binding.serverId === "local-shared" || !binding.directory || binding.directory.includes("\0")) { + throw new ExplicitWorkspaceError("explicit_location_unavailable") + } + this.binding = Object.freeze({ serverId: binding.serverId, directory: binding.directory }) + // Retain before any asynchronous admission/validation; this also spans publication. + this.#lease = connections.retainProject(this.binding) + } + + async validate(signal: AbortSignal) { + const connection = await this.#lease.acquire() + this.assertCurrent(connection, signal) + const lifetime = AbortSignal.any([signal, AbortSignal.timeout(5_000)]) + // Bound native location and readability proof, including the response body. A listing + // is only an attachment proof; it grants no Files capability or directory descendants. + const client = OpenCode.make({ baseUrl: connection.endpoint.url, fetch: async (input, init) => { + this.assertCurrent(connection, lifetime) + const response = await connection.fetch(input, { ...init, signal: lifetime }) + const reader = response.body?.getReader() + if (!reader) throw new ExplicitWorkspaceError("explicit_location_unavailable") + let length = 0 + const chunks: Uint8Array[] = [] + try { + while (true) { + const chunk = await reader.read() + this.assertCurrent(connection, lifetime) + if (chunk.done) break + length += chunk.value.byteLength + if (length > 8 * 1024 * 1024) throw new ExplicitWorkspaceError("explicit_location_unavailable") + chunks.push(chunk.value) + } + } catch (error) { await reader.cancel().catch(() => {}); throw error } + finally { reader.releaseLock() } + return new Response(Buffer.concat(chunks, length), { status: response.status, headers: response.headers }) + } }) + try { + const location = await client.location.get({ location: { directory: this.binding.directory } }, { signal: lifetime }) + this.assertCurrent(connection, lifetime) + if (location.directory !== this.binding.directory || readLocationRef(location).workspaceID !== undefined + || typeof location.project?.id !== "string" || !location.project.id) throw new ExplicitWorkspaceError("explicit_location_unavailable") + const listing = await client.file.list({ location: { directory: this.binding.directory }, path: "." }, { signal: lifetime }) + this.assertCurrent(connection, lifetime) + if (listing.location.directory !== this.binding.directory || readLocationRef(listing.location).workspaceID !== undefined + || !isNativeListing(listing.data)) throw new ExplicitWorkspaceError("explicit_location_unavailable") + this.#connection = connection + return { directory: this.binding.directory } + } catch { + this.assertCurrent(connection, signal) + throw new ExplicitWorkspaceError("explicit_location_unavailable") + } + } + + capabilities() { + // The connection owner publishes only negotiated connections. Inspect it without + // acquisition: pending, failed and revoked connections confer no authority. + let connection: ServerConnection | undefined + if (!this.#released) { + try { connection = this.connections.existingForServer(this.binding.serverId) as ServerConnection | undefined } + catch { /* A superseded connection leaves an unverified display snapshot. */ } + } + const capabilities = initialServerCapabilities({ id: this.binding.serverId, kind: "explicit", label: this.binding.serverId, + origin: connection?.endpoint.url ?? "" }, connection?.generation ?? 0) + if (connection) { + // prototype-1236: read-only Files/Changes, background shells, Yolo, published quotas and plugin inventory, all native. + for (const feature of ["sessions", "chat", "media", "permissions", "questions", "events", + "files", "git", "backgroundShells", "yolo", "providerUsage", "plugins"] as const) { + capabilities.features[feature] = { state: "available", reason: { code: "contractVerified" }, evidence: "nativeContract" } + } + } + return capabilities + } + + requireCapability(capability: ServerCapability) { + if (this.#released || !this.#connection) throw new ExplicitWorkspaceError("explicit_location_unavailable") + // Private current-connection policy owns admission; descriptors are snapshots. + requireServerCapability(capability, this.capabilities().features[capability]) + } + + async acquire() { + const connection = await this.connections.acquireForWorkspace(this.binding) + this.assertCurrent(connection) + return connection + } + + ownsLocation(location: LocationRef, connection: ServiceConnection, client?: OpenCodeClient): boolean { + this.assertCurrent(connection) + return (!client || client === connection.client) && location.workspaceID === undefined && location.directory === this.binding.directory + } + + async ownsSession(sessionID: string) { + const connection = await this.acquire() + const session = await connection.client.session.get({ sessionID }) + this.assertCurrent(connection) + return session?.id === sessionID && Boolean(session.location) && this.ownsLocation(session.location, connection) + } + + assertCurrent(connection = this.#connection, signal?: AbortSignal) { + signal?.throwIfAborted() + if (this.#released) throw new ExplicitWorkspaceError("explicit_location_unavailable") + if (connection && (connection as ServerConnection).serverId !== this.binding.serverId) throw new ExplicitWorkspaceError("explicit_location_unavailable") + connection?.assertCurrent() + } + + release() { + if (this.#released) return + this.#released = true + this.#lease.release() + } + + published(instanceId: string) { this.#lease.published(instanceId) } +} diff --git a/packages/server/src/workspaces/git-clone.ts b/packages/server/src/workspaces/git-clone.ts index b0eeb48a0f..155c893cd8 100644 --- a/packages/server/src/workspaces/git-clone.ts +++ b/packages/server/src/workspaces/git-clone.ts @@ -2,6 +2,7 @@ import fs from "fs" import path from "path" import { spawn } from "child_process" import { homedir } from "os" +import { WorkspaceCapabilityError } from "../opencode/servers/capabilities" class GitCloneError extends Error { statusCode: number @@ -149,10 +150,14 @@ export function isGitCloneError(error: unknown): error is GitCloneError { } export async function cloneGitRepository(params: { + serverId?: string repositoryUrl: string destinationPath: string cleanup?: boolean }): Promise<{ path: string }> { + if (params.serverId !== undefined && params.serverId !== "local-shared") { + throw new WorkspaceCapabilityError("git", { code: "deferred" }) + } const repositoryUrl = params.repositoryUrl.trim() const requestedDestinationPath = params.destinationPath.trim() diff --git a/packages/server/src/workspaces/instance-client.ts b/packages/server/src/workspaces/instance-client.ts index aa79b80f18..2e7866691e 100644 --- a/packages/server/src/workspaces/instance-client.ts +++ b/packages/server/src/workspaces/instance-client.ts @@ -2,13 +2,12 @@ import type { OpenCodeClient } from "@opencode/client" import type { WorkspaceManager } from "./manager" /** - * Returns the shared native OpenCode client when the logical workspace is ready. + * Returns the connection pinned to the published logical workspace. * Session APIs resolve their location from the session itself. */ export async function createInstanceClient( workspaceManager: WorkspaceManager, instanceId: string, ): Promise { - if (!workspaceManager.get(instanceId)) return null - return workspaceManager.getSharedServiceClient() + return (await workspaceManager.getSharedServiceConnection(instanceId))?.client ?? null } diff --git a/packages/server/src/workspaces/instance-event-queue.ts b/packages/server/src/workspaces/instance-event-queue.ts index a7f3351a8c..534d31b6f0 100644 --- a/packages/server/src/workspaces/instance-event-queue.ts +++ b/packages/server/src/workspaces/instance-event-queue.ts @@ -1,6 +1,32 @@ -type Job = { run: () => Promise; bytes: number; deadline: number } +export type InstanceEventReservation = { deliveries: Map } +type Job = { run: (reservation: InstanceEventReservation) => Promise; bytes: number; deadline: number; reservation: InstanceEventReservation } type Lane = { jobs: Job[]; timer?: ReturnType } +export class InstanceEventQueueError extends Error { + constructor(readonly gap: "overflow" | "deadline") { + super(gap === "overflow" ? "Instance event relay backlog exceeded its budget" : "Instance event relay routing timed out") + } +} + +/** Fixed shares; existing local work drains naturally when explicit shares activate. */ +export class InstanceEventBudget { + explicitSources = 0 + jobs = 0 + bytes = 0 + + admit(jobs: number, bytes: number): boolean { + if (this.jobs + jobs > 2048 || this.bytes + bytes > 32 * 1024 * 1024) return false + this.jobs += jobs + this.bytes += bytes + return true + } + + release(jobs: number, bytes: number): void { + this.jobs -= jobs + this.bytes -= bytes + } +} + /** FIFO per native entity/recipient, without head-of-line blocking other lanes. * Exceeding the retained-work budget fails the subscription; reconnect performs * authoritative reconciliation rather than silently dropping individual deltas. @@ -10,21 +36,49 @@ export class InstanceEventQueue { private count = 0 private bytes = 0 private closed = false + private sharing: boolean + private transitionGap = false constructor(private readonly fail: (error: Error) => void, private readonly limits = { jobs: 2048, bytes: 32 * 1024 * 1024, timeoutMs: 60_000, - }) {} + }, private readonly budget?: InstanceEventBudget, private readonly explicit = false, + private readonly drainingGap?: () => void) { this.sharing = Boolean(budget?.explicitSources) } - enqueue(key: string, bytes: number, run: () => Promise): void { + enqueue(key: string, bytes: number, run: (reservation: InstanceEventReservation) => Promise, receivedAt = Date.now(), deliveries = new Map()): void { if (this.closed) return - if (this.count + 1 > this.limits.jobs || this.bytes + bytes > this.limits.bytes) { - this.reject(new Error("Instance event relay backlog exceeded its budget")) + const jobs = this.budget ? this.explicit ? 448 : this.budget.explicitSources ? 256 : 2048 : this.limits.jobs + const byteLimit = this.budget ? (this.explicit ? 7 : this.budget.explicitSources ? 4 : 32) * 1024 * 1024 : this.limits.bytes + const sharing = Boolean(this.budget?.explicitSources) + if (!this.explicit && !this.sharing && sharing && (this.count > jobs || this.bytes > byteLimit)) { + // Keep grandfathered work, including prepaid deliveries. An observed gap + // stops new admission until it drains, then reconnects authoritatively. + this.transitionGap = true + this.drainingGap?.() + } + this.sharing = sharing + if (this.transitionGap) return + const retainedJobs = 1 + deliveries.size + const retainedBytes = bytes + [...deliveries.values()].reduce((sum, value) => sum + value, 0) + if (this.count + retainedJobs > jobs || this.bytes + retainedBytes > byteLimit || (this.budget && !this.budget.admit(retainedJobs, retainedBytes))) { + this.reject(new InstanceEventQueueError("overflow")) return } - this.count++ - this.bytes += bytes + this.count += retainedJobs + this.bytes += retainedBytes + this.schedule(key, { run, bytes, deadline: receivedAt + this.limits.timeoutMs, reservation: { deliveries } }) + } + + /** Delivery capacity was charged at ingestion, before any ownership wait. */ + enqueueDelivery(key: string, reservation: InstanceEventReservation, recipient: string, run: () => Promise, receivedAt: number): void { + if (this.closed) return + const bytes = reservation.deliveries.get(recipient) + if (bytes === undefined) return + reservation.deliveries.delete(recipient) + this.schedule(key, { run, bytes, deadline: receivedAt + this.limits.timeoutMs, reservation: { deliveries: new Map() } }) + } + + private schedule(key: string, job: Job): void { const existing = this.lanes.get(key) - const job = { run, bytes, deadline: Date.now() + this.limits.timeoutMs } if (existing) existing.jobs.push(job) else { const lane: Lane = { jobs: [job] } @@ -39,9 +93,11 @@ export class InstanceEventQueue { this.closed = true for (const lane of this.lanes.values()) { clearTimeout(lane.timer) + for (const job of lane.jobs) job.reservation.deliveries.clear() lane.jobs.length = 0 } this.lanes.clear() + this.budget?.release(this.count, this.bytes) this.count = this.bytes = 0 } @@ -52,17 +108,20 @@ export class InstanceEventQueue { } private async drain(key: string, lane: Lane): Promise { + let batch = 0 while (!this.closed && lane.jobs.length) { + if (++batch % 32 === 0) await new Promise(resolve => setImmediate(resolve)) + if (this.closed) return const job = lane.jobs[0] const remaining = job.deadline - Date.now() if (remaining <= 0) { - this.reject(new Error("Instance event relay routing timed out")) + this.reject(new InstanceEventQueueError("deadline")) return } - lane.timer = setTimeout(() => this.reject(new Error("Instance event relay routing timed out")), remaining) + lane.timer = setTimeout(() => this.reject(new InstanceEventQueueError("deadline")), remaining) lane.timer.unref?.() try { - await job.run() + await job.run(job.reservation) } catch (error) { this.reject(error instanceof Error ? error : new Error(String(error))) } finally { @@ -70,8 +129,16 @@ export class InstanceEventQueue { } if (this.closed) return lane.jobs.shift() - this.count-- - this.bytes -= job.bytes + const jobs = 1 + job.reservation.deliveries.size + const bytes = job.bytes + [...job.reservation.deliveries.values()].reduce((sum, value) => sum + value, 0) + job.reservation.deliveries.clear() + this.count -= jobs + this.bytes -= bytes + this.budget?.release(jobs, bytes) + if (this.count === 0 && this.transitionGap) { + this.reject(new InstanceEventQueueError("overflow")) + return + } } this.lanes.delete(key) } diff --git a/packages/server/src/workspaces/instance-events-multiserver.test.ts b/packages/server/src/workspaces/instance-events-multiserver.test.ts new file mode 100644 index 0000000000..fffcfb849b --- /dev/null +++ b/packages/server/src/workspaces/instance-events-multiserver.test.ts @@ -0,0 +1,351 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import type { LocationRef, OpenCodeEvent } from "@opencode/client" +import { EventBus } from "../events/bus" +import type { WorkspaceEventPayload } from "../api-types" +import type { Logger } from "../logger" +import type { WorkspaceManager } from "./manager" +import { InstanceEventBridge } from "./instance-events" +import { InstanceEventBudget, InstanceEventQueue } from "./instance-event-queue" +import { nativeEventConnections, type ServiceConnection } from "./opencode-service" + +const turn = () => new Promise(resolve => setImmediate(resolve)) +async function until(check: () => boolean) { + const end = Date.now() + 3000 + while (!check()) { assert.ok(Date.now() < end, "relay did not settle"); await turn() } +} +function deferred() { + let resolve!: (value: T) => void + const promise = new Promise(done => { resolve = done }) + return { promise, resolve } +} +const event = (type: string, data: object = {}, location?: LocationRef) => ({ + id: "same-event", created: Date.now(), type, data, ...(location ? { location } : {}), +}) as OpenCodeEvent + +class Feed { + items: (OpenCodeEvent | Error)[] = [] + wake = deferred() + closed = false + send(value: OpenCodeEvent | Error) { this.items.push(value); this.wake.resolve() } + async *read(signal: AbortSignal) { + const abort = () => this.wake.resolve() + signal.addEventListener("abort", abort, { once: true }) + try { + yield event("server.connected") + while (!signal.aborted) { + const item = this.items.shift() + if (item instanceof Error) throw item + if (item) yield item + else { await this.wake.promise; this.wake = deferred() } + } + } finally { this.closed = true; signal.removeEventListener("abort", abort) } + } +} + +function harness() { + const bus = new EventBus() + const workspaces: any[] = ["local-shared", "A", "B"].map(serverId => ({ + id: serverId, path: "/same", binding: { serverId, directory: "/same" }, + })) + const frames: WorkspaceEventPayload[] = [] + bus.on("instance.event", value => frames.push(value)) + bus.on("instance.eventStatus", value => frames.push(value)) + const streams = new Map() + const controllers = new Map() + const connections = new Map() + const sessionReads: string[] = [] + const ownershipRequests: string[] = [] + let observe!: (ids: readonly string[], credentialsChanged?: string) => void + let admitted: string[] = [] + let localInvalidations = 0 + let nativeGeneration = 40 + let blockA: Promise | undefined + function connection(id: string) { + let value = connections.get(id) + if (value) return value + const controller = new AbortController() + controllers.set(id, controller) + value = { + generation: ++nativeGeneration, + signal: controller.signal, + endpoint: { url: `https://${id}.example` }, + assertCurrent: () => controller.signal.throwIfAborted(), + invalidate() { controller.abort(); connections.delete(id) }, + client: { + event: { subscribe({ signal }: { signal: AbortSignal }) { + const feed = new Feed() + streams.set(id, [...(streams.get(id) ?? []), feed]) + return feed.read(signal) + } }, + session: { get: async ({ sessionID }: { sessionID: string }) => { + sessionReads.push(id) + if (sessionID === "missing") throw Object.assign(new Error("not found"), { _tag: "SessionNotFoundError" }) + return { location: { directory: "/same" } } + } }, + }, + } as unknown as ServiceConnection + connections.set(id, value) + return value + } + const manager = { + list: () => workspaces, + observeAdmittedEventSources(listener: typeof observe) { observe = listener; listener(admitted); return () => { observe = () => {} } }, + getServerConnections: () => ({ acquireForServer: async (id: string) => { + assert.ok(admitted.includes(id), "ordinary event work cannot admit a target") + return connection(id) + } }), + subscribeToSharedService: async (signal: AbortSignal) => { + const captured = connection("local-shared") + const events = captured.client.event.subscribe({ signal }) + return (async function* () { for await (const item of events) { nativeEventConnections.set(item, captured); yield item } })() + }, + ownsDirectory: async () => true, + ownsLocation: async (id: string, location: LocationRef, client: unknown) => { + ownershipRequests.push(id) + assert.equal(client, connections.get(id === "A2" ? "A" : id)?.client) + if (id === "A" && blockA) return blockA + return location.directory === "/same" && location.workspaceID === undefined + }, + invalidateWorktrees: () => { localInvalidations++ }, + } as unknown as WorkspaceManager + const bridge = new InstanceEventBridge({ workspaceManager: manager, eventBus: bus, logger: { debug() {}, warn() {} } as unknown as Logger }) + const admit = (...ids: string[]) => { admitted = ids; observe(ids) } + const business = () => frames.filter((value): value is Extract => value.type === "instance.event" && value.event.type !== "server.connected") + return { bridge, bus, workspaces, frames, streams, controllers, connections, sessionReads, ownershipRequests, admit, business, + rotate(id: string) { connections.get(id)?.invalidate(); observe(admitted, id) }, + blockA(value: Promise) { blockA = value }, localInvalidations: () => localInvalidations, + } +} + +test("local/A/B identical IDs, globals, missing locations and deletions stay on their captured source", async t => { + const h = harness(); t.after(() => h.bridge.shutdown()) + h.admit("A", "B") + h.bus.publish({ type: "workspace.started", workspace: h.workspaces[0] }) + await until(() => h.streams.size === 3) + for (const id of ["A", "B", "local-shared"]) { + h.streams.get(id)![0].send(event("session.text.delta", { sessionID: "same-session", delta: id })) + h.streams.get(id)![0].send(event("model.updated")) + h.streams.get(id)![0].send(event("session.deleted", { sessionID: "same-session" })) + } + await until(() => h.business().length === 9) + assert.deepEqual(h.sessionReads.sort(), ["A", "B", "local-shared"].sort()) + for (const frame of h.business()) { + assert.equal(frame.instanceId, frame.source!.serverId) + assert.ok(frame.source!.generation > 0) + assert.ok(nativeEventConnections.get(frame.event), "native attribution survives marker copies and delivery") + } + h.streams.get("A")![0].send(event("worktree.updated")) + await until(() => h.business().length === 10) + assert.equal(h.localInvalidations(), 0) +}) + +test("one admitted stream serves two occurrences, late attach receives current marker; release cancels without reacquisition", async t => { + const h = harness(); t.after(() => h.bridge.shutdown()) + h.admit("A") + await until(() => h.streams.get("A")?.length === 1) + await turn() + h.workspaces.push({ id: "A2", path: "/same", binding: { serverId: "A", directory: "/same" } }) + h.bus.publish({ type: "workspace.started", workspace: h.workspaces.at(-1)! }) + await until(() => h.frames.some(value => value.type === "instance.event" && value.instanceId === "A2" && value.event.type === "server.connected")) + assert.equal(h.streams.get("A")!.length, 1) + const feed = h.streams.get("A")![0] + h.admit() + await until(() => feed.closed) + feed.send(event("model.updated")) + h.bus.publish({ type: "workspace.started", workspace: h.workspaces.at(-1)! }) + await turn() + assert.equal(h.streams.get("A")!.length, 1) + assert.equal(h.business().length, 0) +}) + +test("global Forms retain source-bound full Location; unknown deletion produces only that source's bounded gap", async t => { + const h = harness(); t.after(() => h.bridge.shutdown()) + h.admit("A", "B") + await until(() => h.streams.size === 2) + for (const id of ["A", "B"]) { + h.streams.get(id)![0].send(event("form.created", { form: { id: "same-form", sessionID: "global" } }, { directory: "/same" })) + h.streams.get(id)![0].send(event("form.cancelled", { id: "same-form", sessionID: "global" })) + } + await until(() => h.business().length === 4) + assert.equal(h.sessionReads.length, 0) + for (const frame of h.business()) assert.equal(frame.instanceId, frame.source!.serverId) + for (let i = 0; i < 30; i++) h.streams.get("A")![0].send(event("session.deleted", { sessionID: "missing" })) + await until(() => h.frames.some(value => value.type === "instance.eventStatus" && value.gap === "ownership")) + await turn() + const gaps = h.frames.filter(value => value.type === "instance.eventStatus" && value.gap === "ownership") + assert.equal(gaps.length, 1) + assert.equal((gaps[0] as any).source.serverId, "A") + assert.equal(h.business().some(value => value.event.type === "session.deleted"), false) +}) + +test("blocked and flooded A cannot starve B or local; overflow is attributed only to A", async t => { + const h = harness(), blocked = deferred() + t.after(() => { h.bridge.shutdown(); blocked.resolve(false) }) + h.blockA(blocked.promise) + h.admit("A", "B") + h.bus.publish({ type: "workspace.started", workspace: h.workspaces[0] }) + await until(() => h.streams.size === 3) + for (let i = 0; i < 600; i++) h.streams.get("A")![0].send(event("session.text.delta", { sessionID: "same-session", delta: "a" }, { directory: "/same" })) + for (const id of ["B", "local-shared"]) h.streams.get(id)![0].send(event("model.updated")) + await until(() => h.business().some(value => value.instanceId === "B") && h.business().some(value => value.instanceId === "local-shared")) + await until(() => h.frames.some(value => value.type === "instance.eventStatus" && value.gap === "overflow")) + assert.ok(h.frames.filter(value => value.type === "instance.eventStatus" && value.gap === "overflow").every(value => value.type === "instance.eventStatus" && value.source?.serverId === "A")) + assert.equal(h.business().some(value => value.instanceId === "A"), false) +}) + +test("credential revocation cancels the iterator and stale deliveries; retry keeps the admitted slot and advances only its source", async t => { + t.mock.timers.enable({ apis: ["setTimeout"] }) + const h = harness(), blocked = deferred() + t.after(() => { h.bridge.shutdown(); blocked.resolve(false) }) + h.admit("A", "B") + await until(() => h.streams.size === 2) + await turn() + h.blockA(blocked.promise) + const before = h.frames.find(value => value.type === "instance.eventStatus" && value.instanceId === "A" && value.status === "connected")! + h.streams.get("A")![0].send(event("session.text.delta", { sessionID: "same-session", delta: "old" }, { directory: "/same" })) + await turn() + h.connections.get("A")!.invalidate() + await until(() => h.streams.get("A")![0].closed) + await turn() + t.mock.timers.tick(2000) + await until(() => h.streams.get("A")!.length === 2) + blocked.resolve(true) + await turn() + assert.equal(h.business().length, 0) + h.streams.get("A")![1].send(event("model.updated")) + await until(() => h.business().length === 1) + assert.ok(h.business()[0].source!.generation > (before as any).source.generation) + assert.equal(h.streams.get("B")!.length, 1) + const markers = h.frames.filter((value): value is Extract => value.type === "instance.event" && value.instanceId === "A" && value.event.type === "server.connected") + assert.notEqual((markers[0].event.data as any).daemon, (markers.at(-1)!.event.data as any).daemon, + "an explicit attempt cannot claim verified daemon continuity") +}) + +test("credential rotation interrupts an offline retry timer immediately without a new admission", async t => { + t.mock.timers.enable({ apis: ["setTimeout"] }) + const h = harness(); t.after(() => h.bridge.shutdown()) + h.admit("A") + await until(() => h.streams.get("A")?.length === 1) + h.streams.get("A")![0].send(new Error("offline")) + await until(() => h.frames.some(value => value.type === "instance.eventStatus" && value.gap === "transport")) + h.rotate("A") + await until(() => h.streams.get("A")!.length === 2) +}) + +test("fixed shares include active work, preserve admitted local work during transition and release counters exactly once", async () => { + const budget = new InstanceEventBudget(), blocked = deferred() + let failures = 0 + const local = new InstanceEventQueue(() => { failures++ }, undefined, budget) + for (let i = 0; i < 1800; i++) local.enqueue("same", 1, () => blocked.promise) + assert.equal(budget.jobs, 1800) + budget.explicitSources = 1 + const a = new InstanceEventQueue(() => { failures++ }, undefined, budget, true) + for (let i = 0; i < 249; i++) a.enqueue("same", 1, () => blocked.promise) + assert.equal(failures, 1) + assert.equal(local.pending, 1800, "activation cannot cancel previously admitted local jobs") + assert.equal(budget.jobs, 1800) + a.close(); local.close(); local.close() + blocked.resolve() + await turn() + assert.equal(budget.jobs, 0) + assert.equal(budget.bytes, 0) +}) + +test("delivery deadline uses ingestion time rather than restarting after resolution", async () => { + let error: Error | undefined, ran = false + const queue = new InstanceEventQueue(value => { error = value }, { jobs: 10, bytes: 100, timeoutMs: 10 }) + queue.enqueue("delivery", 1, async () => { ran = true }, Date.now() - 11) + assert.match(error?.message ?? "", /timed out/) + assert.equal(ran, false) + assert.equal(queue.pending, 0) +}) + +test("four fixed shares plus the local reserve exhaust exactly the aggregate jobs and byte ceilings", async () => { + for (const bytes of [false, true]) { + const budget = new InstanceEventBudget(), blocked = deferred() + budget.explicitSources = 4 + const queues = Array.from({ length: 5 }, (_, i) => new InstanceEventQueue(() => {}, undefined, budget, i !== 0)) + for (let i = 0; i < queues.length; i++) { + const jobs = bytes ? 1 : i === 0 ? 256 : 448 + const size = bytes ? (i === 0 ? 4 : 7) * 1024 * 1024 : 1 + for (let j = 0; j < jobs; j++) queues[i].enqueue("blocked", size, () => blocked.promise) + } + assert.equal(bytes ? budget.bytes : budget.jobs, bytes ? 32 * 1024 * 1024 : 2048) + queues[1].enqueue("overflow", 1, async () => {}) + assert.equal(queues[1].pending, 0) + assert.equal(queues[2].pending, bytes ? 1 : 448) + for (const queue of queues) queue.close() + blocked.resolve() + await turn() + assert.equal(budget.bytes, 0) + assert.equal(budget.jobs, 0) + } +}) + +test("share activation refuses new local work but drains grandfathered resolution and prepaid delivery before reconnect", async () => { + const budget = new InstanceEventBudget(), resolve = deferred() + let failed = 0, gap = 0, delivered = 0, newWork = false + const queue = new InstanceEventQueue(() => { failed++ }, undefined, budget, false, () => { gap++ }) + const deliveries = new Map(Array.from({ length: 300 }, (_, index) => [String(index), 1])) + queue.enqueue("resolve", 1, async reservation => { + await resolve.promise + for (let index = 0; index < 300; index++) queue.enqueueDelivery(String(index), reservation, String(index), async () => { delivered++ }, Date.now()) + }, Date.now(), deliveries) + assert.equal(budget.jobs, 301) + budget.explicitSources = 1 + queue.enqueue("new", 1, async () => { newWork = true }) + assert.equal(failed, 0) + assert.equal(gap, 1) + assert.equal(queue.pending, 301) + resolve.resolve() + await until(() => failed === 1) + assert.equal(delivered, 300) + assert.equal(newWork, false) + assert.equal(budget.jobs, 0) + assert.equal(budget.bytes, 0) +}) + +test("healthy long-lived ingestion does not accumulate reactions on one pending cancellation promise", async t => { + const h = harness(); t.after(() => h.bridge.shutdown()) + const original = Promise.prototype.then + const reactions = new WeakMap() + let largest = 0 + t.mock.method(Promise.prototype, "then", function (this: Promise, yes: any, no: any) { + const count = (reactions.get(this) ?? 0) + 1 + reactions.set(this, count) + largest = Math.max(largest, count) + return original.call(this, yes, no) + }) + h.admit("A") + await until(() => h.streams.get("A")?.length === 1) + for (let index = 0; index < 1000; index++) h.streams.get("A")![0].send(event("model.updated")) + await until(() => h.business().length === 1000) + assert.ok(largest <= 16, `one promise retained ${largest} reactions`) +}) + +test("ownership waits retain ingestion-time live boundaries across a same-attempt gap", async t => { + const h = harness(), held = deferred() + t.after(() => { held.resolve(true); h.bridge.shutdown() }) + h.blockA(held.promise); h.admit("A") + await until(() => h.frames.some(frame => frame.type === "instance.eventStatus" && frame.status === "connected" && frame.instanceId === "A")) + const before = h.frames.find((frame: any) => frame.type === "instance.eventStatus" && frame.status === "connected" && frame.instanceId === "A") as any + const feed = h.streams.get("A")![0] + feed.send(event("form.created", { form: { id: "held-before", sessionID: "global" } }, { directory: "/same" })) + await until(() => h.ownershipRequests.includes("A")) + feed.send(event("session.deleted", { sessionID: "missing" })) + await until(() => h.frames.some(frame => frame.type === "instance.eventStatus" && frame.gap === "ownership")) + const after = h.frames.filter((frame: any) => frame.type === "instance.eventStatus" && frame.status === "connected" && frame.instanceId === "A").at(-1) as any + assert.equal(after.source.generation, before.source.generation) + assert.equal(after.source.connectionGeneration, before.source.connectionGeneration) + assert(after.liveGeneration > before.liveGeneration) + feed.send(event("form.created", { form: { id: "held-after", sessionID: "global" } }, { directory: "/same" })) + // Let ingestion capture the second event while ownership remains held. + await turn(); await turn() + held.resolve(true) + await until(() => h.business().filter(frame => frame.event.type === "form.created").length === 2) + const forms = h.business().filter(frame => frame.event.type === "form.created") + assert.equal(forms[0].liveGeneration, before.liveGeneration) + assert.equal(forms[1].liveGeneration, after.liveGeneration) + assert.equal(forms[0].source!.connectionGeneration, (h.connections.get("A") as any).generation) +}) diff --git a/packages/server/src/workspaces/instance-events-settlement.test.ts b/packages/server/src/workspaces/instance-events-settlement.test.ts new file mode 100644 index 0000000000..508430f699 --- /dev/null +++ b/packages/server/src/workspaces/instance-events-settlement.test.ts @@ -0,0 +1,152 @@ +import assert from "node:assert/strict" +import { test } from "node:test" +import { EventBus } from "../events/bus" +import { InstanceEventBridge } from "./instance-events" +import { InstanceEventQueue } from "./instance-event-queue" + +const turn = () => new Promise(resolve => setImmediate(resolve)) +async function until(check: () => boolean) { + for (let i = 0; i < 500 && !check(); i++) await turn() + assert(check(), "memory relay did not settle") +} +function deferred() { + let resolve!: (value: T) => void + let reject!: (error: unknown) => void + const promise = new Promise((done, fail) => { resolve = done; reject = fail }) + return { promise, resolve, reject } +} + +function harness(t: any) { + const held = deferred(), bus = new EventBus(), frames: any[] = [] + bus.onEvent(frame => frames.push(JSON.parse(JSON.stringify(frame)))) + const controller = new AbortController(), items: any[] = [] + let wake: (() => void) | undefined, reads = 0, forbidden = 0 + const workspace = { id: "same-occurrence", path: "/opaque", binding: { serverId: "A", directory: "/opaque" } } + let workspaces = [workspace] + const connection = { + generation: 42, signal: controller.signal, endpoint: { url: "http://memory.invalid" }, + assertCurrent() { controller.signal.throwIfAborted() }, + invalidate() { throw new Error("unexpected invalidation") }, + client: { event: { subscribe: ({ signal }: { signal: AbortSignal }) => (async function* () { + yield { type: "server.connected", data: {} } + while (!signal.aborted) { + if (items.length) yield items.shift() + else await new Promise(resolve => { + const done = () => { signal.removeEventListener("abort", done); resolve() } + wake = done + if (signal.aborted) done() + else signal.addEventListener("abort", done, { once: true }) + }) + } + })() }, session: { get: () => { reads++; return held.promise } } }, + } + const bridge = new InstanceEventBridge({ eventBus: bus, logger: { debug() {}, warn() {} } as any, + workspaceManager: { + list: () => workspaces, + observeAdmittedEventSources(listener: any) { listener(["A"]); return () => {} }, + getServerConnections: () => ({ acquireForServer: async () => connection }), + ownsLocation: async () => true, + subscribeToSharedService() { forbidden++; throw new Error("local access forbidden") }, + } as any, + }) + t.after(() => { bridge.shutdown(); controller.abort(); wake?.(); assert.equal(forbidden, 0) }) + return { bus, frames, held, reads: () => reads, + emit(value: any) { items.push(value); wake?.() }, + reopen() { + workspaces = [] + bus.publish({ type: "workspace.stopped", workspaceId: workspace.id, reason: "deleted" }) + workspaces = [workspace] + bus.publish({ type: "workspace.started", workspace } as any) + }, + } +} + +test("connected marker prepays its exact decorated serialized delivery envelope", async t => { + const jobs: any[] = [], original = InstanceEventQueue.prototype.enqueue + t.mock.method(InstanceEventQueue.prototype, "enqueue", function (this: InstanceEventQueue, ...args: Parameters) { + jobs.push({ bytes: args[1], deliveries: [...(args[4] ?? [])] }) + return original.apply(this, args) + }) + const h = harness(t) + await until(() => h.frames.some(frame => frame.type === "instance.event")) + const marker = h.frames.find(frame => frame.type === "instance.event") + assert.equal(marker.source.connectionGeneration, 42) + assert.equal(typeof marker.event.data.daemon, "string") + assert.equal(jobs[0].deliveries[0][1], Buffer.byteLength(JSON.stringify(marker))) + assert.equal(jobs[0].bytes, Buffer.byteLength(JSON.stringify(marker.event))) +}) + +test("retired placement lookup cannot pulse a reopened same-ID occurrence; current lookup still pulses", async t => { + const h = harness(t) + await until(() => h.frames.some(frame => frame.type === "instance.event")) + h.emit({ type: "session.deleted", data: { sessionID: "old-unresolved" } }) + await until(() => h.reads() === 1) + h.reopen() + h.emit({ type: "form.created", location: { directory: "/opaque" }, data: { form: { id: "new-live-request", sessionID: "global" } } }) + await until(() => h.frames.some(frame => frame.type === "instance.event" && frame.event.type === "form.created")) + const before = h.frames.length + h.held.reject(Object.assign(new Error("synthetic missing session"), { _tag: "SessionNotFoundError" })) + await turn(); await turn() + assert.equal(h.frames.slice(before).filter(frame => frame.gap === "ownership").length, 0) + assert.equal(h.frames.length, before) + h.emit({ type: "session.deleted", data: { sessionID: "current-unresolved" } }) + await until(() => h.frames.slice(before).some(frame => frame.gap === "ownership")) + const pulse = h.frames.slice(before) + assert.deepEqual(pulse.map(frame => frame.status), ["error", "connected"]) + assert.equal(pulse[0].source.generation, pulse[1].source.generation) + assert.equal(h.reads(), 2) +}) + +test("delayed resolution transfers original ingestion deadline into enqueueDelivery", async t => { + const originalNow = Date.now, receivedAt = originalNow(), held = deferred() + let now = receivedAt, failure: Error | undefined, delivered = false + t.mock.method(Date, "now", () => now) + const queue = new InstanceEventQueue(error => { failure = error }, { jobs: 10, bytes: 100, timeoutMs: 10 }) + t.after(() => queue.close()) + queue.enqueue("resolve", 1, async reservation => { + await held.promise + queue.enqueueDelivery("delivery", reservation, "A", async () => { delivered = true }, receivedAt) + }, receivedAt, new Map([["A", 1]])) + now += 11 + held.resolve() + await turn() + assert.match(failure?.message ?? "", /timed out/) + assert.equal(delivered, false) + assert.equal(queue.pending, 0) +}) + +test("invalid acquired native generations fail before subscribe", async () => { + for (const generation of [undefined, 0, -1, 1.5, NaN, "42", Infinity, Number.MAX_SAFE_INTEGER + 1]) { + const bus = new EventBus(), frames: any[] = [] + bus.onEvent(frame => frames.push(frame)) + let subscribed = 0 + const bridge = new InstanceEventBridge({ eventBus: bus, logger: { debug() {}, warn() {} } as any, + workspaceManager: { + list: () => [{ id: "guard", binding: { serverId: "A", directory: "/opaque" } }], + observeAdmittedEventSources(listener: any) { listener(["A"]); return () => {} }, + getServerConnections: () => ({ acquireForServer: async () => ({ generation, + client: { event: { subscribe() { subscribed++; throw new Error("forbidden") } } } }) }), + } as any, + }) + try { + await until(() => frames.some(frame => frame.status === "error")) + assert.equal(subscribed, 0) + assert.equal(frames.some(frame => frame.type === "instance.event" || frame.status === "connected"), false) + } finally { bridge.shutdown() } + } +}) + +test("bus rejects older live boundaries and same-boundary contradictions before replay and stop purge", () => { + const bus = new EventBus(), frames: any[] = [] + const status = (liveGeneration: number, state = "connected", connectionGeneration = 42) => ({ + type: "instance.eventStatus", instanceId: "held", status: state, generation: 3, + source: { serverId: "A", generation: 3, connectionGeneration }, liveGeneration, + }) + for (const frame of [status(70), status(71, "error"), status(72), status(70), status(72, "error"), status(72, "connected", 43)]) bus.publish(frame as any) + bus.onEvent(frame => frames.push(frame))() + assert.deepEqual(frames, [status(72)]) + bus.publish({ type: "workspace.stopped", workspaceId: "held", reason: "deleted" }) + const retired: any[] = [] + bus.onEvent(frame => retired.push(frame))() + assert.deepEqual(retired, []) +}) diff --git a/packages/server/src/workspaces/instance-events.test.ts b/packages/server/src/workspaces/instance-events.test.ts index 824911a47e..2f8aef8381 100644 --- a/packages/server/src/workspaces/instance-events.test.ts +++ b/packages/server/src/workspaces/instance-events.test.ts @@ -245,7 +245,7 @@ describe("InstanceEventBridge", () => { }, } as unknown as WorkspaceManager const bus = new EventBus() - const statuses: Array<{ status: string; reason?: string }> = [] + const statuses: Array<{ status: string; reason?: string; gap?: string }> = [] const received: OpenCodeEvent[] = [] bus.on("instance.eventStatus", (event) => statuses.push(event)) bus.on("instance.event", (event) => received.push(event.event)) @@ -253,7 +253,7 @@ describe("InstanceEventBridge", () => { try { bus.publish({ type: "workspace.started", workspace: manager.list()[0] as any }) await waitFor(() => statuses.some((event) => event.status === "error")) - assert.match(statuses.find((event) => event.status === "error")?.reason ?? "", /expected server\.connected/) + assert.equal(statuses.find((event) => event.status === "error")?.gap, "transport") assert.deepEqual(received, []) await waitFor(() => statuses.some((event) => event.status === "connected")) assert.equal(subscriptions, 2) @@ -711,13 +711,15 @@ describe("InstanceEventBridge", () => { } }) - it("broadcasts an unresolvable locationless deletion", async () => { + it("requests targeted recovery instead of broadcasting an unresolvable deletion", async () => { const events = [{ type: "session.deleted", data: { sessionID: "deleted" } }] as OpenCodeEvent[] const workspaces = [{ id: "a", path: "/repo-a" }, { id: "b", path: "/repo-b" }] const notFound = Object.assign(new Error("not found"), { _tag: "SessionNotFoundError" }) const { manager, sessionGets } = locationlessManager(events, { deleted: notFound }, workspaces) const bus = new EventBus() const received: any[] = [] + const gaps: any[] = [] + bus.on("instance.eventStatus", event => { if (event.gap === "ownership") gaps.push(event) }) bus.on("instance.event", (event) => { if (event.event.type !== "server.connected") received.push(event) }) @@ -725,10 +727,10 @@ describe("InstanceEventBridge", () => { try { bus.publish({ type: "workspace.started", workspace: manager.list()[0] as any }) - await waitFor(() => received.length === 2) + await waitFor(() => gaps.length === 2) assert.equal(sessionGets(), 1) - assert.deepEqual(received.map((event) => event.instanceId), ["a", "b"]) - assert.deepEqual(received.map((event) => event.event.data.sessionID), ["deleted", "deleted"]) + assert.deepEqual(gaps.map((event) => event.instanceId), ["a", "b"]) + assert.equal(received.length, 0) } finally { bridge.shutdown() } @@ -847,6 +849,7 @@ describe("InstanceEventBridge", () => { it("relays server.connected with a stable daemon identity digest per connection", async () => { const runtimeKey = Symbol.for("codenomad.opencode.runtime") const connectionFor = (pid: number) => ({ + assertCurrent() {}, endpoint: Object.assign( { url: "http://127.0.0.1:4010", auth: { username: "u", password: "p" } }, { [runtimeKey]: Object.freeze({ version: "2.2.3", pid, contract: {} }) }, @@ -902,6 +905,7 @@ describe("InstanceEventBridge", () => { it("keeps one daemon token across stream resubscriptions of the same source", async () => { const runtimeKey = Symbol.for("codenomad.opencode.runtime") const connection = { + assertCurrent() {}, endpoint: Object.assign( { url: "http://127.0.0.1:4011" }, { [runtimeKey]: Object.freeze({ version: "2.2.3", pid: 4242, contract: {} }) }, @@ -942,6 +946,7 @@ describe("InstanceEventBridge", () => { it("drops a superseded source's token and never revives it", async () => { const runtimeKey = Symbol.for("codenomad.opencode.runtime") const connectionFor = (pid: number) => ({ + assertCurrent() {}, endpoint: Object.assign( { url: "http://127.0.0.1:4012" }, { [runtimeKey]: Object.freeze({ version: "2.2.3", pid, contract: {} }) }, @@ -980,6 +985,7 @@ describe("InstanceEventBridge", () => { it("a disposed relay's tokens are not reused by a new relay", async () => { const runtimeKey = Symbol.for("codenomad.opencode.runtime") const connection = { + assertCurrent() {}, endpoint: Object.assign( { url: "http://127.0.0.1:4013" }, { [runtimeKey]: Object.freeze({ version: "2.2.3", pid: 3333, contract: {} }) }, diff --git a/packages/server/src/workspaces/instance-events.ts b/packages/server/src/workspaces/instance-events.ts index 94831a28b6..2795917887 100644 --- a/packages/server/src/workspaces/instance-events.ts +++ b/packages/server/src/workspaces/instance-events.ts @@ -6,9 +6,9 @@ import { EventBus } from "../events/bus" import { Logger } from "../logger" import { WorkspaceManager } from "./manager" import { nativeEventConnections, type ServiceConnection } from "./opencode-service" -import { InstanceStreamStatus } from "../api-types" -import { InstanceEventQueue } from "./instance-event-queue" import { integrationEventForRelay } from "../opencode/integrations/events" +import { InstanceStreamStatus, type InstanceEventSource as Source, type InstanceEventGap } from "../api-types" +import { InstanceEventQueue, InstanceEventBudget, InstanceEventQueueError, type InstanceEventReservation } from "./instance-event-queue" const RECONNECT_DELAY_MS = 1000 const LOCATION_OWNER_CACHE_MS = 2000 @@ -44,12 +44,15 @@ interface InstanceEventBridgeOptions { } interface EventRoute { + source: Source + connection?: ServiceConnection + reservation: InstanceEventReservation current: () => boolean signal: AbortSignal queue: InstanceEventQueue key: string bytes: number - recipients: Array<{ id: string; epoch: number }> + recipients: Array<{ id: string; epoch: number; liveGeneration: number }> receivedAt: number } @@ -71,10 +74,65 @@ function daemonSourceKey(connection: ServiceConnection): string { } export class InstanceEventBridge { + private readonly sources = new Map() + private readonly budget = new InstanceEventBudget() + private generation = 0 + private liveGeneration = 0 + private readonly unobserve?: () => void + + constructor(private readonly options: InstanceEventBridgeOptions) { + this.sources.set("local-shared", this.create("local-shared")) + this.unobserve = options.workspaceManager.observeAdmittedEventSources?.((ids, credentialsChanged) => { + this.budget.explicitSources = ids.length + for (const [id, relay] of this.sources) { + if (id !== "local-shared" && !ids.includes(id)) { relay.shutdown(); this.sources.delete(id) } + } + for (const id of ids) { + if (!this.sources.has(id)) { + const relay = this.create(id) + this.sources.set(id, relay) + relay.start() + } + } + if (credentialsChanged) this.sources.get(credentialsChanged)?.restart() + }) + } + + private create(serverId: string): InstanceEventRelay { + return new InstanceEventRelay({ ...this.options, serverId, budget: this.budget, + nextGeneration: () => ++this.generation, + nextLiveGeneration: () => ++this.liveGeneration, + }) + } + + shutdown(): void { + this.unobserve?.() + for (const source of this.sources.values()) source.shutdown() + this.sources.clear() + } +} + +function nextEvent(iterator: AsyncIterator, signal: AbortSignal): Promise> { + return new Promise((resolve, reject) => { + const cleanup = () => signal.removeEventListener("abort", cancel) + const cancel = () => { cleanup(); resolve({ done: true, value: undefined }) } + if (signal.aborted) { cancel(); return } + signal.addEventListener("abort", cancel, { once: true }) + void iterator.next().then(value => { cleanup(); resolve(value) }, error => { cleanup(); reject(error) }) + }) +} + +class InstanceEventRelay { private readonly controller = new AbortController() private status: InstanceStreamStatus = "connecting" private generation = 0 + private connectionGeneration?: number + private readonly liveStatuses = new Map() private task?: Promise + private marker?: { event: OpenCodeEvent; source: Source } + private attempt?: AbortController + private retryWake?: AbortController + private restartRequested = false /** The attributed source of the current shared stream and its opaque token. * Exactly one entry: a reconnect of the same source keeps its token, a * replacement drops the superseded source's credential-bearing key with it, @@ -84,31 +142,50 @@ export class InstanceEventBridge { private ownershipRevision = 0 private lastSlowWarning = -Infinity private readonly workspaceEpochs = new Map() + private workspaceEpoch = 0 private readonly sessionLocations = new Map }>() - private readonly ptyLocations = new Map() - private readonly shellLocations = new Map() + private readonly ptyLocations = new Map() + private readonly shellLocations = new Map() + private readonly formLocations = new Map() private readonly routingResyncs = new Map }>() private readonly onWorkspaceStarted = (event: { workspace: { id: string } }) => { + if (!this.recipients().some(workspace => workspace.id === event.workspace.id)) return this.advanceWorkspace(event.workspace.id) this.clearLocationCaches() if (!this.task) this.task = this.run() - else this.publishStatus(event.workspace.id, this.status) + else { + this.publishStatus(event.workspace.id, this.status) + if (this.marker && this.status === "connected") this.options.eventBus.publish({ + type: "instance.event", instanceId: event.workspace.id, event: this.marker.event, source: this.marker.source, + liveGeneration: this.liveStatuses.get(event.workspace.id)!.generation, + }) + } } private readonly onWorkspaceStopped = (event: { workspaceId: string }) => { + if (!this.workspaceEpochs.has(event.workspaceId)) return this.advanceWorkspace(event.workspaceId) this.clearLocationCaches() this.clearRoutingResync(event.workspaceId) this.publishStatus(event.workspaceId, "disconnected", "workspace stopped") + this.workspaceEpochs.delete(event.workspaceId) + this.liveStatuses.delete(event.workspaceId) } private readonly onWorkspaceError = (event: { workspace: { id: string } }) => { + if (!this.workspaceEpochs.has(event.workspace.id)) return this.advanceWorkspace(event.workspace.id) this.clearLocationCaches() this.clearRoutingResync(event.workspace.id) this.publishStatus(event.workspace.id, "disconnected", "workspace error") + this.workspaceEpochs.delete(event.workspace.id) + this.liveStatuses.delete(event.workspace.id) + } + private readonly onWorktreesChanged = (event: { workspaceId: string }) => { + if (this.recipients().some(workspace => workspace.id === event.workspaceId)) this.invalidateOwners() } - private readonly onWorktreesChanged = () => this.invalidateOwners() - constructor(private readonly options: InstanceEventBridgeOptions) { + constructor(private readonly options: InstanceEventBridgeOptions & { + serverId: string; budget: InstanceEventBudget; nextGeneration: () => number; nextLiveGeneration: () => number + }) { const bus = this.options.eventBus bus.on("workspace.started", this.onWorkspaceStarted) bus.on("workspace.stopped", this.onWorkspaceStopped) @@ -116,8 +193,30 @@ export class InstanceEventBridge { bus.on("workspace.worktreesChanged", this.onWorktreesChanged) } + start(): void { if (!this.task) this.task = this.run() } + + restart(): void { + this.restartRequested = true + this.marker = undefined + this.status = "error" + this.attempt?.abort() + this.retryWake?.abort() + } + + private source(): Source { return { serverId: this.options.serverId, generation: this.generation, + ...(this.connectionGeneration === undefined ? {} : { connectionGeneration: this.connectionGeneration }) } } + + private recipients() { + const workspaces = this.options.workspaceManager.list().filter(workspace => (workspace.binding?.serverId ?? "local-shared") === this.options.serverId) + for (const workspace of workspaces) if (!this.workspaceEpochs.has(workspace.id)) this.advanceWorkspace(workspace.id) + return workspaces + } + shutdown() { this.controller.abort() + this.clearLocationCaches() + this.marker = undefined + this.workspaceEpochs.clear() this.clearRoutingResync() // Release the current source's credential-bearing key and its token. this.daemonSource = undefined @@ -126,64 +225,127 @@ export class InstanceEventBridge { bus.off("workspace.stopped", this.onWorkspaceStopped) bus.off("workspace.error", this.onWorkspaceError) bus.off("workspace.worktreesChanged", this.onWorktreesChanged) - for (const workspace of this.options.workspaceManager.list()) { - this.publishStatus(workspace.id, "disconnected") + for (const workspace of this.recipients()) { + this.publishStatus(workspace.id, "disconnected", undefined, "revoked") } + this.liveStatuses.clear() } private async run() { + let retry = RECONNECT_DELAY_MS while (!this.controller.signal.aborted) { - this.generation += 1 + this.restartRequested = false + this.generation = this.options.nextGeneration() + this.connectionGeneration = undefined + this.marker = undefined this.clearLocationCaches() // Reconnecting reconciles every instance, including pending routing pulses. this.clearRoutingResync() this.updateStatus("connecting") const attempt = new AbortController() + this.attempt = attempt let failure: Error | undefined - const queue = new InstanceEventQueue(error => { failure = error; attempt.abort() }) - const abort = () => { attempt.abort(); queue.close() } + let ended = false + const queue = new InstanceEventQueue(error => { + failure = error + this.marker = undefined + this.status = "error" + attempt.abort() + }, undefined, this.options.budget, this.options.serverId !== "local-shared", + () => this.updateStatus("error", "event backlog draining after share activation", "overflow")) + const abort = () => { attempt.abort(); queue.close(); this.marker = undefined; this.status = "error" } this.controller.signal.addEventListener("abort", abort, { once: true }) const current = () => !attempt.signal.aborted && !this.controller.signal.aborted + let connection: ServiceConnection | undefined + let iterator: AsyncIterator | undefined + let unbind = () => {} try { - const events = await this.options.workspaceManager.subscribeToSharedService(attempt.signal) + let events: AsyncIterable + if (this.options.serverId === "local-shared") events = await this.options.workspaceManager.subscribeToSharedService(attempt.signal) + else { + const acquired = await this.options.workspaceManager.getServerConnections().acquireForServer(this.options.serverId) + const generation = "generation" in acquired ? acquired.generation : undefined + if (typeof generation !== "number" || !Number.isSafeInteger(generation) || generation < 1) throw new Error("Explicit event connection generation unavailable") + this.connectionGeneration = generation + connection = acquired + connection.assertCurrent() + const signal = (connection as { signal?: AbortSignal }).signal + signal?.addEventListener("abort", abort, { once: true }) + unbind = () => signal?.removeEventListener("abort", abort) + if (signal?.aborted || !current()) throw new Error("Event source revoked") + events = connection.client.event.subscribe({ signal: attempt.signal }) + } + const source = this.source() + iterator = events[Symbol.asyncIterator]() let confirmed = false - for await (const incoming of events) { - if (!current()) break - const event = integrationEventForRelay(incoming) + let ingested = 0 + while (current()) { + const result = await nextEvent(iterator, attempt.signal) + if (result.done) { ended = true; break } + let event = integrationEventForRelay(result.value) if (!event) continue + if (!current()) break + const captured = connection ?? nativeEventConnections.get(result.value) + captured?.assertCurrent() + if (captured) nativeEventConnections.set(event, captured) if (!confirmed) { if (event.type !== "server.connected") { throw new Error(`Shared OpenCode event stream started with ${event.type}, expected server.connected`) } confirmed = true + retry = RECONNECT_DELAY_MS this.updateStatus("connected") } if (event.type === "worktree.updated") { - this.options.workspaceManager.invalidateWorktrees() + if (this.options.serverId === "local-shared") this.options.workspaceManager.invalidateWorktrees() this.invalidateOwners() } const receivedAt = Date.now() + if (event.type === "server.connected" && captured) { + // Decorate before admission so resolution and deliveries pay the final envelope. + const key = this.options.serverId === "local-shared" ? daemonSourceKey(captured) : String(source.generation) + if (this.daemonSource?.key !== key) this.daemonSource = { key, token: randomBytes(16).toString("hex") } + event = { ...event, data: { ...event.data, daemon: this.daemonSource.token } } as OpenCodeEvent + nativeEventConnections.set(event, captured) + } const bytes = Buffer.byteLength(JSON.stringify(event)) const key = this.eventKey(event) - const recipients = this.options.workspaceManager.list().map(workspace => ({ - id: workspace.id, epoch: this.workspaceEpochs.get(workspace.id) ?? 0, - })) - queue.enqueue(`resolve:${key}`, bytes, () => this.publishEvent(event, { - current, signal: attempt.signal, queue, key, bytes, recipients, receivedAt, - })) + const recipients = this.recipients().map(workspace => { + if (!this.liveStatuses.has(workspace.id)) this.publishStatus(workspace.id, this.status) + return { id: workspace.id, epoch: this.workspaceEpochs.get(workspace.id) ?? 0, + liveGeneration: this.liveStatuses.get(workspace.id)!.generation } + }) + const deliveries = new Map(recipients.map(({ id, liveGeneration }) => [id, + Buffer.byteLength(JSON.stringify({ type: "instance.event", instanceId: id, event, source, liveGeneration })), + ])) + queue.enqueue(`resolve:${key}`, bytes, reservation => this.publishEvent(event, { + current: () => { + if (!current()) return false + try { captured?.assertCurrent(); return true } catch { return false } + }, source, connection: captured, reservation, signal: attempt.signal, queue, key, bytes, recipients, receivedAt, + }), receivedAt, deliveries) + if (++ingested % 32 === 0) await new Promise(resolve => setImmediate(resolve)) } if (!this.controller.signal.aborted) throw failure ?? new Error("Shared OpenCode event stream ended") } catch (error) { + this.marker = undefined + const revoked = attempt.signal.aborted attempt.abort() queue.close() if (this.controller.signal.aborted) return const reason = failure ?? error - this.options.logger.warn({ err: reason }, "Shared OpenCode event stream disconnected") - this.updateStatus("error", reason instanceof Error ? reason.message : String(reason)) - await this.delay(RECONNECT_DELAY_MS) + this.options.logger.warn(this.options.serverId === "local-shared" ? { err: reason } : { serverId: this.options.serverId }, "OpenCode event stream disconnected") + if (connection && !revoked && !failure) connection.invalidate() + const gap = failure instanceof InstanceEventQueueError ? failure.gap : revoked ? "revoked" : ended ? "eof" : "transport" + this.updateStatus("error", "native event stream interrupted", gap) + if (!this.restartRequested) await this.delay(Math.min(30_000, Math.round(retry * (0.8 + Math.random() * 0.4)))) + retry = Math.min(30_000, retry * 2) } finally { attempt.abort() queue.close() + unbind() + if (this.attempt === attempt) this.attempt = undefined + void iterator?.return?.().catch(() => {}) this.controller.signal.removeEventListener("abort", abort) } } @@ -192,57 +354,51 @@ export class InstanceEventBridge { private async publishEvent(event: OpenCodeEvent, route: EventRoute) { if (!route.current()) return if (event.type === "server.connected") { - const connection = nativeEventConnections.get(event) - if (connection) { - const key = daemonSourceKey(connection) - if (this.daemonSource?.key !== key) { - this.daemonSource = { key, token: randomBytes(16).toString("hex") } - } - event = { ...event, data: { ...event.data, daemon: this.daemonSource.token } } as OpenCodeEvent - } + this.marker = { event, source: route.source } } const sessionId = this.sessionId(event) const ptyId = this.ptyId(event) const shellId = this.shellId(event) + const formId = this.formId(event) if (event.type === "session.moved" && sessionId) this.sessionLocations.delete(sessionId) // A scoped event is native location authority, not merely a cwd hint. Keep // that full pair for subsequent locationless PTY/Shell/session events. const location = event.location ? readLocationRef(event.location) - : (ptyId ? this.ptyLocations.get(ptyId) : undefined) + : (ptyId ? this.cachedEntityLocation(this.ptyLocations, ptyId) : undefined) ?? this.ptyInfoLocation(event) - ?? (shellId ? this.shellLocations.get(shellId) : undefined) + ?? (shellId ? this.cachedEntityLocation(this.shellLocations, shellId) : undefined) ?? this.shellInfoLocation(event) - ?? (sessionId ? await this.resolveSessionLocation(sessionId, route.signal) : undefined) + ?? (formId ? this.cachedEntityLocation(this.formLocations, formId) : undefined) + ?? (sessionId ? await this.resolveSessionLocation(sessionId, route) : undefined) if (!route.current()) return if (!location) { if (GLOBAL_EVENT_TYPES.has(event.type)) { this.deliverEvent(event, undefined, route) return } - if (event.type === "session.deleted" && sessionId) { - // Deletion can make session.get return 404 before the event arrives. Session IDs are - // service-global, so notifying every logical workspace cannot delete another session. - this.deliverEvent(event, undefined, route) - this.sessionLocations.delete(sessionId) + for (const { id, epoch } of route.recipients) { + if ((this.workspaceEpochs.get(id) ?? 0) === epoch) this.requestRoutingResync(id) } return } // The moved envelope can refer to the old location. The next locationless // event must resolve the native session rather than cache that old owner. if (sessionId && event.type !== "session.moved") { - this.sessionLocations.set(sessionId, { + this.setBounded(this.sessionLocations, sessionId, { expiresAt: Date.now() + SESSION_LOCATION_CACHE_MS, location: Promise.resolve(location), }) } - if (ptyId) this.ptyLocations.set(ptyId, location) - if (shellId) this.shellLocations.set(shellId, location) + if (ptyId) this.setBounded(this.ptyLocations, ptyId, { expiresAt: Date.now() + 60_000, location }) + if (shellId) this.setBounded(this.shellLocations, shellId, { expiresAt: Date.now() + 60_000, location }) + if (formId) this.setBounded(this.formLocations, formId, { expiresAt: Date.now() + 60_000, location }) this.deliverEvent(event, location, route) if (event.type === "session.deleted" && sessionId) this.sessionLocations.delete(sessionId) if (event.type === "pty.deleted" && ptyId) this.ptyLocations.delete(ptyId) if (event.type === "shell.deleted" && shellId) this.shellLocations.delete(shellId) + if ((event.type === "form.cancelled" || event.type === "form.replied") && formId) this.formLocations.delete(formId) } private eventKey(event: OpenCodeEvent): string { @@ -252,15 +408,17 @@ export class InstanceEventBridge { if (pty) return `pty:${pty}` const shell = this.shellId(event) if (shell) return `shell:${shell}` + const form = this.formId(event) + if (form) return `form:${form}` const location = event.location ? readLocationRef(event.location) : undefined return `location:${JSON.stringify([location?.directory, location?.workspaceID])}` } private deliverEvent(event: OpenCodeEvent, location: LocationRef | undefined, route: EventRoute): void { const resolvedAt = Date.now() - for (const { id: instanceId, epoch } of route.recipients) { + for (const { id: instanceId, epoch, liveGeneration } of route.recipients) { const current = () => route.current() && (this.workspaceEpochs.get(instanceId) ?? 0) === epoch - route.queue.enqueue(`deliver:${JSON.stringify([instanceId, route.key])}`, route.bytes, async () => { + route.queue.enqueueDelivery(`deliver:${JSON.stringify([instanceId, route.key])}`, route.reservation, instanceId, async () => { if (!current()) return const lookupStarted = Date.now() let allowed = !location @@ -268,7 +426,7 @@ export class InstanceEventBridge { try { do { revision = this.ownershipRevision - if (location) allowed = await this.resolveLocationOwner(instanceId, location, current, route.signal) + if (location) allowed = await this.resolveLocationOwner(instanceId, location, current, route.signal, route.connection) if (!current()) return } while (revision !== this.ownershipRevision) } catch { @@ -288,8 +446,8 @@ export class InstanceEventBridge { upstreamAgeMs, }, "Slow instance event routing") } - if (allowed) this.options.eventBus.publish({ type: "instance.event", instanceId, event }) - }) + if (allowed) this.options.eventBus.publish({ type: "instance.event", instanceId, event, source: route.source, liveGeneration }) + }, route.receivedAt) } } @@ -325,12 +483,14 @@ export class InstanceEventBridge { return typeof cwd === "string" && cwd ? { directory: cwd } : undefined } - private resolveSessionLocation(sessionId: string, signal: AbortSignal): Promise { + private resolveSessionLocation(sessionId: string, route: EventRoute): Promise { + const signal = route.signal const now = Date.now() const cached = this.sessionLocations.get(sessionId) if (cached && cached.expiresAt > now) return cached.location - const resolve = () => this.options.workspaceManager.getSharedServiceClient() + const resolve = () => (route.connection ? Promise.resolve(route.connection.client) : this.options.workspaceManager.getSharedServiceClient()) + .then(client => { if (!route.current()) throw new Error("Event source revoked"); return client }) .then((client) => client.session.get({ sessionID: sessionId }, { signal })) .then((session) => readLocationRef(session.location)) const location = resolve().catch((error) => { @@ -341,24 +501,24 @@ export class InstanceEventBridge { }) }) const entry = { expiresAt: Number.POSITIVE_INFINITY, location } - this.sessionLocations.set(sessionId, entry) + this.setBounded(this.sessionLocations, sessionId, entry) const settle = () => { entry.expiresAt = Date.now() + SESSION_LOCATION_CACHE_MS } void location.then(settle, settle) return location } - private resolveLocationOwner(instanceId: string, location: LocationRef, current: () => boolean, signal: AbortSignal): Promise { + private resolveLocationOwner(instanceId: string, location: LocationRef, current: () => boolean, signal: AbortSignal, connection?: ServiceConnection): Promise { const now = Date.now() const key = JSON.stringify([instanceId, location.directory, location.workspaceID]) const cached = this.locationOwners.get(key) if (cached && cached.expiresAt > now) return cached.owns - const resolve = () => location.workspaceID === undefined + const resolve = () => this.options.serverId === "local-shared" && location.workspaceID === undefined ? this.options.workspaceManager.ownsDirectory(instanceId, location.directory, "event") - : this.options.workspaceManager.ownsLocation(instanceId, location, undefined, signal, "event") + : this.options.workspaceManager.ownsLocation(instanceId, location, connection?.client, signal, "event") const owns = Promise.resolve().then(resolve).catch(() => current() ? resolve() : false) const entry = { expiresAt: Number.POSITIVE_INFINITY, owns } - this.locationOwners.set(key, entry) + this.setBounded(this.locationOwners, key, entry) void owns.then(() => { entry.expiresAt = Date.now() + LOCATION_OWNER_CACHE_MS }, error => { // Never cache a failure: the next event for this location looks it up again. if (this.locationOwners.get(key) === entry) this.locationOwners.delete(key) @@ -385,7 +545,7 @@ export class InstanceEventBridge { private pulseRoutingResync(instanceId: string, interval: number): void { this.routingResyncs.set(instanceId, { next: Date.now() + interval, interval }) if (this.status !== "connected" || !this.options.workspaceManager.list().some(workspace => workspace.id === instanceId)) return - this.publishStatus(instanceId, "error", "event routing failed") + this.publishStatus(instanceId, "error", "event routing failed", "ownership") this.publishStatus(instanceId, "connected") } @@ -403,7 +563,26 @@ export class InstanceEventBridge { } private advanceWorkspace(id: string): void { - this.workspaceEpochs.set(id, (this.workspaceEpochs.get(id) ?? 0) + 1) + this.workspaceEpochs.set(id, ++this.workspaceEpoch) + } + + private formId(event: OpenCodeEvent): string | undefined { + if (!event.type.startsWith("form.")) return undefined + const data = event.data as { id?: unknown; form?: { id?: unknown } } + const id = data.id ?? data.form?.id + return typeof id === "string" && id ? id : undefined + } + + private setBounded(map: Map, key: string, value: T): void { + if (!map.has(key) && map.size >= 1024) map.delete(map.keys().next().value!) + map.set(key, value) + } + + private cachedEntityLocation(map: Map, id: string): LocationRef | undefined { + const cached = map.get(id) + if (cached && cached.expiresAt > Date.now()) return cached.location + map.delete(id) + return undefined } private clearLocationCaches(): void { @@ -411,29 +590,41 @@ export class InstanceEventBridge { this.sessionLocations.clear() this.ptyLocations.clear() this.shellLocations.clear() + this.formLocations.clear() } - private updateStatus(status: InstanceStreamStatus, reason?: string) { + private updateStatus(status: InstanceStreamStatus, reason?: string, gap?: InstanceEventGap) { this.status = status - for (const workspace of this.options.workspaceManager.list()) { - this.publishStatus(workspace.id, status, reason) + for (const workspace of this.recipients()) { + this.publishStatus(workspace.id, status, reason, gap) } } - private publishStatus(instanceId: string, status: InstanceStreamStatus, reason?: string) { + private publishStatus(instanceId: string, status: InstanceStreamStatus, reason?: string, gap?: InstanceEventGap) { + const source = this.source(), previous = this.liveStatuses.get(instanceId) + const generation = previous?.status === status && previous.source.generation === source.generation + && previous.source.connectionGeneration === source.connectionGeneration && previous.reason === reason && previous.gap === gap + ? previous.generation : this.options.nextLiveGeneration() + this.liveStatuses.set(instanceId, { status, source, reason, gap, generation }) this.options.logger.debug({ instanceId, status, reason }, "Instance event status updated") - this.options.eventBus.publish({ type: "instance.eventStatus", instanceId, status, generation: this.generation, reason }) + this.options.eventBus.publish({ type: "instance.eventStatus", instanceId, status, generation: this.generation, reason, source, gap, liveGeneration: generation }) } private delay(duration: number) { + if (this.controller.signal.aborted) return Promise.resolve() + const wake = new AbortController() + this.retryWake = wake return new Promise((resolve) => { const done = () => { clearTimeout(timeout) this.controller.signal.removeEventListener("abort", done) + wake.signal.removeEventListener("abort", done) + if (this.retryWake === wake) this.retryWake = undefined resolve() } const timeout = setTimeout(done, duration) this.controller.signal.addEventListener("abort", done, { once: true }) + wake.signal.addEventListener("abort", done, { once: true }) }) } } diff --git a/packages/server/src/workspaces/manager.ts b/packages/server/src/workspaces/manager.ts index e6c835e7cd..33934a608a 100644 --- a/packages/server/src/workspaces/manager.ts +++ b/packages/server/src/workspaces/manager.ts @@ -40,6 +40,11 @@ import { resolveRepoRoot, sharesGitCommonDirectory } from "./git-worktrees" import { GitRequiredError, requireHostGit } from "./git-requirement" import { readLocationRef } from "../opencode/compatibility/location" import type { TemporaryFolderRegistry } from "./temporary-workspaces" +import { ExplicitWorkspace, ExplicitWorkspaceError } from "./explicit-workspace" +import type { ServerAttachmentReservations } from "../opencode/servers/attachment-types" +import { readServerAttachments } from "./server-attachments" +import type { NativeParent } from "../native-parent" +import { ProjectParticipants } from "./project-participants" const DEFAULT_LAUNCH_TIMEOUT_MS = 30_000 const MAX_ACTIVE_WORKSPACE_CREATIONS = 32 @@ -138,6 +143,7 @@ interface WorkspaceState { creationClaims: Map creationRetained: boolean serviceOptions?: OpenCodeSharedServiceOptions + explicit?: ExplicitWorkspace } export class WorkspaceLaunchCancelledError extends Error { constructor(workspaceId: string) { @@ -175,9 +181,12 @@ export interface WorkspaceCreateResult { } export interface WorkspaceCreateOptions { requestId?: string + /** Internal only until proxy and event routing are qualified. */ + serverId?: string } type CreationRequestState = "owner" | "cancelled" | "released" export class WorkspaceManager { + readonly projectParticipants = new ProjectParticipants() private readonly workspaces = new Map() private readonly deletingWorktreeRoots = new Set() private readonly cancelledCreationRequests = new Set() @@ -188,6 +197,8 @@ export class WorkspaceManager { private serviceAuthorization?: string private warnedLegacyServiceEnvironment = false private readonly fileWatches: WorkspaceFileWatches + private attachmentReceipt = randomUUID() + private pendingLocalAttachmentCreations = 0 constructor(private readonly options: WorkspaceManagerOptions) { this.sharedService = options.sharedService ?? new OpenCodeSharedService() @@ -199,14 +210,46 @@ export class WorkspaceManager { list(): WorkspaceDescriptor[] { return Array.from(this.workspaces.values()) .filter((record) => record[WORKSPACE_STATE].published) + .map((record) => this.descriptor(record)) } get(id: string): WorkspaceDescriptor | undefined { const record = this.workspaces.get(id) - return record?.[WORKSPACE_STATE].published ? record : undefined + return record?.[WORKSPACE_STATE].published ? this.descriptor(record) : undefined + } + + /** Includes unpublished records; a local path still resolving has no qualified directory yet. */ + attachmentReservations(serverId: string): ServerAttachmentReservations { + const records = [...this.workspaces.values()].filter(record => record.binding?.serverId === serverId) + return { + receipt: this.attachmentReceipt, + status: this.shuttingDown || records.length > 512 ? "unknown" : "complete", + reservations: records.slice(0, 512).map(record => ({ + reservationId: record.id, instanceId: record.id, serverId, + directory: record.binding!.directory, + state: record[WORKSPACE_STATE].published ? "published" : "reserved", + })), + inFlight: (serverId === "local-shared" && this.pendingLocalAttachmentCreations > 0) + || records.some(record => !record[WORKSPACE_STATE].published), + } + } + + attachmentReceiptCurrent(receipt: string): boolean { return !this.shuttingDown && receipt === this.attachmentReceipt } + + readServerAttachments(parent: Pick, serverId: string) { + return readServerAttachments(this, parent, serverId) + } + + private descriptor(record: WorkspaceRecord): WorkspaceDescriptor { + const explicit = record[WORKSPACE_STATE].explicit + if (!explicit) return record + return Object.defineProperty({ ...record, capabilities: explicit.capabilities() }, "binding", { + value: explicit.binding, enumerable: true, writable: false, configurable: false, + }) } getInstanceAuthorizationHeader(id: string): string | undefined { + if (this.workspaces.get(id)?.[WORKSPACE_STATE].explicit) return undefined return this.workspaces.get(id)?.[WORKSPACE_STATE].published ? this.serviceAuthorization : undefined } @@ -223,6 +266,7 @@ export class WorkspaceManager { async getSharedServiceEndpoint(id: string): Promise { if (!this.workspaces.get(id)?.[WORKSPACE_STATE].published) return undefined + if (this.workspaces.get(id)![WORKSPACE_STATE].explicit) return (await this.acquireForWorkspace(id))?.endpoint try { const [endpoint, headers] = await Promise.all([this.sharedService.endpoint(), this.sharedService.headers()]) this.serviceAuthorization = headers?.authorization @@ -248,6 +292,18 @@ export class WorkspaceManager { return this.sharedService.client() } + /** Shared resolver for explicitly targeted calls; workspace binding is supplied by its owner. */ + getServerConnections() { + return this.options.settings.getOpenCodeServerConnections({ + acquire: () => { + if (!this.sharedService.acquire) throw new Error("OpenCode connection acquisition unavailable") + return this.sharedService.acquire() + }, + existing: () => this.sharedService.existingConnection?.(), + invalidate: () => this.sharedService.invalidate?.(), + }) + } + /** Await before a bundled-plugin RPC: plugins register only after observing this backend's lease. */ desktopPluginsReady(): Promise { return this.options.desktopPluginsReady?.() ?? Promise.resolve() @@ -260,7 +316,7 @@ export class WorkspaceManager { throw new Error("Worktree deletion is already in progress") } if (Array.from(this.workspaces.values()).some((workspace) => ( - pathContains(target, canonicalWorktreeIdentity(workspace.path, this.options.platform)) + !workspace[WORKSPACE_STATE].explicit && pathContains(target, canonicalWorktreeIdentity(workspace.path, this.options.platform)) ))) { throw new Error("Worktree is open as another workspace") } @@ -273,12 +329,46 @@ export class WorkspaceManager { } async getSharedServiceConnection(id: string): Promise { + return this.acquireForWorkspace(id) + } + + async acquireForWorkspace(id: string): Promise { if (!this.workspaces.get(id)?.[WORKSPACE_STATE].published) return undefined + const explicit = this.workspaces.get(id)![WORKSPACE_STATE].explicit + if (explicit) return explicit.acquire() + if (typeof this.options.settings.getOpenCodeServerConnections === "function") return this.getServerConnections().acquireForServer("local-shared") return this.sharedService.acquire?.() } + /** Synchronous product-policy admission, before acquisition or adapter effects. */ + requireWorkspaceCapability(id: string, capability: import("../opencode/servers/capabilities").ServerCapability): AbortSignal { + const record = this.workspaces.get(id) + if (!record?.[WORKSPACE_STATE].published) throw Object.assign(new Error("Workspace not found"), { statusCode: 404 }) + record[WORKSPACE_STATE].abortController.signal.throwIfAborted() + record[WORKSPACE_STATE].explicit?.requireCapability(capability) + return record[WORKSPACE_STATE].abortController.signal + } + + /** prototype-1236: true for a project on an explicit OpenCode server (never the host disk or Git). */ + isExplicitWorkspace(id: string): boolean { + const record = this.workspaces.get(id) + return Boolean(record?.[WORKSPACE_STATE].published && record[WORKSPACE_STATE].explicit) + } + + /** prototype-1236: the server connection and exact folder of an explicit project, after admission. */ + async explicitReadScope(id: string, capability: import("../opencode/servers/capabilities").ServerCapability) { + const explicit = this.isExplicitWorkspace(id) ? this.workspaces.get(id)![WORKSPACE_STATE].explicit! : undefined + if (!explicit) return undefined + const signal = this.requireWorkspaceCapability(id, capability) + const connection = await explicit.acquire() + this.requireWorkspaceCapability(id, capability) + return { connection, directory: explicit.binding.directory, signal } + } + getExistingSharedServiceConnection(id: string): import("./opencode-service").ServiceConnection | undefined { if (!this.workspaces.get(id)?.[WORKSPACE_STATE].published) return undefined + const explicit = this.workspaces.get(id)![WORKSPACE_STATE].explicit + if (explicit) return this.getServerConnections().existingForServer(explicit.binding.serverId) return this.sharedService.existingConnection?.() } @@ -289,6 +379,7 @@ export class WorkspaceManager { async ownsDirectory(id: string, directory: string, purpose: "request" | "event" = "request"): Promise { const record = this.workspaces.get(id) if (!record?.[WORKSPACE_STATE].published) return false + if (record[WORKSPACE_STATE].explicit) return this.ownsLocation(id, { directory }, undefined, undefined, purpose) if (directory === record.path || directory === record.location?.directory) return true if (await this.ownsHostDirectory(record, directory, purpose)) return true if (!record.wslDistro) return false @@ -305,6 +396,12 @@ export class WorkspaceManager { if (location.workspaceID !== undefined) return false const record = this.workspaces.get(id) if (!record?.[WORKSPACE_STATE].published) return false + const explicit = record[WORKSPACE_STATE].explicit + if (explicit) { + const connection = purpose === "event" ? this.getExistingSharedServiceConnection(id) : await this.acquireForWorkspace(id) + signal?.throwIfAborted() + return Boolean(connection && explicit.ownsLocation(location, connection, _client)) + } const directory = await this.getServiceDirectoryForPath(id, location.directory, purpose) signal?.throwIfAborted() return Boolean(directory) @@ -313,6 +410,7 @@ export class WorkspaceManager { async getServiceDirectoryForPath(id: string, directory: string, purpose: "request" | "event" = "request"): Promise { const record = this.workspaces.get(id) if (!record?.[WORKSPACE_STATE].published) return undefined + if (record[WORKSPACE_STATE].explicit) return await this.ownsLocation(id, { directory }, undefined, undefined, purpose) ? directory : undefined // Directory authorization does not need the checkout's Git mutation identity. // Resolve aliases against the explicitly opened folder without spawning Git. if (!record.wslDistro) { @@ -330,6 +428,8 @@ export class WorkspaceManager { async getWorktreeIdentityForPath(id: string, directory: string, purpose: "request" | "event" = "request"): Promise { const record = this.workspaces.get(id) if (!record?.[WORKSPACE_STATE].published) return undefined + this.requireWorkspaceCapability(id, "worktrees") + this.requireLocalWorkspace(id) const owned = await this.resolveOwnedWorktree(record, directory, purpose) if (!owned) return undefined return canonicalWorktreeIdentity(owned.worktreeDirectory) @@ -346,6 +446,7 @@ export class WorkspaceManager { getServicePathStyle(id: string): "win32" | "posix" | undefined { const record = this.workspaces.get(id) if (!record?.[WORKSPACE_STATE].published) return undefined + if (record[WORKSPACE_STATE].explicit) return isWindowsHostPath(record.path) ? "win32" : "posix" const platform = this.options.platform ?? process.platform return record.wslDistro || platform !== "win32" ? "posix" : "win32" } @@ -359,11 +460,14 @@ export class WorkspaceManager { async getHostPathForServicePath(id: string, servicePath: string): Promise { const record = this.workspaces.get(id) if (!record?.[WORKSPACE_STATE].published) return undefined + this.requireWorkspaceCapability(id, "files") + this.requireLocalWorkspace(id) if (!record.wslDistro) return servicePath return await this.resolveWslHostDirectory(servicePath, record.wslDistro, DEFAULT_LAUNCH_TIMEOUT_MS) ?? undefined } private async nativeWorktreeContext(id: string, purpose: "request" | "event" = "request") { + this.requireWorkspaceCapability(id, "worktrees") const record = this.workspaces.get(id) const location = this.getServiceLocation(id) if (!record || !location) throw new Error("Workspace has no native location") @@ -395,6 +499,7 @@ export class WorkspaceManager { }) getWorktrees(id: string, mode: "cached" | "validated" | "fresh" = "cached") { + this.requireWorkspaceCapability(id, "worktrees") return this.worktreeInventory.read(id, mode) } @@ -424,12 +529,14 @@ export class WorkspaceManager { } async createWorktree(id: string, branch: string, fromSlug?: string) { + this.requireWorkspaceCapability(id, "worktrees") await requireHostGit() try { return await createNativeWorktree(await this.nativeWorktreeContext(id), branch, fromSlug) } finally { this.invalidateWorktrees("blocking") } } async removeWorktree(id: string, serviceDirectory: string, force: boolean) { + this.requireWorkspaceCapability(id, "worktrees") await requireHostGit() try { return await removeNativeWorktree(await this.nativeWorktreeContext(id), serviceDirectory, force) } finally { this.invalidateWorktrees("blocking") } @@ -437,6 +544,7 @@ export class WorkspaceManager { /** Native `vcs.init` for the explicitly opened folder; callers hold its deletion fence. */ async initializeGit(id: string) { + this.requireWorkspaceCapability(id, "git") await requireHostGit() try { return await initializeNativeGit(await this.nativeWorktreeContext(id)) } finally { this.invalidateWorktrees("blocking") } @@ -494,6 +602,7 @@ export class WorkspaceManager { async ownsPath(id: string, candidate: string): Promise { const record = this.workspaces.get(id) if (!record?.[WORKSPACE_STATE].published) return false + if (record[WORKSPACE_STATE].explicit) return this.ownsDirectory(id, candidate) if (await this.ownsHostPath(record, candidate)) return true if (!record.wslDistro) return false const hostPath = await this.resolveWslHostDirectory(candidate, record.wslDistro, DEFAULT_LAUNCH_TIMEOUT_MS) @@ -514,15 +623,21 @@ export class WorkspaceManager { return this.sharedService.subscribe({ signal }) } + observeAdmittedEventSources(observer: (serverIds: readonly string[], credentialsChanged?: string) => void): () => void { + if (typeof this.options.settings.getOpenCodeServerConnections !== "function") { observer([]); return () => {} } + return this.getServerConnections().observeAdmitted(observer) + } + findReadyInstanceIdByBinary(binaryPath: string): string | undefined { const resolvedPath = this.resolveBinaryPath(binaryPath) return this.list().find((workspace) => { - return workspace.status === "ready" && binaryPathsEqual(workspace.binaryId, resolvedPath) + return workspace.status === "ready" && workspace.binaryId !== undefined && binaryPathsEqual(workspace.binaryId, resolvedPath) })?.id } private async fileBrowserRoot(workspaceId: string, directory?: string): Promise { - const workspace = this.requireWorkspace(workspaceId) + this.requireWorkspaceCapability(workspaceId, "files") + const workspace = this.requireLocalWorkspace(workspaceId) if (!directory) return workspace.path const owned = await this.resolveOwnedWorktree(workspace, directory) if (!owned) throw new Error("Directory is not owned by this workspace") @@ -542,7 +657,8 @@ export class WorkspaceManager { } async readFile(workspaceId: string, relativePath: string, options?: { encoding?: "utf-8" | "base64" }): Promise { - const workspace = this.requireWorkspace(workspaceId) + this.requireWorkspaceCapability(workspaceId, "files") + const workspace = this.requireLocalWorkspace(workspaceId) const browser = new FileSystemBrowser({ rootDir: workspace.path }) const encoding = options?.encoding ?? "utf-8" const contents = await (encoding === "base64" ? browser.readFileBase64(relativePath) : browser.readFile(relativePath)) @@ -561,7 +677,8 @@ export class WorkspaceManager { } async readFileInDirectory(workspaceId: string, directory: string, relativePath: string, options?: { encoding?: "utf-8" | "base64" }): Promise { - this.requireWorkspace(workspaceId) + this.requireWorkspaceCapability(workspaceId, "files") + this.requireLocalWorkspace(workspaceId) const browser = new FileSystemBrowser({ rootDir: directory }) const encoding = options?.encoding ?? "utf-8" const contents = await (encoding === "base64" ? browser.readFileBase64(relativePath) : browser.readFile(relativePath)) @@ -574,7 +691,8 @@ export class WorkspaceManager { } async writeFile(workspaceId: string, relativePath: string, contents: string): Promise { - const workspace = this.requireWorkspace(workspaceId) + this.requireWorkspaceCapability(workspaceId, "files") + const workspace = this.requireLocalWorkspace(workspaceId) const browser = new FileSystemBrowser({ rootDir: workspace.path }) await browser.writeFile(relativePath, contents) } @@ -589,7 +707,10 @@ export class WorkspaceManager { name?: string, options: WorkspaceCreateOptions = {}, ): Promise { + if (options.serverId !== undefined && options.serverId !== "local-shared") return this.createExplicitWorkspace(folder, name, options) if (options.requestId) this.beginCreationRequest(options.requestId) + this.pendingLocalAttachmentCreations++ + this.attachmentReceipt = randomUUID() let creationCounted = false let settlementTracked = false const launchTimeoutMs = Math.max(1, this.options.launchTimeoutMs ?? DEFAULT_LAUNCH_TIMEOUT_MS) @@ -623,10 +744,38 @@ export class WorkspaceManager { void record[WORKSPACE_STATE].settlement!.then(() => { this.activeWorkspaceCreations -= 1 }) return this.finishCreation(await creation, options.requestId, record) } finally { + this.pendingLocalAttachmentCreations-- + this.attachmentReceipt = randomUUID() if (creationCounted && !settlementTracked) this.activeWorkspaceCreations -= 1 if (options.requestId) this.finishCreationRequest(options.requestId) } } + private async createExplicitWorkspace(folder: string, name: string | undefined, options: WorkspaceCreateOptions): Promise { + if (this.shuttingDown) throw new Error("Workspace manager is shutting down") + if (this.activeWorkspaceCreations >= MAX_ACTIVE_WORKSPACE_CREATIONS) throw new Error("Too many workspace creations are already in progress") + if (options.requestId) this.beginCreationRequest(options.requestId) + let record: WorkspaceRecord | undefined + try { + const explicit = new ExplicitWorkspace(this.getServerConnections(), { serverId: options.serverId!, directory: folder }) + const id = randomUUID(), now = new Date().toISOString() + record = { id, path: folder, name, requestId: options.requestId, status: "starting", proxyPath: `/workspaces/${id}/instance`, createdAt: now, updatedAt: now } as WorkspaceRecord + Object.defineProperties(record, { + binding: { value: explicit.binding, enumerable: true }, + [WORKSPACE_STATE]: { value: { explicit, abortController: new AbortController(), published: false, stoppedPublished: false, + creationClaims: new Map(options.requestId ? [[options.requestId, "owner"]] : []), creationRetained: options.requestId === undefined } }, + }) + record[WORKSPACE_STATE].abortController.signal.addEventListener("abort", () => explicit.release(), { once: true }) + this.workspaces.set(id, record) + this.attachmentReceipt = randomUUID() + this.activeWorkspaceCreations++ + const timeout = Math.max(1, this.options.launchTimeoutMs ?? DEFAULT_LAUNCH_TIMEOUT_MS) + const creation = this.startCreation(record, this.now() + timeout, timeout) + void record[WORKSPACE_STATE].settlement!.then(() => { this.activeWorkspaceCreations-- }) + return this.finishCreation(await creation, options.requestId, record) + } finally { + if (options.requestId) this.finishCreationRequest(options.requestId) + } + } private reserveWorkspace( workspacePath: string, name: string | undefined, @@ -658,6 +807,7 @@ export class WorkspaceManager { ...(this.options.temporaryFolders?.has(workspacePath) ? { temporary: true } : {}), } as WorkspaceRecord Object.defineProperties(record, { + binding: { value: Object.freeze({ serverId: "local-shared", directory: workspacePath }), enumerable: true }, wslDistro: { value: undefined, writable: true }, [WORKSPACE_STATE]: { value: { abortController: new AbortController(), @@ -669,15 +819,41 @@ export class WorkspaceManager { }) this.workspaces.set(id, record) + this.attachmentReceipt = randomUUID() return record } private startCreation(record: WorkspaceRecord, launchDeadlineAt: number, launchTimeoutMs: number): Promise { - const launch = this.createResolvedWorkspace(record, launchDeadlineAt) + const launch = record[WORKSPACE_STATE].explicit + ? this.createResolvedExplicitWorkspace(record) : this.createResolvedWorkspace(record, launchDeadlineAt) const creation = this.createWithDeadline(record, launchDeadlineAt, launchTimeoutMs, launch) record[WORKSPACE_STATE].settlement = launch.then(() => undefined, () => undefined) return creation } + private async createResolvedExplicitWorkspace(record: WorkspaceRecord): Promise { + const state = record[WORKSPACE_STATE], explicit = state.explicit! + try { + record.location = await explicit.validate(state.abortController.signal) + this.throwIfCancelled(record) + explicit.assertCurrent() + record.capabilities = explicit.capabilities() + explicit.published(record.id) + state.published = true + this.attachmentReceipt = randomUUID() + this.options.eventBus.publish({ type: "workspace.created", workspace: record }) + this.throwIfCancelled(record) + explicit.assertCurrent() + record.status = "ready" + this.options.eventBus.publish({ type: "workspace.started", workspace: record }) + this.throwIfCancelled(record) + explicit.assertCurrent() + return { workspace: record, created: true } + } catch (error) { + explicit.release() + if (!state.deletePromise) this.removeRecord(record.id, record, state.published) + throw error + } + } private async createWithDeadline(record: WorkspaceRecord, launchDeadlineAt: number, launchTimeoutMs: number, launch: Promise): Promise { @@ -722,10 +898,10 @@ export class WorkspaceManager { const state = record[WORKSPACE_STATE] const { id, path: workspacePath, binaryId: resolvedBinaryPath } = record try { - const launch = buildServiceLaunchSpec(resolvedBinaryPath, { + const launch = buildServiceLaunchSpec(resolvedBinaryPath!, { platform: this.options.platform, }) - const serviceOptions = await this.setupServiceOptions(resolvedBinaryPath, launchDeadlineAt) + const serviceOptions = await this.setupServiceOptions(resolvedBinaryPath!, launchDeadlineAt) state.serviceOptions = serviceOptions this.throwIfCancelled(record) record.wslDistro = launch.kind === "wsl" ? launch.distro : undefined @@ -751,6 +927,7 @@ export class WorkspaceManager { this.serviceAuthorization = headersResult.value?.authorization this.throwIfCancelled(record) state.published = true + this.attachmentReceipt = randomUUID() this.options.eventBus.publish({ type: "workspace.created", workspace: record }) this.throwIfCancelled(record) @@ -864,6 +1041,8 @@ export class WorkspaceManager { async shutdown() { this.shuttingDown = true + this.projectParticipants.dispose() + await this.options.settings.disposeOpenCodeServers?.() this.fileWatches.close() this.options.logger.info("Shutting down all workspaces") const shutdownTimeoutMs = Math.max(1, this.options.shutdownTimeoutMs ?? 10000) @@ -918,6 +1097,13 @@ export class WorkspaceManager { if (!record?.[WORKSPACE_STATE].published) throw new Error("Workspace not found") return record } + private requireLocalWorkspace(id: string): WorkspaceRecord { + this.assertLocalWorkspace(id) + return this.requireWorkspace(id) + } + private assertLocalWorkspace(id: string): void { + if (this.workspaces.get(id)?.[WORKSPACE_STATE].explicit) throw new ExplicitWorkspaceError("explicit_capability_unavailable") + } private throwIfCancelled(record: WorkspaceRecord): void { record[WORKSPACE_STATE].abortController.signal.throwIfAborted() @@ -982,6 +1168,7 @@ export class WorkspaceManager { assertSetupExecutionHost(binary: string): void { const launch = buildServiceLaunchSpec(binary, { platform: this.options.platform }) for (const record of this.workspaces.values()) { + if (record[WORKSPACE_STATE].explicit) continue const distro = launch.kind === "wsl" ? launch.distro.toLowerCase() : undefined if (record.wslDistro?.toLowerCase() !== distro) throw new Error("Close workspaces before changing the OpenCode execution host") } @@ -993,6 +1180,7 @@ export class WorkspaceManager { // This disposes client authority only; it never stops the shared daemon. await this.sharedService.shutdown() for (const record of this.workspaces.values()) { + if (record[WORKSPACE_STATE].explicit) continue record[WORKSPACE_STATE].serviceOptions = options record.binaryId = binary } @@ -1039,6 +1227,7 @@ export class WorkspaceManager { } async getSessionEnvironment(id: string, signal?: AbortSignal): Promise> { + this.requireWorkspaceCapability(id, "sessionEnvironment") const record = this.workspaces.get(id) if (!record || record.status !== "ready") throw new Error("Workspace is not ready") const configured = await this.options.settings.readEnvironmentForAdmission(signal) @@ -1114,6 +1303,13 @@ export class WorkspaceManager { ): void { if (this.workspaces.get(id) !== record) return this.workspaces.delete(id) + this.attachmentReceipt = randomUUID() + const explicit = record[WORKSPACE_STATE].explicit + explicit?.release() + if (explicit) { + if (publishStopped) this.publishStopped(record, reason) + return + } this.fileWatches.forget(id) this.worktreeInventory.forget(id) this.eventWorktreeInventory.forget(id) diff --git a/packages/server/src/workspaces/opencode-service.ts b/packages/server/src/workspaces/opencode-service.ts index 98d580a5af..59b2c50e34 100644 --- a/packages/server/src/workspaces/opencode-service.ts +++ b/packages/server/src/workspaces/opencode-service.ts @@ -331,7 +331,7 @@ export class OpenCodeSharedService { private clear(): void { if (this.connected) this.previousConnection = this.connected - if (this.connected) this.negotiationControllers.get(this.connected)?.abort() + if (this.connected) this.negotiationControllers.get(this.connected)?.abort(new Error("OpenCode connection changed; refresh before retrying")) this.connection = undefined this.connected = undefined this.healthCheck = undefined diff --git a/packages/server/src/workspaces/project-participants.test.ts b/packages/server/src/workspaces/project-participants.test.ts new file mode 100644 index 0000000000..5cde83f15d --- /dev/null +++ b/packages/server/src/workspaces/project-participants.test.ts @@ -0,0 +1,156 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { randomUUID } from "node:crypto" +import { ProjectParticipants } from "./project-participants" + +const ref = (serverId = "A", directory = "Z:\\Opaque\\é/שלום ") => ({ tabId: randomUUID(), serverId, directory }) +const unavailable = () => { assert.fail("metadata must not read files, sessions, providers or credentials") } + +test("scoped declarations retain exact homonyms and independent occurrence lifetimes, never global absence", () => { + const owner = new ProjectParticipants(), before = owner.snapshot("A") + const a = owner.register("cookie-A", () => true)!, b = owner.register("cookie-B", () => true)! + assert.equal(owner.isCurrent(before.receipt), false) + assert.equal(owner.admit(a.grant.token, "cookie-B"), undefined) + const refs = [ref(), ref(), ref("B")] + assert.equal(owner.admit(a.grant.token, "cookie-A")!.publish({ revision: 1, refs }, unavailable), true) + assert.equal(owner.admit(b.grant.token, "cookie-B")!.publish({ revision: 1, refs: [ref()] }, unavailable), true) + const captured = owner.snapshot("A") + assert.equal(captured.refs.length, 3) + assert.equal(new Set(captured.refs.map(value => value.tabId)).size, 3) + assert.ok(captured.refs.every(value => value.directory === refs[0]!.directory)) + assert.equal(captured.status, "unknown") + assert.equal(owner.isCurrent(captured.receipt), true) + assert.equal(owner.admit(a.grant.token, "cookie-A")!.publish({ revision: 2, refs: [] }, unavailable), true) + assert.equal(owner.snapshot("A").refs.length, 1, "one window never clears its sibling") + assert.equal(owner.isCurrent(captured.receipt), false) + assert.doesNotMatch(JSON.stringify(owner.snapshot("A")), new RegExp(`${a.grant.token}|${b.grant.token}|cookie-A|cookie-B`)) + owner.dispose() +}) + +test("pre-body admissions, held/out-of-order bodies, replay and close retire receipts irreversibly", () => { + const owner = new ProjectParticipants(), stream = owner.register("principal", () => true)! + const publish = (revision: number) => owner.admit(stream.grant.token, "principal")!.publish({ revision, refs: [ref()] }, unavailable) + assert.equal(publish(1), true) + const before = owner.snapshot("A"), old = owner.admit(stream.grant.token, "principal")! + assert.equal(owner.isCurrent(before.receipt), false, "admission revokes before a body exists") + const fresh = owner.admit(stream.grant.token, "principal")! + assert.equal(fresh.publish({ revision: 3, refs: [ref()] }, unavailable), true) + assert.equal(old.publish({ revision: 2, refs: [] }, unavailable), false) + assert.equal(publish(3), false) + assert.equal(owner.snapshot("A").owners[0]!.observation, "unknown") + assert.equal(publish(4), true) + const stable = owner.snapshot("A") + stream.close(); stream.close() + assert.equal(owner.isCurrent(stable.receipt), false) + assert.equal(owner.admit(stream.grant.token, "principal"), undefined) + assert.equal(owner.snapshot("A").unresolvedOwners, 1) + assert.equal(owner.snapshot("A").refs.length, 1, "loss keeps bounded positive refs with unknown coverage") + assert.equal(owner.snapshot("A").status, "unknown") + const replacement = owner.register("principal", () => true)! + assert.notEqual(replacement.grant.token, stream.grant.token) + assert.equal(owner.admit(replacement.grant.token, "principal")!.publish({ revision: 1, refs: [ref()] }, unavailable), true) + assert.equal(owner.isCurrent(stable.receipt), false) + owner.dispose() + assert.equal(owner.isCurrent(owner.snapshot("A").receipt), false) +}) + +test("binding provenance, principal loss and same-ID replacement fence current before IO", () => { + const owner = new ProjectParticipants(); let authorized = true, identity: object = {}, calls = 0 + const stream = owner.register("principal", () => authorized)! + const resolve = () => { calls++; return { owner: identity, serverId: "A", directory: "/same" } } + const value = { revision: 1, refs: [{ ...ref("A", "/same"), workspaceId: "same" }] } + assert.equal(owner.admit(stream.grant.token, "principal")!.publish(value, resolve), true) + const captured = owner.snapshot("A") + identity = {} + assert.equal(owner.isCurrent(captured.receipt), false) + assert.equal(owner.snapshot("A").owners[0]!.observation, "unknown") + assert.equal(owner.admit(stream.grant.token, "principal")!.publish({ ...value, revision: 2 }, resolve), true) + const newer = owner.snapshot("A") + authorized = false + const before = calls + assert.equal(owner.isCurrent(newer.receipt), false) + assert.equal(calls, before, "revocation precedes binding resolution") + authorized = true + assert.equal(owner.admit(stream.grant.token, "principal"), undefined, "authorization returning never revives the retired grant") + assert.equal(owner.isCurrent(newer.receipt), false) +}) + +test("strict metadata limits reject selectors and forged refs before resolution, with a fresh positive after each refusal", () => { + const owner = new ProjectParticipants(), stream = owner.register("principal", () => true)! + let revision = 0 + for (const invalid of [ + { profile: "other" }, { config: "/secret" }, { ownerId: randomUUID() }, { credential: "PRIVATE" }, + { refs: [ref("../bad")] }, { refs: [ref("A", "x\0y")] }, { refs: [ref("A", "x".repeat(4097))] }, + { refs: Array.from({ length: 33 }, () => ref()) }, { refs: [ref(), { ...ref(), draft: "PRIVATE" }] }, + ]) { + assert.equal(owner.admit(stream.grant.token, "principal")!.publish({ revision: ++revision, refs: [], ...invalid }, unavailable), false) + assert.equal(owner.admit(stream.grant.token, "principal")!.publish({ revision: ++revision, refs: [ref()] }, unavailable), true) + assert.equal(owner.snapshot("A").status, "unknown") + } + const duplicate = ref() + assert.equal(owner.admit(stream.grant.token, "principal")!.publish({ revision: ++revision, refs: [duplicate, duplicate] }, unavailable), false) + assert.equal(owner.admit(stream.grant.token, "principal")!.publish({ revision: ++revision, refs: [ref()] }, unavailable), true) + assert.equal(owner.admit(stream.grant.token, "principal")!.publish({ revision: ++revision, refs: [], unknown: true }, unavailable), true) + assert.equal(owner.snapshot("A").owners[0]!.observation, "unknown") +}) + +test("32-owner/512-ref ceilings preserve unknown without TTL reclamation or enlarged test limits", () => { + const owner = new ProjectParticipants() + const streams = Array.from({ length: 32 }, () => owner.register("principal", () => true)!) + for (const stream of streams.slice(0, 16)) assert.equal(owner.admit(stream.grant.token, "principal")!.publish({ revision: 1, refs: Array.from({ length: 32 }, () => ref()) }, unavailable), true) + assert.equal(owner.snapshot("A").refs.length, 512) + const admission = owner.admit(streams[16]!.grant.token, "principal")!, captured = owner.snapshot("A") + assert.equal(captured.overflow, false) + assert.equal(admission.publish({ revision: 1, refs: [ref()] }, unavailable), false) + assert.equal(owner.isCurrent(captured.receipt), false, "overflow after a held body retires its observable snapshot") + assert.equal(owner.register("principal", () => true), undefined) + streams[0]!.close() + assert.equal(owner.snapshot("A").refs.length, 512) + assert.equal(owner.snapshot("A").overflow, true) + assert.equal(owner.snapshot("A").status, "unknown") + assert.equal(owner.register("principal", () => true), undefined) + assert.equal(owner.admit(streams[1]!.grant.token, "principal")!.publish({ revision: 2, refs: [ref()] }, unavailable), true) + assert.equal(owner.snapshot("A").refs.length, 481) +}) + +test("authorization loss observed inside an admitted publication retires the grant across return ABA", () => { + const owner = new ProjectParticipants(); let authorized = true + const stream = owner.register("principal", () => authorized)!, admitted = owner.admit(stream.grant.token, "principal")! + const value = { revision: 1, refs: [{ ...ref("A", "/same"), workspaceId: "same" }] } + assert.equal(admitted.publish(value, () => { authorized = false; return { serverId: "A", directory: "/same", owner: {} } }), false) + authorized = true + assert.equal(owner.admit(stream.grant.token, "principal"), undefined) + const fresh = owner.register("principal", () => true)! + assert.equal(owner.admit(fresh.grant.token, "principal")!.publish({ revision: 1, refs: [ref()] }, unavailable), true) +}) + +test("monotonic publication deadline fences held bodies and expiry crossed during resolution", t => { + let now = 0 + t.mock.method(performance, "now", () => now) + const owner = new ProjectParticipants(), stream = owner.register("principal", () => true)! + const held = owner.admit(stream.grant.token, "principal")! + now = 5_000 + assert.equal(held.publish({ revision: 1, refs: [ref()] }, unavailable), false) + const crossed = owner.admit(stream.grant.token, "principal")! + assert.equal(crossed.publish({ revision: 1, refs: [{ ...ref("A", "/same"), workspaceId: "same" }] }, () => { + now = 10_001; return { serverId: "A", directory: "/same", owner: {} } + }), false) + assert.equal(owner.admit(stream.grant.token, "principal")!.publish({ revision: 2, refs: [ref()] }, unavailable), true) + assert.equal(owner.snapshot("A").owners[0]!.observation, "declared") +}) + +test("unreadable principals/bindings fail closed without exposing callback errors", () => { + const owner = new ProjectParticipants(); let fail = false + const stream = owner.register("principal", () => { if (fail) throw new Error("PRIVATE_PRINCIPAL_ERROR"); return true })! + const value = { revision: 1, refs: [{ ...ref("A", "/same"), workspaceId: "same" }] } + assert.equal(owner.admit(stream.grant.token, "principal")!.publish(value, () => { throw new Error("PRIVATE_BINDING_ERROR") }), false) + assert.equal(owner.admit(stream.grant.token, "principal")!.publish({ revision: 2, refs: [ref()] }, unavailable), true) + const captured = owner.snapshot("A") + fail = true + assert.equal(owner.isCurrent(captured.receipt), false) + fail = false + assert.equal(owner.admit(stream.grant.token, "principal"), undefined) + assert.doesNotMatch(JSON.stringify(owner.snapshot("A")), /PRIVATE|principal/) + const fresh = owner.register("principal", () => true)! + assert.equal(owner.admit(fresh.grant.token, "principal")!.publish({ revision: 1, refs: [ref()] }, unavailable), true) +}) diff --git a/packages/server/src/workspaces/project-participants.ts b/packages/server/src/workspaces/project-participants.ts new file mode 100644 index 0000000000..f578c7aa81 --- /dev/null +++ b/packages/server/src/workspaces/project-participants.ts @@ -0,0 +1,123 @@ +import { randomBytes, randomUUID } from "node:crypto" +import { z } from "zod" +import { OpenCodeServerIdSchema } from "../config/schema" + +export const PARTICIPATION_HEADER = "x-codenomad-participation" +export const PARTICIPATION_EVENT = "codenomad.project.participation" +export interface ProjectParticipationGrant { token: string } +export interface ProjectParticipationRef { tabId: string; serverId: string; directory: string; workspaceId?: string } +export interface ProjectParticipationUpdate { revision: number; refs: ProjectParticipationRef[]; unknown?: true } +const updateSchema = z.object({ + revision: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER), + unknown: z.literal(true).optional(), + refs: z.array(z.object({ tabId: z.string().uuid(), serverId: OpenCodeServerIdSchema, + directory: z.string().min(1).max(4096).refine(value => value.trim().length > 0 && !value.includes("\0")), + workspaceId: z.string().min(1).max(512).optional(), + }).strict()).max(32), +}).strict() +type Binding = { serverId: string; directory: string; owner: object } +type Participant = { id: string; principal: string; current: () => boolean; revision: number; admission?: object; + refs: ProjectParticipationRef[]; bindings: Array<() => boolean>; known: boolean } +const holds = (check: () => boolean) => { try { return check() } catch { return false } } + +/** Positive declarations only. Every snapshot keeps unknown overall participation. */ +export class ProjectParticipants { + private readonly active = new Map() + private readonly lost = new Map() + private epoch = randomUUID() + private closed = false + private overflow = false + + private changed() { this.epoch = randomUUID() } + private overflowed() { if (!this.overflow) { this.overflow = true; this.changed() } } + register(principal: string, current: () => boolean) { + this.changed() // Admission is visible before the grant can reach a renderer. + if (this.closed || !holds(current)) return undefined + // ponytail: uncertain closed streams retain one bounded slot until backend restart; + // reclaim only after an authenticated retirement/reconciliation contract is qualified. + if (this.active.size + this.lost.size >= 32) { this.overflowed(); return undefined } + const token = randomBytes(32).toString("hex"), participant: Participant = { + id: randomUUID(), principal, current, revision: 0, refs: [], bindings: [], known: false, + } + this.active.set(token, participant) + return { grant: { token }, close: () => this.retire(token, participant) } + } + + private retire(token: string, participant: Participant) { + if (this.active.get(token) !== participant) return + this.active.delete(token) + this.lost.set(participant.id, participant.refs) + this.changed() + } + + /** Called before body parsing; each overlapping request owns a separate admission. */ + admit(token: unknown, principal: string) { + if (typeof token !== "string" || !/^[a-f0-9]{64}$/.test(token) || this.closed) return undefined + const participant = this.active.get(token) + if (!participant || participant.principal !== principal) return undefined + if (!holds(participant.current)) { this.retire(token, participant); return undefined } + const admission = {} + const expiresAt = performance.now() + 5_000 + participant.admission = admission; participant.known = false; this.changed() + const current = () => { + if (this.closed || this.active.get(token) !== participant) return false + if (!holds(participant.current)) { this.retire(token, participant); return false } + return true + } + return { + publish: (value: unknown, resolve: (id: string) => Binding | undefined) => { + if (!current() || performance.now() >= expiresAt || participant.admission !== admission) return false + const parsed = updateSchema.safeParse(value) + if (!parsed.success || parsed.data.revision <= participant.revision) return false + const update = parsed.data + if (update.unknown) { + if (update.refs.length) return false + participant.revision = update.revision; this.changed(); return true + } + if (new Set(update.refs.map(ref => ref.tabId)).size !== update.refs.length) return false + const total = [...this.active.values()].reduce((count, item) => count + (item === participant ? 0 : item.refs.length), 0) + + [...this.lost.values()].reduce((count, refs) => count + refs.length, 0) + if (total + update.refs.length > 512) { this.overflowed(); return false } + const bindings: Array<() => boolean> = [] + const lookup = (id: string) => { try { return resolve(id) } catch { return undefined } } + for (const ref of update.refs) if (ref.workspaceId !== undefined) { + const id = ref.workspaceId, captured = lookup(id) + if (!captured || captured.serverId !== ref.serverId || captured.directory !== ref.directory) return false + bindings.push(() => { const now = lookup(id); return !!now && now.owner === captured.owner + && now.serverId === captured.serverId && now.directory === captured.directory }) + } + if (!current() || performance.now() >= expiresAt || participant.admission !== admission) return false + participant.refs = update.refs.map(ref => ({ ...ref })); participant.bindings = bindings + participant.revision = update.revision; participant.known = true; this.changed() + return true + }, + } + } + + private revalidate() { + for (const [token, participant] of this.active) { + if (!holds(participant.current)) { this.retire(token, participant); continue } + if (participant.known && participant.bindings.some(current => !holds(current))) { + participant.known = false; participant.bindings = []; this.changed() + } + } + } + + snapshot(serverId: string) { + this.revalidate() + return { receipt: this.epoch, status: "unknown" as const, overflow: this.overflow, + referenceCount: [...this.active.values()].reduce((count, participant) => count + participant.refs.length, 0) + + [...this.lost.values()].reduce((count, refs) => count + refs.length, 0), + owners: [...this.active.values()].map(participant => ({ ownerId: participant.id, observation: participant.known ? "declared" as const : "unknown" as const })) + .concat([...this.lost.keys()].map(ownerId => ({ ownerId, observation: "unknown" as const }))), + refs: [...this.active.values()].flatMap(participant => participant.refs.filter(ref => ref.serverId === serverId) + .map(ref => ({ ...ref, ownerId: participant.id, source: "participant" as const }))) + .concat([...this.lost].flatMap(([ownerId, refs]) => refs.filter(ref => ref.serverId === serverId) + .map(ref => ({ ...ref, ownerId, source: "participant" as const })))), + unresolvedOwners: this.lost.size, + } + } + + isCurrent(receipt: string) { this.revalidate(); return !this.closed && receipt === this.epoch } + dispose() { this.closed = true; this.active.clear(); this.lost.clear(); this.changed() } +} diff --git a/packages/server/src/workspaces/server-attachments.ts b/packages/server/src/workspaces/server-attachments.ts new file mode 100644 index 0000000000..69a5708d41 --- /dev/null +++ b/packages/server/src/workspaces/server-attachments.ts @@ -0,0 +1,58 @@ +import { randomUUID } from "node:crypto" +import { z } from "zod" +import { OpenCodeServerIdSchema } from "../config/schema" +import type { NativeParent } from "../native-parent" +import type { WorkspaceManager } from "./manager" + +const desktopSchema = z.object({ + receipt: z.string().uuid(), status: z.literal("unknown"), retainedStatus: z.enum(["complete", "unknown"]), + owners: z.array(z.object({ ownerId: z.string().uuid(), live: z.boolean(), retained: z.boolean() }).strict()).max(32), + refs: z.array(z.object({ ownerId: z.string().uuid(), tabId: z.string().uuid(), source: z.literal("retained"), + serverId: OpenCodeServerIdSchema, directory: z.string().min(1).max(4096).refine(value => !value.includes("\0")), + }).strict()).max(512), +}).strict() + +/** Backend-owned snapshot, kept internal until a consumer has qualified every participant. */ +export async function readServerAttachments(manager: WorkspaceManager, parent: Pick, serverId: string) { + OpenCodeServerIdSchema.parse(serverId) + // Capture owners before the first defer: a formerly empty reader cannot adopt new reservations. + const connections = manager.getServerConnections() + const workspaces = manager.attachmentReservations(serverId), leases = connections.attachmentReservations(serverId) + const participants = manager.projectParticipants.snapshot(serverId) + const receipt = randomUUID() + const backendCurrent = () => manager.attachmentReceiptCurrent(workspaces.receipt) && connections.attachmentReceiptCurrent(leases.receipt) + && manager.projectParticipants.isCurrent(participants.receipt) + let desktop: z.infer | undefined + if (parent.available) { + try { + const value = await parent.request("projects.attachments.read", {}, 5_000) + if (Buffer.byteLength(JSON.stringify(value), "utf8") > 8 * 1024 * 1024) throw new Error("attachment_inventory_unavailable") + const parsed = desktopSchema.parse(value) + const owners = new Set(parsed.owners.map(owner => owner.ownerId)) + if (owners.size !== parsed.owners.length || new Set(parsed.refs.map(ref => ref.tabId)).size !== parsed.refs.length + || parsed.refs.some(ref => !owners.has(ref.ownerId))) throw new Error("attachment_inventory_unavailable") + desktop = parsed + } catch { /* Missing, unreadable or retired native metadata preserves unknown coverage. */ } + } + const current = async () => { + if (!backendCurrent() || !desktop) return false + try { + const valid = await parent.request("projects.attachments.current", { receipt: desktop.receipt }, 5_000) + return valid === true && backendCurrent() + } catch { return false } + } + const valid = await current() + const bounded = (desktop?.owners.length ?? 0) + participants.owners.length <= 32 + && (desktop?.refs.length ?? 0) + participants.referenceCount <= 512 + return { + receipt, serverId, status: "unknown" as const, + coverage: { retained: valid && bounded ? desktop!.retainedStatus : "unknown", live: "unknown", participants: "unknown" }, + observationOverflow: !bounded, + owners: valid && bounded ? desktop!.owners : [], + refs: valid && bounded ? desktop!.refs.filter(ref => ref.serverId === serverId) : [], + // These independent owner views overlap; they are never added as tab counts. + backend: backendCurrent() ? { workspaces, leases } : undefined, + participants: backendCurrent() && bounded ? participants : undefined, + isCurrent: current, + } +} diff --git a/packages/server/src/workspaces/temporary-workspaces.test.ts b/packages/server/src/workspaces/temporary-workspaces.test.ts index b1dcf09399..399a79db4c 100644 --- a/packages/server/src/workspaces/temporary-workspaces.test.ts +++ b/packages/server/src/workspaces/temporary-workspaces.test.ts @@ -6,12 +6,13 @@ import { test } from "node:test" import { TemporaryFolderRegistry, TemporaryWorkspaceError, TemporaryWorkspaces } from "./temporary-workspaces" import { WorktreeDeletionFence } from "./worktree-session-evacuation" import type { WorkspaceManager } from "./manager" +import { WorkspaceCapabilityError } from "../opencode/servers/capabilities" async function harness() { const base = await mkdtemp(path.join(os.tmpdir(), "codenomad-temporary-")) const file = path.join(base, "temporary-workspaces.json") const registry = await TemporaryFolderRegistry.open(path.join(base, "temporary-workspaces"), file) - const workspaces = new Map() + const workspaces = new Map() const removed: string[] = [] const cleared: string[] = [] let sessions: Array<{ id: string; parentID?: string; location: { directory: string } }> = [] @@ -29,13 +30,17 @@ async function harness() { }, } const manager = { + requireWorkspaceCapability(id: string, capability: "worktrees") { + if (workspaces.get(id)?.binding) throw new WorkspaceCapabilityError(capability, { code: "deferred" }) + return new AbortController().signal + }, get: (id: string) => workspaces.get(id), list: () => [...workspaces.values()], getServiceDirectory: (id: string) => workspaces.get(id)?.path, getSharedServiceClient: async () => client, delete: async (id: string) => { workspaces.delete(id) }, reserveWorktreeDeletion: async (folder: string) => { - if ([...workspaces.values()].some((workspace) => workspace.path.toLowerCase() === folder.toLowerCase())) { + if ([...workspaces.values()].some((workspace) => !workspace.binding && workspace.path.toLowerCase() === folder.toLowerCase())) { throw new Error("Worktree is open as another workspace") } return () => {} @@ -76,6 +81,28 @@ test("temporary folders are created under the root and survive a restart only wh } finally { await h.cleanup() } }) +test("explicit bindings cannot keep or discard a colliding host temporary folder", async () => { + const h = await harness() + try { + const folder = await h.temporary.createFolder() + await writeFile(path.join(folder, "sentinel"), "local") + h.workspaces.set("local", { id: "local", path: folder }) + h.setSessions([{ id: "same-session", location: { directory: folder } }]) + for (const serverId of ["A", "B"]) { + h.workspaces.set(serverId, { id: serverId, path: folder, binding: { serverId, directory: folder } }) + for (const operation of [() => h.temporary.keep(serverId), () => h.temporary.discard(serverId)]) { + await assert.rejects(operation(), (error: unknown) => error instanceof WorkspaceCapabilityError && error.capability === "worktrees") + } + assert.equal(h.registry.has(folder), true) + assert.equal(await readFile(path.join(folder, "sentinel"), "utf8"), "local") + assert.deepEqual(h.removed, []) + assert.deepEqual(h.cleared, []) + } + await h.temporary.discard("local") + assert.deepEqual(h.removed, ["same-session"]) + } finally { await h.cleanup() } +}) + test("keeping a temporary workspace unregisters it without touching the folder", async () => { const h = await harness() try { diff --git a/packages/server/src/workspaces/temporary-workspaces.ts b/packages/server/src/workspaces/temporary-workspaces.ts index 4cdbb7c64b..0c525298f4 100644 --- a/packages/server/src/workspaces/temporary-workspaces.ts +++ b/packages/server/src/workspaces/temporary-workspaces.ts @@ -200,6 +200,7 @@ export class TemporaryWorkspaces { private requireTemporary(workspaceId: string) { const workspace = this.options.workspaceManager.get(workspaceId) if (!workspace) throw new TemporaryWorkspaceError("temporary_not_found", "Workspace not found", 404) + this.options.workspaceManager.requireWorkspaceCapability(workspaceId, "worktrees") if (!this.options.registry.has(workspace.path)) { throw new TemporaryWorkspaceError("temporary_not_temporary", "This workspace is not temporary", 400) } @@ -223,7 +224,9 @@ export class TemporaryWorkspaces { async discard(workspaceId: string, options: { onlyIfEmpty?: boolean } = {}): Promise { const manager = this.options.workspaceManager const workspace = this.requireTemporary(workspaceId) - if (manager.list().some((other) => other.id !== workspaceId && this.options.registry.sameFolder(other.path, workspace.path))) { + if (manager.list().some((other) => other.id !== workspaceId + && (other.binding?.serverId ?? "local-shared") === "local-shared" + && this.options.registry.sameFolder(other.path, workspace.path))) { throw new TemporaryWorkspaceError("temporary_open_elsewhere", "This temporary folder is open in another tab", 409) } const serviceDirectory = manager.getServiceDirectory(workspaceId) ?? workspace.path diff --git a/packages/tauri-app/src-tauri/src/cli_manager.rs b/packages/tauri-app/src-tauri/src/cli_manager.rs index 04d02dd130..3da2982f91 100644 --- a/packages/tauri-app/src-tauri/src/cli_manager.rs +++ b/packages/tauri-app/src-tauri/src/cli_manager.rs @@ -1503,6 +1503,7 @@ impl CliProcessManager { &request.method, request.params, request.deadline, + generation, ) }; manager.write_native_response( diff --git a/packages/tauri-app/src-tauri/src/client_state.rs b/packages/tauri-app/src-tauri/src/client_state.rs index 0f022b6191..106d13c028 100644 --- a/packages/tauri-app/src-tauri/src/client_state.rs +++ b/packages/tauri-app/src-tauri/src/client_state.rs @@ -1,4 +1,5 @@ mod access; +mod attachments; mod commands; mod cross_host; mod envelope; @@ -98,6 +99,7 @@ pub struct ClientState { renderer_flush: RendererFlush, startup_commands: startup_command::StartupCommands, write_state: StateWriter, + attachment_state: Mutex, } type StateWriter = @@ -109,6 +111,7 @@ impl ClientState { window_id: &str, url: &Url, ) -> Result<(), String> { + self.attachments_changed(); self.renderer_access .begin_navigation_for(window_id, Some(url)) .map(|_| ()) @@ -233,6 +236,7 @@ impl ClientState { renderer_flush: RendererFlush::default(), startup_commands: startup_command::StartupCommands::default(), write_state, + attachment_state: Mutex::new(attachments::AttachmentState::default()), } } @@ -336,7 +340,7 @@ impl ClientState { &self, request: Option, ) -> Result { - let _write = self.write_lock.lock().map_err(|err| err.to_string())?; + let _write = self.attachment_publication_guard()?; if !self.is_primary() { return Ok(false); } @@ -351,6 +355,7 @@ impl ClientState { let previous = (state.preferences.clone(), state.last_preferences.clone()); if let Some(request) = &request { state.last_preferences = Some(crate::preferences_window::PreferencesRequest { + server_id: None, section: request.section.clone(), scroll_top: request.scroll_top, instance_id: None, @@ -382,7 +387,7 @@ impl ClientState { } pub(crate) fn set_active_window(&self, window_id: &str) -> Result { - let _write = self.write_lock.lock().map_err(|err| err.to_string())?; + let _write = self.attachment_publication_guard()?; if !self.is_primary() { return Ok(false); } @@ -419,7 +424,7 @@ impl ClientState { access_token: &str, renderer_url: &Url, ) -> Result<(), String> { - let _write = self.write_lock.lock().map_err(|err| err.to_string())?; + let _write = self.attachment_publication_guard()?; let persisted = self .state .lock() @@ -547,7 +552,7 @@ impl ClientState { snapshot: Value, access_valid: impl Fn() -> bool, ) -> Result { - let _write = self.write_lock.lock().map_err(|err| err.to_string())?; + let _write = self.attachment_publication_guard()?; if !access_valid() { return Err("Client state renderer authority changed before mutation".to_string()); } @@ -593,7 +598,7 @@ impl ClientState { payload: partitions::PartitionCommit, access_valid: impl Fn() -> bool, ) -> Result { - let _write = self.write_lock.lock().map_err(|err| err.to_string())?; + let _write = self.attachment_publication_guard()?; if !access_valid() { return Err("Client state renderer authority changed before mutation".to_string()); } @@ -650,7 +655,7 @@ impl ClientState { enabled: bool, access_valid: impl Fn() -> bool, ) -> Result { - let _write = self.write_lock.lock().map_err(|err| err.to_string())?; + let _write = self.attachment_publication_guard()?; if !access_valid() { return Err("Client state renderer authority changed before mutation".to_string()); } @@ -699,7 +704,7 @@ impl ClientState { window_id: &str, access_valid: impl Fn() -> bool, ) -> Result { - let _write = self.write_lock.lock().map_err(|err| err.to_string())?; + let _write = self.attachment_publication_guard()?; if !access_valid() { return Err("Client state renderer authority changed before mutation".to_string()); } @@ -736,7 +741,7 @@ impl ClientState { } fn flush(&self) -> Result<(), String> { - let _write = self.write_lock.lock().map_err(|err| err.to_string())?; + let _write = self.attachment_publication_guard()?; let unsupported = self .state .lock() @@ -787,9 +792,14 @@ impl ClientState { let state = self.state.lock().map_err(|err| err.to_string())?; serde_json::to_vec(&*state).map_err(|err| err.to_string())? }; - (self.write_state)(&self.state_path, &bytes, &|| { + let result = (self.write_state)(&self.state_path, &bytes, &|| { self.is_primary() && replacement_valid() - })?; + }); + if let Ok(mut attachments) = self.attachment_state.lock() { + attachments.publication_unknown = result.is_err(); + attachments.epoch = uuid::Uuid::new_v4().to_string(); + } + result?; // New events may already be queued, but only this serialized writer can // have merged captures into the state we just published. self.window_captures_published(); @@ -822,7 +832,7 @@ impl ClientState { } pub(crate) fn add_window(&self, window_id: String) -> Result { - let _write = self.write_lock.lock().map_err(|err| err.to_string())?; + let _write = self.attachment_publication_guard()?; if !self.is_primary() { return Ok(false); } @@ -853,6 +863,7 @@ impl ClientState { } pub(crate) fn unregister_window(&self, window_id: &str) { + self.attachments_changed(); self.renderer_access.remove(window_id); if let Ok(mut windows) = self.ephemeral_windows.lock() { windows.remove(window_id); @@ -863,7 +874,7 @@ impl ClientState { } pub(crate) fn remove_window(&self, window_id: &str) -> Result { - let _write = self.write_lock.lock().map_err(|err| err.to_string())?; + let _write = self.attachment_publication_guard()?; if !self.is_primary() { return Ok(false); } @@ -899,6 +910,8 @@ impl ClientState { } fn release_locks(&self) { + let _publication = self.attachment_publication_admission().ok(); + self.attachments_changed(); self.stop_window_captures(); self.window_flush.stop(); // Lock order fences takeover until root publication and partition GC leave write_lock. diff --git a/packages/tauri-app/src-tauri/src/client_state/attachments.rs b/packages/tauri-app/src-tauri/src/client_state/attachments.rs new file mode 100644 index 0000000000..137bc89048 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/client_state/attachments.rs @@ -0,0 +1,192 @@ +use super::{envelope::WindowRecord, partitions, ClientState}; +use crate::local_windows::LocalWindows; +use serde_json::{json, Value}; +use std::collections::{HashMap, HashSet}; +use std::sync::{Mutex, MutexGuard}; + +pub(super) struct AttachmentState { + pub(super) epoch: String, + pub(super) publication_unknown: bool, + publications: HashSet, + #[cfg(test)] + after_admission: Option>, + captured: Option<(String, String, String)>, + owners: HashMap, + tabs: HashMap, + backend_generation: Option, +} + +impl Default for AttachmentState { + fn default() -> Self { + Self { epoch: uuid::Uuid::new_v4().to_string(), publication_unknown: false, publications: HashSet::new(), + #[cfg(test)] after_admission: None, + captured: None, owners: HashMap::new(), tabs: HashMap::new(), backend_generation: None } + } +} + +pub(super) struct PublicationAdmission<'a> { + state: &'a Mutex, + owner: String, +} + +impl Drop for PublicationAdmission<'_> { + fn drop(&mut self) { + if let Ok(mut state) = self.state.lock() { + state.publications.remove(&self.owner); + state.epoch = uuid::Uuid::new_v4().to_string(); + } + } +} + +pub(super) struct PublicationGuard<'a> { + _admission: PublicationAdmission<'a>, + _write: MutexGuard<'a, ()>, +} + +// Read only the accepted tab manifest; workspace/session/blob partitions remain unopened. +fn project_metadata(record: &WindowRecord, load: impl Fn(&str) -> Option) -> Option> { + if !record.restore_enabled { return Some(vec![]); } + let root = record.snapshot.as_ref()?.as_object()?; + let partitioned = record.partition_protocol_version == Some(1); + let manifest; + let session = if partitioned { + partitions::validate_root(record.snapshot.as_ref()?)?; + let key = root.get("sessionPartition")?.as_str()?; + if !record.partition_keys.as_ref()?.iter().any(|value| value == key) { return None; } + manifest = serde_json::from_str::(&load(key)?).ok()?; + if manifest.get("format")?.as_u64()? != 2 || !manifest.as_object()?.keys().all(|key| ["format", "session"].contains(&key.as_str())) { return None; } + manifest.get("session")? + } else { + if root.get("version").is_some_and(|version| version.as_u64() != Some(1)) { return None; } + root.get("session")? + }; + if session.is_null() { return Some(vec![]); } + let session = session.as_object()?; + if !session.keys().all(|key| ["tabs", "activeTabIndex", "homeActive"].contains(&key.as_str())) { return None; } + let tabs = session.get("tabs")?.as_array()?; + if tabs.len() > 32 { return None; } + let active = session.get("activeTabIndex")?.as_i64()?; + if active < -1 || active >= tabs.len() as i64 || session.get("homeActive").is_some_and(|value| !value.is_boolean()) { return None; } + let mut result = Vec::new(); + for (index, raw) in tabs.iter().enumerate() { + let tab = raw.as_object()?; + let kind = tab.get("kind").or_else(|| tab.get("type"))?.as_str()?; + if kind == "sidecar" { + let id = tab.get("sidecarId")?.as_str()?; + if id.is_empty() || id.encode_utf16().count() > 512 { return None; } + continue; + } + if kind != "workspace" && (partitioned || kind != "instance") { return None; } + let directory = tab.get("folder")?.as_str()?; + if directory.trim().is_empty() || directory.encode_utf16().count() > 4096 || directory.contains('\0') { return None; } + let server_id = match tab.get("serverId") { Some(value) => value.as_str()?, None => "local-shared" }; + if server_id.is_empty() || server_id.len() > 128 || !server_id.as_bytes()[0].is_ascii_alphanumeric() + || !server_id.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') { return None; } + if let Some(value) = tab.get("occurrence") { + if value.as_u64()? >= 32 { return None; } + } + if partitioned { + let key = tab.get("workspacePartition")?.as_str()?; + if !partitions::valid_key(key) || !record.partition_keys.as_ref()?.iter().any(|value| value == key) { return None; } + } + result.push(json!({ "index": index, "serverId": server_id, "directory": directory })); + } + Some(result) +} + +impl ClientState { + pub(crate) fn bind_attachment_backend(&self, generation: u64) { + if let Ok(mut state) = self.attachment_state.lock() { + if state.backend_generation != Some(generation) { + state.backend_generation = Some(generation); + state.epoch = uuid::Uuid::new_v4().to_string(); + state.captured = None; + state.owners.clear(); state.tabs.clear(); + } + } + } + pub(super) fn attachments_changed(&self) { + if let Ok(mut state) = self.attachment_state.lock() { state.epoch = uuid::Uuid::new_v4().to_string(); } + } + + pub(super) fn attachment_publication_admission(&self) -> Result, String> { + let owner = uuid::Uuid::new_v4().to_string(); + self.attachment_state.lock().map_err(|_| "attachment_inventory_unavailable")?.publications.insert(owner.clone()); + Ok(PublicationAdmission { state: &self.attachment_state, owner }) + } + + pub(super) fn attachment_publication_guard(&self) -> Result, String> { + // Each waiting writer keeps its own fence through publication and rollback. + let admission = self.attachment_publication_admission()?; + self.attachments_changed(); + #[cfg(test)] + { + let hook = self.attachment_state.lock().unwrap().after_admission.take(); + if let Some(hook) = hook { hook(); } + } + let write = self.write_lock.lock().map_err(|error| error.to_string())?; + Ok(PublicationGuard { _admission: admission, _write: write }) + } + + fn attachment_epoch_current(&self, epoch: &str) -> bool { + self.is_primary() && self.attachment_state.lock().is_ok_and(|state| state.epoch == epoch && !state.publication_unknown) + } + + pub(crate) fn attachment_inventory(&self, windows: &LocalWindows) -> Result { + let epoch = self.attachment_state.lock().map_err(|_| "attachment_inventory_unavailable")?.epoch.clone(); + let (window_epoch, live) = windows.attachment_membership()?; + // Publication and rollback share this lock. Never project tentative state. + let _write = self.write_lock.lock().map_err(|_| "attachment_inventory_unavailable")?; + let state = self.state.lock().map_err(|_| "attachment_inventory_unavailable")?; + let receipt = uuid::Uuid::new_v4().to_string(); + { + let mut handles = self.attachment_state.lock().map_err(|_| "attachment_inventory_unavailable")?; + handles.captured = Some((receipt.clone(), epoch.clone(), window_epoch.clone())); + handles.owners.clear(); handles.tabs.clear(); + } + let unknown = || json!({ "receipt": receipt, "status": "unknown", "retainedStatus": "unknown", "owners": [], "refs": [] }); + if state.unsupported_future_envelope || !self.attachment_epoch_current(&epoch) { return Ok(unknown()); } + let ids: HashSet<_> = live.iter().chain(state.window_order.iter()).collect(); + let mut owners = vec![]; + let mut refs = vec![]; + let mut owner_handles = HashMap::new(); + let mut tab_handles = HashMap::new(); + let mut complete = true; + for id in ids { + let owner_id = uuid::Uuid::new_v4().to_string(); + owner_handles.insert(owner_id.clone(), id.clone()); + let record = state.windows.get(id); + owners.push(json!({ "ownerId": owner_id, "live": live.contains(id), "retained": record.is_some() })); + if let Some(record) = record { + let tabs = project_metadata(record, |key| self.partition_store().load(key, &|| self.attachment_epoch_current(&epoch)).ok().flatten()); + match tabs { + Some(tabs) => for tab in tabs { + let tab_id = uuid::Uuid::new_v4().to_string(); + tab_handles.insert(tab_id.clone(), (id.clone(), tab["index"].as_u64().unwrap_or(0) as usize)); + refs.push(json!({ "ownerId": owner_id, "tabId": tab_id, "source": "retained", "serverId": tab["serverId"], "directory": tab["directory"] })); + }, + None => complete = false, + } + } + } + if !self.attachment_epoch_current(&epoch) || windows.attachment_membership()?.0 != window_epoch { return Ok(unknown()); } + { + let mut handles = self.attachment_state.lock().map_err(|_| "attachment_inventory_unavailable")?; + handles.owners = owner_handles; + handles.tabs = tab_handles; + } + // Live tab reports and browser participation require their own attestation path. + Ok(json!({ "receipt": receipt, "status": "unknown", "retainedStatus": if complete { "complete" } else { "unknown" }, "owners": owners, "refs": refs })) + } + + pub(crate) fn attachment_receipt_current(&self, receipt: &str, windows: &LocalWindows) -> bool { + let captured = self.attachment_state.lock().ok().and_then(|state| state.captured.clone()); + captured.is_some_and(|(current, epoch, window_epoch)| current == receipt && self.is_primary() + && self.attachment_state.lock().is_ok_and(|state| state.epoch == epoch && !state.publication_unknown && state.publications.is_empty()) + && windows.attachment_membership().is_ok_and(|current| current.0 == window_epoch)) + } +} + +#[cfg(test)] +#[path = "attachments_tests.rs"] +mod tests; diff --git a/packages/tauri-app/src-tauri/src/client_state/attachments_tests.rs b/packages/tauri-app/src-tauri/src/client_state/attachments_tests.rs new file mode 100644 index 0000000000..568a2ddc69 --- /dev/null +++ b/packages/tauri-app/src-tauri/src/client_state/attachments_tests.rs @@ -0,0 +1,286 @@ +use super::*; +use std::fs; +use std::sync::{Arc, mpsc}; +use std::sync::atomic::{AtomicBool, Ordering}; + +fn vector() -> Value { + serde_json::from_str(include_str!("../../../../electron-app/electron/main/client-state-attachment-vector.json")).unwrap() +} + +fn snapshot() -> Value { + json!({"version":1, "revision":1, "savedAt":1, "layout":{}, "session":{"activeTabIndex":0, + "tabs":[{"kind":"workspace", "serverId":"unknown-A", "folder":"Z:\\Case\\Project/ ", "drafts":{"secret":"DRAFT_SENTINEL"}}]}}) +} + +#[test] +fn attachments_real_v1_v2_v3_migrations_keep_exact_shells_and_unknown_live_coverage() { + let fixture = vector(); + for version in [1, 2, 3] { + let directory = tempfile::tempdir().unwrap(); + let initial = if version == 1 { + json!({"version":1, "restoreEnabled":true, "snapshot":snapshot()}) + } else { + json!({"version":2, "restoreEnabled":true, "protocolVersion":1, + "snapshot":fixture["root"], "partitionKeys":fixture["partitionKeys"]}) + }; + fs::write(directory.path().join("client-state.json"), serde_json::to_vec(&initial).unwrap()).unwrap(); + fs::create_dir(directory.path().join("partitions")).unwrap(); + for (key, text) in fixture["partitions"].as_object().unwrap() { + fs::write(directory.path().join("partitions").join(key), text.as_str().unwrap()).unwrap(); + } + let state = ClientState::initialize_at(directory.path()).unwrap(); + if version == 3 { + let payload = json!({"protocolVersion":1, "snapshot":fixture["root"], "partitionKeys":fixture["partitionKeys"], "partitions":fixture["partitions"]}); + state.commit_partitions_guarded(serde_json::from_value(payload).unwrap(), || true).unwrap(); + } + let windows = LocalWindows::default(); + let result = state.attachment_inventory(&windows).unwrap(); + assert_eq!(result["status"], "unknown"); + assert_eq!(result["retainedStatus"], "complete"); + assert_eq!(result["refs"][0]["serverId"], "unknown-A"); + assert_eq!(result["refs"][0]["directory"], "Z:\\Case\\Project/ "); + assert_eq!(result["owners"].as_array().unwrap().len(), 1); + assert!(state.attachment_receipt_current(result["receipt"].as_str().unwrap(), &windows)); + assert!(!result.to_string().contains("DRAFT_SENTINEL")); + assert!(!result.to_string().contains("sessionPartition")); + if version != 1 { + let manifest = fixture["root"]["sessionPartition"].as_str().unwrap(); + fs::write(directory.path().join("partitions").join(manifest), "corrupt").unwrap(); + assert_eq!(state.attachment_inventory(&windows).unwrap()["retainedStatus"], "unknown"); + fs::remove_file(directory.path().join("partitions").join(manifest)).unwrap(); + assert_eq!(state.attachment_inventory(&windows).unwrap()["retainedStatus"], "unknown"); + } + } +} + +#[test] +fn attachments_metadata_never_follows_workspace_content_and_rejects_overflow_or_bad_identity() { + let fixture = vector(); + let record = WindowRecord { restore_enabled:true, snapshot:Some(fixture["root"].clone()), partition_protocol_version:Some(1), + partition_keys:Some(serde_json::from_value(fixture["partitionKeys"].clone()).unwrap()), ..WindowRecord::default() }; + let key = fixture["root"]["sessionPartition"].as_str().unwrap(); + let tabs = project_metadata(&record, |requested| { + assert_eq!(requested, key, "only the manifest may be read"); + Some(fixture["partitions"][key].as_str().unwrap().to_string()) + }).unwrap(); + assert_eq!(tabs.len(), 1); + for shell in [json!({"kind":"workspace","folder":"/x","serverId":"../bad"}), + json!({"kind":"workspace","folder":"x\u{0}y"}), json!({"kind":"workspace","folder":"/x","occurrence":32}), json!({"kind":"unknown"})] { + let record = WindowRecord { snapshot:Some(json!({"version":1,"session":{"tabs":[shell],"activeTabIndex":0}})), ..WindowRecord::default() }; + assert!(project_metadata(&record, |_| panic!("content read forbidden")).is_none()); + } + let record = WindowRecord { snapshot:Some(json!({"version":1,"session":{"tabs":vec![json!({"kind":"workspace","folder":"/x"});33],"activeTabIndex":0}})), ..WindowRecord::default() }; + assert!(project_metadata(&record, |_| panic!("content read forbidden")).is_none()); +} + +#[test] +fn attachments_corrupt_future_secondary_restore_off_and_receipt_aba_are_honest() { + for raw in ["{", "{\"version\":99}"] { + let directory = tempfile::tempdir().unwrap(); + fs::write(directory.path().join("client-state.json"), raw).unwrap(); + let state = ClientState::initialize_at(directory.path()).unwrap(); + assert_eq!(state.attachment_inventory(&LocalWindows::default()).unwrap()["retainedStatus"], "unknown"); + } + let directory = tempfile::tempdir().unwrap(); + let state = ClientState::initialize_at(directory.path()).unwrap(); + state.save_snapshot(snapshot()).unwrap(); + let windows = LocalWindows::default(); + let first = state.attachment_inventory(&windows).unwrap(); + let secondary = ClientState::initialize_at(directory.path()).unwrap(); + assert_eq!(secondary.attachment_inventory(&windows).unwrap()["retainedStatus"], "unknown"); + let id = state.active_window_id().unwrap(); + state.unregister_window(&id); + assert!(!state.attachment_receipt_current(first["receipt"].as_str().unwrap(), &windows)); + let second = state.attachment_inventory(&windows).unwrap(); + state.remove_window(&id).unwrap(); state.add_window(id).unwrap(); + assert!(!state.attachment_receipt_current(second["receipt"].as_str().unwrap(), &windows)); + state.set_restore_enabled(false).unwrap(); + let disabled = state.attachment_inventory(&windows).unwrap(); + assert_eq!(disabled["status"], "unknown"); + assert_eq!(disabled["refs"], json!([])); + state.release_locks(); + assert!(!state.attachment_receipt_current(disabled["receipt"].as_str().unwrap(), &windows)); +} + +#[test] +fn attachments_wait_for_real_publication_and_rollback_then_recover_with_a_new_receipt() { + let directory = tempfile::tempdir().unwrap(); + let holding = Arc::new(AtomicBool::new(false)); + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let release_rx = std::sync::Mutex::new(release_rx); + let flag = holding.clone(); + let state = Arc::new(ClientState::initialize_at_with_writer(directory.path(), Arc::new(move |path, bytes, valid| { + if flag.load(Ordering::SeqCst) { + entered_tx.send(()).unwrap(); release_rx.lock().unwrap().recv().unwrap(); + return Err("owned write failure".into()); + } + super::super::write_atomically(path, bytes, valid) + })).unwrap()); + state.save_snapshot(snapshot()).unwrap(); + let windows = Arc::new(LocalWindows::default()); + let first = state.attachment_inventory(&windows).unwrap(); + holding.store(true, Ordering::SeqCst); + let writer_state = state.clone(); + let writer = std::thread::spawn(move || writer_state.save_snapshot(json!({"version":1,"session":null}))); + entered_rx.recv().unwrap(); + assert!(!state.attachment_receipt_current(first["receipt"].as_str().unwrap(), &windows)); + let reader_state = state.clone(); let reader_windows = windows.clone(); + let (read_tx, read_rx) = mpsc::channel(); + let reader = std::thread::spawn(move || read_tx.send(reader_state.attachment_inventory(&reader_windows)).unwrap()); + assert!(read_rx.try_recv().is_err()); + release_tx.send(()).unwrap(); + assert!(writer.join().unwrap().is_err()); reader.join().unwrap(); + assert_eq!(read_rx.recv().unwrap().unwrap()["retainedStatus"], "unknown"); + holding.store(false, Ordering::SeqCst); + state.save_snapshot(snapshot()).unwrap(); + let fresh = state.attachment_inventory(&windows).unwrap(); + assert_eq!(fresh["refs"][0]["serverId"], "unknown-A"); + assert!(state.attachment_receipt_current(fresh["receipt"].as_str().unwrap(), &windows)); +} + +#[test] +fn attachments_receipts_belong_to_the_private_transport_backend_generation_even_when_empty() { + let directory = tempfile::tempdir().unwrap(); + let state = ClientState::initialize_at(directory.path()).unwrap(); + state.save_snapshot(json!({"version":1,"session":null})).unwrap(); + let windows = LocalWindows::default(); + state.bind_attachment_backend(1); + let first = state.attachment_inventory(&windows).unwrap(); + assert!(state.attachment_receipt_current(first["receipt"].as_str().unwrap(), &windows)); + state.bind_attachment_backend(2); + assert!(!state.attachment_receipt_current(first["receipt"].as_str().unwrap(), &windows)); + let fresh = state.attachment_inventory(&windows).unwrap(); + assert_eq!(fresh["status"], "unknown"); + assert_eq!(fresh["retainedStatus"], "complete"); + assert!(state.attachment_receipt_current(fresh["receipt"].as_str().unwrap(), &windows)); +} + +#[test] +fn attachments_union_uses_real_live_registry_including_ephemeral_and_retained_only_windows() { + let directory = tempfile::tempdir().unwrap(); + let state = ClientState::initialize_at(directory.path()).unwrap(); + state.save_snapshot(snapshot()).unwrap(); + let retained = uuid::Uuid::new_v4().to_string(); + state.add_window(retained.clone()).unwrap(); + state.save_snapshot_guarded_for(&retained, snapshot(), || true).unwrap(); + let windows = LocalWindows::default(); + windows.register(state.active_window_id().unwrap(), true).unwrap(); + let ephemeral = windows.register(uuid::Uuid::new_v4().to_string(), false).unwrap(); + assert!(windows.register("preferences".into(), false).is_err()); + assert!(windows.register("remote-foreign-backend".into(), false).is_err()); + let result = state.attachment_inventory(&windows).unwrap(); + let owners = result["owners"].as_array().unwrap(); + assert_eq!(owners.len(), 3); + assert_eq!(owners.iter().filter(|owner| owner["live"] == true && owner["retained"] == true).count(), 1); + assert_eq!(result["refs"].as_array().unwrap().len(), 2); + assert_eq!(result["status"], "unknown"); + assert!(state.attachment_receipt_current(result["receipt"].as_str().unwrap(), &windows)); + windows.remove_runtime(&ephemeral.label).unwrap(); + windows.register(ephemeral.id, false).unwrap(); + assert!(!state.attachment_receipt_current(result["receipt"].as_str().unwrap(), &windows)); +} + +#[test] +fn attachments_fence_each_waiting_writer_before_and_after_real_root_publication() { + let directory = tempfile::tempdir().unwrap(); + let hold = Arc::new(AtomicBool::new(false)); + let flag = hold.clone(); + let (persisted_tx, persisted_rx) = mpsc::channel(); + let (finish_tx, finish_rx) = mpsc::channel(); + let finish_rx = std::sync::Mutex::new(finish_rx); + let state = Arc::new(ClientState::initialize_at_with_writer(directory.path(), Arc::new(move |path, bytes, valid| { + super::super::write_atomically(path, bytes, valid)?; + if flag.swap(false, Ordering::SeqCst) { + persisted_tx.send(()).unwrap(); + finish_rx.lock().unwrap().recv().unwrap(); + } + Ok(()) + })).unwrap()); + state.save_snapshot(json!({"version":1,"session":null})).unwrap(); + let windows = LocalWindows::default(); + let first = state.attachment_inventory(&windows).unwrap(); + let (admitted_tx, admitted_rx) = mpsc::channel(); + let (resume_tx, resume_rx) = mpsc::channel(); + state.attachment_state.lock().unwrap().after_admission = Some(Box::new(move || { + admitted_tx.send(()).unwrap(); resume_rx.recv().unwrap(); + })); + hold.store(true, Ordering::SeqCst); + let writing = state.clone(); + let writer = std::thread::spawn(move || writing.save_snapshot(snapshot())); + admitted_rx.recv().unwrap(); + assert!(!state.attachment_receipt_current(first["receipt"].as_str().unwrap(), &windows)); + let empty = state.attachment_inventory(&windows).unwrap(); + assert_eq!(empty["retainedStatus"], "complete"); + assert_eq!(empty["refs"], json!([])); + assert!(!state.attachment_receipt_current(empty["receipt"].as_str().unwrap(), &windows)); + resume_tx.send(()).unwrap(); + persisted_rx.recv().unwrap(); + assert!(fs::read_to_string(directory.path().join("client-state.json")).unwrap().contains("unknown-A")); + let during_publication = state.attachment_receipt_current(empty["receipt"].as_str().unwrap(), &windows); + + let (queued_tx, queued_rx) = mpsc::channel(); + let (resume_next_tx, resume_next_rx) = mpsc::channel(); + state.attachment_state.lock().unwrap().after_admission = Some(Box::new(move || { + queued_tx.send(()).unwrap(); resume_next_rx.recv().unwrap(); + })); + let writing = state.clone(); + let next = std::thread::spawn(move || writing.save_snapshot(json!({"version":1,"session":null}))); + queued_rx.recv().unwrap(); + finish_tx.send(()).unwrap(); + assert!(writer.join().unwrap().unwrap()); + let between = state.attachment_inventory(&windows).unwrap(); + assert_eq!(between["refs"][0]["serverId"], "unknown-A"); + let while_next_waits = state.attachment_receipt_current(between["receipt"].as_str().unwrap(), &windows); + resume_next_tx.send(()).unwrap(); + assert!(next.join().unwrap().unwrap()); + let fresh = state.attachment_inventory(&windows).unwrap(); + assert_eq!(fresh["refs"], json!([])); + assert_eq!(fresh["retainedStatus"], "complete"); + assert_eq!(fresh["status"], "unknown"); + assert!(state.attachment_receipt_current(fresh["receipt"].as_str().unwrap(), &windows)); + assert!(!state.attachment_receipt_current(empty["receipt"].as_str().unwrap(), &windows)); + assert!(!state.attachment_receipt_current(between["receipt"].as_str().unwrap(), &windows)); + assert!(!during_publication, "an empty receipt survived root commit before writer return"); + assert!(!while_next_waits, "a waiting writer lost its publication fence"); +} + +#[test] +fn attachments_real_manifest_exact_limit_overflow_and_fresh_recovery() { + use sha2::{Digest, Sha256}; + let fixture = vector(); + let original_key = fixture["root"]["sessionPartition"].as_str().unwrap(); + let original = fixture["partitions"][original_key].as_str().unwrap(); + let manifest = format!("{original}{}", " ".repeat(1024 * 1024 - original.len())); + let key = format!("{:x}", Sha256::digest(manifest.as_bytes())); + let mut keys: Vec = fixture["partitionKeys"].as_array().unwrap().iter().map(|value| { + let value = value.as_str().unwrap(); if value == original_key { key.clone() } else { value.to_string() } + }).collect(); + keys.sort(); + let mut root = fixture["root"].clone(); + root["sessionPartition"] = json!(key); + root["partitionKeys"] = json!(keys); + let directory = tempfile::tempdir().unwrap(); + fs::create_dir(directory.path().join("partitions")).unwrap(); + let path = directory.path().join("partitions").join(&key); + fs::write(&path, &manifest).unwrap(); + fs::write(directory.path().join("client-state.json"), serde_json::to_vec(&json!({"version":2, + "restoreEnabled":true,"protocolVersion":1,"snapshot":root,"partitionKeys":keys})).unwrap()).unwrap(); + // The referenced workspace partition is absent; metadata reads the manifest only. + let state = ClientState::initialize_at(directory.path()).unwrap(); + let windows = LocalWindows::default(); + let first = state.attachment_inventory(&windows).unwrap(); + assert_eq!(first["retainedStatus"], "complete"); + assert_eq!(first["refs"].as_array().unwrap().len(), 1); + assert!(state.attachment_receipt_current(first["receipt"].as_str().unwrap(), &windows)); + fs::write(&path, format!("{manifest} ")).unwrap(); + let refused = state.attachment_inventory(&windows).unwrap(); + assert_eq!(refused["retainedStatus"], "unknown"); + assert!(!state.attachment_receipt_current(first["receipt"].as_str().unwrap(), &windows)); + fs::write(&path, &manifest).unwrap(); + let fresh = state.attachment_inventory(&windows).unwrap(); + assert_eq!(fresh["retainedStatus"], "complete"); + assert_eq!(fresh["status"], "unknown"); + assert!(state.attachment_receipt_current(fresh["receipt"].as_str().unwrap(), &windows)); + assert!(!state.attachment_receipt_current(refused["receipt"].as_str().unwrap(), &windows)); +} diff --git a/packages/tauri-app/src-tauri/src/client_state/partitions.rs b/packages/tauri-app/src-tauri/src/client_state/partitions.rs index 37796d2b19..ad835fa775 100644 --- a/packages/tauri-app/src-tauri/src/client_state/partitions.rs +++ b/packages/tauri-app/src-tauri/src/client_state/partitions.rs @@ -5,7 +5,7 @@ use std::collections::{HashMap, HashSet}; use std::fs; #[cfg(not(windows))] use std::fs::File; -use std::io::Write; +use std::io::{Read, Write}; use std::path::{Path, PathBuf}; pub(super) const PROTOCOL_VERSION: u64 = 1; @@ -245,15 +245,18 @@ impl PartitionStore { Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(err) => return Err(err.to_string()), } - match fs::read(path) { - Ok(bytes) if bytes.len() <= MAX_PARTITION_BYTES && hex_digest(&bytes) == key => { + let bytes = match fs::File::open(path).and_then(read_bounded_partition) { + Ok(bytes) => bytes, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(err) => return Err(err.to_string()), + }; + match bytes { + Some(bytes) if hex_digest(&bytes) == key => { String::from_utf8(bytes) .map(Some) .map_err(|err| err.to_string()) } - Ok(_) => Ok(None), - Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None), - Err(err) => Err(err.to_string()), + _ => Ok(None), } } @@ -295,6 +298,21 @@ impl PartitionStore { } } +fn read_bounded_partition(mut reader: impl Read) -> std::io::Result>> { + let mut bytes = Vec::with_capacity(MAX_PARTITION_BYTES); + let mut chunk = [0u8; 64 * 1024]; + loop { + let remaining = chunk.len().min(MAX_PARTITION_BYTES + 1 - bytes.len()); + let read = match reader.read(&mut chunk[..remaining]) { + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue, + result => result?, + }; + if read == 0 { return Ok(Some(bytes)); } + if bytes.len() + read > MAX_PARTITION_BYTES { return Ok(None); } + bytes.extend_from_slice(&chunk[..read]); + } +} + fn authority(authority_valid: &dyn Fn() -> bool) -> Result<(), String> { if authority_valid() { Ok(()) @@ -322,3 +340,7 @@ pub(super) fn sync_directory(_path: &Path) -> Result<(), String> { // Windows std::fs cannot open directories; synced files plus atomic publication are the stdlib limit. Ok(()) } + +#[cfg(test)] +#[path = "partitions_tests.rs"] +mod tests; diff --git a/packages/tauri-app/src-tauri/src/client_state/partitions_tests.rs b/packages/tauri-app/src-tauri/src/client_state/partitions_tests.rs new file mode 100644 index 0000000000..832a773d7a --- /dev/null +++ b/packages/tauri-app/src-tauri/src/client_state/partitions_tests.rs @@ -0,0 +1,102 @@ +use super::*; +use std::sync::{Arc, Mutex}; + +#[derive(Default)] +struct Observation { bytes: usize, max_read: usize, dropped: bool } + +struct ObservedFile { + file: fs::File, + observation: Arc>, + grow: Option, + fail: bool, +} + +impl Read for ObservedFile { + fn read(&mut self, bytes: &mut [u8]) -> std::io::Result { + if let Some(path) = self.grow.take() { + fs::OpenOptions::new().append(true).open(path)?.write_all(&vec![b'x'; 4 * MAX_PARTITION_BYTES])?; + } + if self.fail { return Err(std::io::Error::other("owned read failure")); } + // Real file short reads, including a UTF-8 sequence split across chunks. + let length = bytes.len().min(1001); + let read = self.file.read(&mut bytes[..length])?; + let mut observed = self.observation.lock().unwrap(); + observed.bytes += read; + observed.max_read = observed.max_read.max(bytes.len()); + Ok(read) + } +} + +impl Drop for ObservedFile { + fn drop(&mut self) { self.observation.lock().unwrap().dropped = true; } +} + +#[test] +fn bounded_partition_real_files_exact_limit_oversize_growth_errors_and_release() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("owned"); + for size in [0, MAX_PARTITION_BYTES, MAX_PARTITION_BYTES + 1, 16 * MAX_PARTITION_BYTES] { + fs::write(&path, []).unwrap(); + fs::OpenOptions::new().write(true).open(&path).unwrap().set_len(size as u64).unwrap(); + let observation = Arc::new(Mutex::new(Observation::default())); + let result = read_bounded_partition(ObservedFile { file: fs::File::open(&path).unwrap(), observation: observation.clone(), grow: None, fail: false }).unwrap(); + assert_eq!(result.as_ref().map(Vec::len), (size <= MAX_PARTITION_BYTES).then_some(size)); + let observed = observation.lock().unwrap(); + assert!(observed.bytes <= MAX_PARTITION_BYTES + 1); + assert!(observed.max_read <= 64 * 1024); + assert!(observed.dropped); + drop(observed); + fs::remove_file(&path).unwrap(); + fs::write(&path, "fresh").unwrap(); + assert_eq!(read_bounded_partition(fs::File::open(&path).unwrap()).unwrap().unwrap(), b"fresh"); + } + for fail in [false, true] { + fs::write(&path, "été").unwrap(); + assert_eq!(fs::symlink_metadata(&path).unwrap().len(), 5); + let observation = Arc::new(Mutex::new(Observation::default())); + let result = read_bounded_partition(ObservedFile { file: fs::File::open(&path).unwrap(), observation: observation.clone(), grow: (!fail).then_some(path.clone()), fail }); + if fail { assert!(result.is_err()); } else { + assert!(result.unwrap().is_none()); + assert_eq!(observation.lock().unwrap().bytes, MAX_PARTITION_BYTES + 1); + } + assert!(observation.lock().unwrap().dropped); + assert!(observation.lock().unwrap().bytes <= MAX_PARTITION_BYTES + 1); + fs::remove_file(&path).unwrap(); + fs::write(&path, "été").unwrap(); + assert_eq!(read_bounded_partition(fs::File::open(&path).unwrap()).unwrap().unwrap(), "été".as_bytes()); + } +} + +#[test] +fn verified_partition_store_preserves_hash_authority_paths_and_positive_recovery() { + let root = tempfile::tempdir().unwrap(); + let store = PartitionStore::new(root.path()); + fs::create_dir(&store.directory).unwrap(); + let content = "é".repeat(MAX_PARTITION_BYTES / 2); + let key = hex_digest(content.as_bytes()); + let path = store.directory.join(&key); + fs::write(&path, &content).unwrap(); + assert_eq!(store.load(&key, &|| true).unwrap().as_deref(), Some(content.as_str())); + assert!(store.load(&key, &|| false).is_err()); + for bytes in [b"wrong hash".to_vec(), vec![0; MAX_PARTITION_BYTES + 1], vec![0; 16 * MAX_PARTITION_BYTES]] { + fs::write(&path, bytes).unwrap(); + assert!(store.load(&key, &|| true).unwrap().is_none()); + fs::write(&path, &content).unwrap(); + assert_eq!(store.load(&key, &|| true).unwrap().as_deref(), Some(content.as_str())); + } + fs::remove_file(&path).unwrap(); + assert!(store.load(&key, &|| true).unwrap().is_none()); + fs::create_dir(&path).unwrap(); + assert!(store.load(&key, &|| true).unwrap().is_none()); + fs::remove_dir(&path).unwrap(); + let target = root.path().join("target"); + fs::write(&target, &content).unwrap(); + #[cfg(windows)] + std::os::windows::fs::symlink_file(&target, &path).unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink(&target, &path).unwrap(); + assert!(store.load(&key, &|| true).unwrap().is_none()); + fs::remove_file(&path).unwrap(); + fs::write(&path, &content).unwrap(); + assert_eq!(store.load(&key, &|| true).unwrap().as_deref(), Some(content.as_str())); +} diff --git a/packages/tauri-app/src-tauri/src/client_state/tests.rs b/packages/tauri-app/src-tauri/src/client_state/tests.rs index 3518caf37e..f8695a174f 100644 --- a/packages/tauri-app/src-tauri/src/client_state/tests.rs +++ b/packages/tauri-app/src-tauri/src/client_state/tests.rs @@ -43,6 +43,7 @@ fn preferences_restoration_survives_final_window_removal_and_clears_explicitly() let directory = tempfile::tempdir().unwrap(); let state = ClientState::initialize_at(directory.path()).unwrap(); let request = crate::preferences_window::PreferencesRequest { + server_id: None, scroll_top: Some(420), section: "providers".into(), instance_id: Some("instance-1".into()), @@ -93,6 +94,25 @@ fn preferences_restoration_survives_final_window_removal_and_clears_explicitly() bounds, maximized: true, fullscreen: false, zoom_factor: 1.25, })); } + +#[test] +fn preferences_server_identity_roundtrips_through_the_window_envelope() { + let directory = tempfile::tempdir().unwrap(); + let state = ClientState::initialize_at(directory.path()).unwrap(); + let value = json!({ "section": "providers", "serverId": "unknown-A", "instanceId": "same", + "workspacePath": "C:\\App/", "location": { "directory": "/App//" }, "scrollTop": 123 }); + let request = crate::preferences_window::validate_request(serde_json::from_value(value.clone()).unwrap()).unwrap(); + state.set_preferences(Some(request.clone())).unwrap(); + let bytes = fs::read(directory.path().join(CLIENT_STATE_FILENAME)).unwrap(); + let persisted: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(persisted["preferences"], value); + assert_eq!(parse_client_state(&bytes).preferences, Some(request)); + for server_id in [json!(null), json!(""), json!("a/b"), json!(42)] { + let mut invalid = persisted.clone(); + invalid["preferences"]["serverId"] = server_id; + assert!(parse_client_state(&serde_json::to_vec(&invalid).unwrap()).unsupported_future_envelope); + } +} use std::time::Duration; use tempfile::TempDir; use url::Url; @@ -538,6 +558,10 @@ fn electron_and_tauri_share_the_complete_envelope_across_handoffs() { Some(&electron_snapshot), ); assert_eq!(node["acquired"], true); + let preferences_a = json!({ "section": "providers", "serverId": "unknown-A", "instanceId": "same", + "workspacePath": "C:\\App/", "location": { "directory": "/App//" }, "scrollTop": 123 }); + let node = run_node_state_host(&election, &electron, &tauri, "save-preferences", Some(&preferences_a)); + assert_eq!(node["acquired"], true); let rust = ClientState::initialize_at_with_writer_and_election( &tauri, &election, @@ -548,6 +572,10 @@ fn electron_and_tauri_share_the_complete_envelope_across_handoffs() { ) .unwrap(); assert_eq!(rust.load().unwrap().snapshot, electron_snapshot); + assert_eq!(serde_json::to_value(rust.preferences()).unwrap(), preferences_a); + let mut preferences_b = preferences_a; + preferences_b["serverId"] = json!("unknown-B"); + rust.set_preferences(Some(crate::preferences_window::validate_request(serde_json::from_value(preferences_b.clone()).unwrap()).unwrap())).unwrap(); let tauri_snapshot = json!({ "savedAt": 20, "from": "tauri" }); assert!(rust.save_snapshot(tauri_snapshot.clone()).unwrap()); rust.release_locks(); @@ -556,6 +584,7 @@ fn electron_and_tauri_share_the_complete_envelope_across_handoffs() { let node = run_node_state_host(&election, &electron, &tauri, "load", None); assert_eq!(node["acquired"], true); assert_eq!(node["state"]["snapshot"], tauri_snapshot); + assert_eq!(node["preferences"], preferences_b); } #[test] fn normalizes_window_bounds_against_displays() { diff --git a/packages/tauri-app/src-tauri/src/local_windows.rs b/packages/tauri-app/src-tauri/src/local_windows.rs index df87a2d567..39271146a9 100644 --- a/packages/tauri-app/src-tauri/src/local_windows.rs +++ b/packages/tauri-app/src-tauri/src/local_windows.rs @@ -156,6 +156,7 @@ struct Registry { records: HashMap, mru: Vec, backend_target: Option, + attachment_epoch: String, } impl Registry { @@ -188,6 +189,7 @@ impl Registry { view_menu_state: None, }; self.records.insert(label.clone(), record.clone()); + self.attachment_epoch = uuid::Uuid::new_v4().to_string(); self.mark_focused(&label); Ok(record) } @@ -202,6 +204,7 @@ impl Registry { } fn remove(&mut self, label: &str) -> Option { + self.attachment_epoch = uuid::Uuid::new_v4().to_string(); self.mru.retain(|candidate| candidate != label); self.records.remove(label) } @@ -248,6 +251,16 @@ impl LocalWindows { .store(false, std::sync::atomic::Ordering::SeqCst); } + #[cfg(test)] + pub(crate) fn register(&self, id: String, persisted: bool) -> Result { + self.registry.lock().map_err(|error| error.to_string())?.add(id, persisted) + } + + pub(crate) fn attachment_membership(&self) -> Result<(String, Vec), String> { + let registry = self.registry.lock().map_err(|_| "attachment_inventory_unavailable")?; + Ok((registry.attachment_epoch.clone(), registry.records.values().map(|record| record.id.clone()).collect())) + } + pub(crate) fn records(&self) -> Vec { self.registry .lock() diff --git a/packages/tauri-app/src-tauri/src/local_windows_tests.rs b/packages/tauri-app/src-tauri/src/local_windows_tests.rs index b3b37a81d3..e75b02d4d2 100644 --- a/packages/tauri-app/src-tauri/src/local_windows_tests.rs +++ b/packages/tauri-app/src-tauri/src/local_windows_tests.rs @@ -1,5 +1,23 @@ use super::*; +#[test] +fn attachments_registry_receipt_retires_on_add_remove_and_same_id_reuse() { + let mut registry = Registry::default(); + let empty = registry.attachment_epoch.clone(); + let first = registry.add(id(1), false).unwrap(); + assert_ne!(registry.attachment_epoch, empty); + let live = registry.attachment_epoch.clone(); + registry.remove(&first.label).unwrap(); + registry.add(id(1), true).unwrap(); + assert_ne!(registry.attachment_epoch, live); + assert_ne!(registry.attachment_epoch, empty); + let reused = registry.attachment_epoch.clone(); + let hidden = registry.add_window(id(2), false, true).unwrap(); + assert_ne!(registry.attachment_epoch, reused); + assert_eq!(registry.mru_label(), Some(first.label)); + assert!(hidden.connect_only); +} + fn id(value: u8) -> String { format!("00000000-0000-4000-8000-{value:012}") } diff --git a/packages/tauri-app/src-tauri/src/main.rs b/packages/tauri-app/src-tauri/src/main.rs index fd3cc3d660..6199738ee1 100644 --- a/packages/tauri-app/src-tauri/src/main.rs +++ b/packages/tauri-app/src-tauri/src/main.rs @@ -285,9 +285,20 @@ pub(crate) fn handle_native_request( method: &str, params: Option, deadline: u64, + backend_generation: u64, ) -> Result { let state = app.state::(); + if method.starts_with("projects.attachments.") { + app.state::().bind_attachment_backend(backend_generation); + } match method { + "projects.attachments.read" => app.state::() + .attachment_inventory(&app.state::()), + "projects.attachments.current" => { + let receipt = params.as_ref().and_then(|value| value.get("receipt")).and_then(serde_json::Value::as_str); + Ok(serde_json::Value::Bool(receipt.is_some_and(|receipt| app.state::() + .attachment_receipt_current(receipt, &app.state::())))) + } "browser.probe" | "browser.execute" | "browser.page.begin" | "browser.page.send" | "browser.page.check" | "browser.page.end" => state .browser_controller diff --git a/packages/tauri-app/src-tauri/src/native_request.rs b/packages/tauri-app/src-tauri/src/native_request.rs index 76c465b012..376ced407c 100644 --- a/packages/tauri-app/src-tauri/src/native_request.rs +++ b/packages/tauri-app/src-tauri/src/native_request.rs @@ -88,4 +88,12 @@ mod tests { "CODENOMAD_NATIVE_RESPONSE:{\"v\":1,\"id\":\"r1\",\"ok\":true,\"result\":{\"available\":true}}\n" ); } + + #[test] + fn attachment_response_preserves_opaque_scoped_id_and_canonical_header() { + let id = "attachments-00000000-0000-4000-8000-000000000000"; + let request = parse(&format!("{REQUEST_PREFIX}{{\"v\":1,\"id\":\"{id}\",\"method\":\"projects.attachments.current\",\"deadline\":9999999999999}}")).unwrap(); + assert_eq!(request.id, id); + assert_eq!(response(&request.id, Ok(json!(true))), format!("{RESPONSE_PREFIX}{{\"v\":1,\"id\":\"{id}\",\"ok\":true,\"result\":true}}\n")); + } } diff --git a/packages/tauri-app/src-tauri/src/preferences_window.rs b/packages/tauri-app/src-tauri/src/preferences_window.rs index ab5a30fc86..df33df2f34 100644 --- a/packages/tauri-app/src-tauri/src/preferences_window.rs +++ b/packages/tauri-app/src-tauri/src/preferences_window.rs @@ -41,6 +41,8 @@ pub(crate) struct PreferencesLocation { #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(crate) struct PreferencesRequest { pub(crate) section: String, + #[serde(default, deserialize_with = "deserialize_server_id", skip_serializing_if = "Option::is_none")] + pub(crate) server_id: Option, #[serde(skip_serializing_if = "Option::is_none")] pub(crate) scroll_top: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -51,6 +53,20 @@ pub(crate) struct PreferencesRequest { pub(crate) location: Option, } +fn valid_server_id(value: &str) -> bool { + !value.is_empty() && value.len() <= 128 + && value.as_bytes()[0].is_ascii_alphanumeric() + && value.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') +} + +fn deserialize_server_id<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + let value = String::deserialize(deserializer)?; + if !valid_server_id(&value) { + return Err(serde::de::Error::custom("Invalid Preferences server ID")); + } + Ok(Some(value)) +} + /// Host-observed local window label that opened Preferences, never renderer-supplied. #[derive(Clone, Debug, Default, Eq, PartialEq)] struct PreferencesOpener { @@ -100,6 +116,7 @@ impl Default for PreferencesWindow { state: Mutex::new(PreferencesState { request: PreferencesRequest { section: DEFAULT_SECTION.to_string(), + server_id: None, scroll_top: None, instance_id: None, workspace_path: None, @@ -168,6 +185,9 @@ fn validate_section(section: &str) -> Result<(), String> { pub(crate) fn validate_request(request: PreferencesRequest) -> Result { validate_section(&request.section)?; + if request.server_id.as_deref().is_some_and(|value| !valid_server_id(value)) { + return Err("Invalid Preferences server ID".to_string()); + } if request.scroll_top.is_some_and(|top| top > 10_000_000) { return Err("Invalid Preferences scroll position".to_string()); } @@ -186,7 +206,7 @@ pub(crate) fn validate_request(request: PreferencesRequest) -> Result 32768 { + if location.directory.is_empty() || location.directory.len() > 32768 || location.directory.contains('\0') { return Err("Invalid Preferences directory".to_string()); } if location @@ -705,6 +725,29 @@ mod tests { use super::*; use serde_json::json; + #[test] + fn preferences_server_identity_is_strict_opaque_and_survives_reuse() { + let value = json!({ "section": "providers", "serverId": "unknown-A", "instanceId": "same", + "workspacePath": "C:\\App/", "location": { "directory": "/App//" }, "scrollTop": 123 }); + let request = validate_request(serde_json::from_value(value.clone()).unwrap()).unwrap(); + let preferences = PreferencesWindow::default(); + preferences.set_request(request.clone()); + assert_eq!(serde_json::to_value(preferences.request()).unwrap(), value); + preferences.set_request(PreferencesRequest { server_id: Some("B".into()), ..request }); + assert_eq!(preferences.request().server_id.as_deref(), Some("B")); + for server_id in [json!(null), json!(""), json!("a/b"), json!(42), json!("a".repeat(129))] { + let mut invalid = value.clone(); + invalid["serverId"] = server_id; + assert!(serde_json::from_value::(invalid).is_err()); + } + let legacy: PreferencesRequest = serde_json::from_value(json!({ "section": "general" })).unwrap(); + assert!(legacy.server_id.is_none()); + assert_eq!(serde_json::to_value(legacy).unwrap(), json!({ "section": "general" })); + let mut invalid = value; + invalid["token"] = json!("forbidden"); + assert!(serde_json::from_value::(invalid).is_err()); + } + #[test] fn validates_sections_and_builds_an_explicit_preferences_target() { assert!(validate_section("general").is_ok()); @@ -718,6 +761,7 @@ mod tests { .any(|(key, value)| key == "preferences" && value == "chat")); assert!(target_url("file:///tmp/preferences", "chat").is_err()); let request = validate_request(PreferencesRequest { + server_id: None, scroll_top: None, section: "providers".into(), instance_id: Some("workspace-1".into()), @@ -741,9 +785,18 @@ mod tests { ); assert!(validate_request(PreferencesRequest { workspace_path: Some("bad\0path".into()), - ..request + ..request.clone() }) .is_err()); + for path in [String::new(), "x".repeat(32769)] { + assert!(validate_request(PreferencesRequest { + workspace_path: Some(path), + ..request.clone() + }).is_err()); + } + let mut invalid = serde_json::to_value(&request).unwrap(); + invalid["workspacePath"] = json!(42); + assert!(serde_json::from_value::(invalid).is_err()); } #[test] diff --git a/packages/tauri-app/src-tauri/src/workspace_open.rs b/packages/tauri-app/src-tauri/src/workspace_open.rs index a08c72899e..55466ea7ab 100644 --- a/packages/tauri-app/src-tauri/src/workspace_open.rs +++ b/packages/tauri-app/src-tauri/src/workspace_open.rs @@ -22,6 +22,26 @@ struct LaunchCandidate { #[derive(Deserialize)] struct WorkspaceDescriptor { path: String, + binding: Option, +} + +#[derive(Deserialize)] +struct WorkspaceBinding { + #[serde(rename = "serverId")] + server_id: String, +} + +#[derive(serde::Serialize)] +#[serde(rename_all = "camelCase")] +enum WorkspaceOpenReason { + LocalOnly, +} + +fn local_only_error() -> String { + serde_json::json!({ + "code": "explicit_capability_unavailable", "capability": "files", + "reason": { "code": WorkspaceOpenReason::LocalOnly } + }).to_string() } #[derive(Deserialize)] @@ -64,6 +84,14 @@ fn resolve_active_workspace_folder( manager: &CliProcessManager, instance_id: &str, worktree_slug: &str, +) -> Result { + resolve_workspace_folder(instance_id, worktree_slug, |path| get_local_json(manager, path)) +} + +fn resolve_workspace_folder( + instance_id: &str, + worktree_slug: &str, + mut get_json: impl FnMut(&str) -> Result, ) -> Result { if instance_id.is_empty() || !instance_id @@ -72,13 +100,18 @@ fn resolve_active_workspace_folder( { return Err("Invalid workspace id".into()); } - let workspace: WorkspaceDescriptor = - get_local_json(manager, &format!("/api/workspaces/{instance_id}"))?; + let workspace: WorkspaceDescriptor = serde_json::from_value( + get_json(&format!("/api/workspaces/{instance_id}"))? + ).map_err(|error| error.to_string())?; + if workspace.binding.as_ref().is_some_and(|binding| binding.server_id != "local-shared") { + return Err(local_only_error()); + } if worktree_slug == "root" { return Ok(workspace.path); } - let payload: WorktreeListResponse = - get_local_json(manager, &format!("/api/workspaces/{instance_id}/worktrees"))?; + let payload: WorktreeListResponse = serde_json::from_value( + get_json(&format!("/api/workspaces/{instance_id}/worktrees"))? + ).map_err(|error| error.to_string())?; payload .worktrees .into_iter() @@ -600,6 +633,51 @@ pub async fn open_workspace_target( mod tests { use super::*; + #[test] + fn explicit_binding_refuses_before_paths_worktrees_or_launch() { + for server_id in ["loopback-profile", "remote", "missing-profile"] { + for folder in [r"C:\workspace\app", "/workspace/app", "."] { + for slug in ["root", "branch"] { + for _target in ["default", "reveal", "terminal", "editor"] { + let mut reads = 0; + let result = resolve_workspace_folder("id", slug, |_| { + reads += 1; + assert_eq!(reads, 1, "worktree reads must be refused"); + Ok(serde_json::json!({ "path": folder, "binding": { + "serverId": server_id, "directory": folder + }})) + }).and_then(|folder| { + panic!("filesystem/launch adapter must not be entered: {folder}"); + }); + let result: Result<(), String> = result; + let error: serde_json::Value = serde_json::from_str(&result.unwrap_err()).unwrap(); + assert_eq!(error["code"], "explicit_capability_unavailable"); + assert_eq!(error["reason"]["code"], "localOnly"); + assert_eq!(reads, 1); + } + } + } + } + } + + #[test] + fn folder_authority_keeps_local_and_refuses_invalid_or_stale_ids() { + for binding in [serde_json::Value::Null, serde_json::json!({"serverId": "local-shared"})] { + for slug in ["root", "branch"] { + let folder = resolve_workspace_folder("id", slug, |route| Ok( + if route.ends_with("/worktrees") { + serde_json::json!({"worktrees": [{"slug": "branch", "directory": "local/branch"}]}) + } else { serde_json::json!({"path": "local", "binding": binding}) } + )).unwrap(); + assert_eq!(folder, if slug == "root" { "local" } else { "local/branch" }); + } + } + for id in ["id%2Fother", "id/other", ""] { + assert!(resolve_workspace_folder(id, "root", |_| panic!("invalid id read")).is_err()); + } + assert!(resolve_workspace_folder("stale", "root", |_| Err("Workspace is not active".into())).is_err()); + } + #[test] fn rejects_paths_outside_the_workspace() { let workspace = tempfile::tempdir().unwrap(); diff --git a/packages/ui/src/App.tsx b/packages/ui/src/App.tsx index 47e57b5468..ac230bca06 100644 --- a/packages/ui/src/App.tsx +++ b/packages/ui/src/App.tsx @@ -26,6 +26,9 @@ import { reloadWorktrees } from "./stores/worktrees" import { useCommands } from "./lib/hooks/use-commands" import { useAppLifecycle } from "./lib/hooks/use-app-lifecycle" import { useAppSessionRestore } from "./lib/hooks/use-app-session-restore" +import { useProjectParticipation } from "./lib/hooks/use-project-participation" +import { getProjectAvailability } from "./stores/project-capability" +import { captureInstanceRequestAuthority } from "./stores/session-api" import { loadedRestorableSession } from "./stores/client-state" import { shouldShowAppHomeOverlay, shouldShowAppRestoreLoading } from "./stores/app-session-restore-gate" import { getLogger } from "./lib/logger" @@ -131,6 +134,7 @@ async function withForegroundRefreshTimeout( const App: Component = () => { onMount(() => onCleanup(startNotificationIconBadge())) useAppSessionRestore() + useProjectParticipation() const { t } = useI18n() const { preferences, @@ -264,10 +268,10 @@ const App: Component = () => { } }, 30_000) const openRequestedPreview = async (sessionID: string, url: string, requestID: string) => { - const findOwners = () => [...instances().values()].filter((instance) => getSessions(instance.id).some((session) => session.id === sessionID)) + const findOwners = () => [...instances().values()].filter((instance) => getProjectAvailability(instance.id, "automation").allowed && getSessions(instance.id).some((session) => session.id === sessionID)) let owners = findOwners() if (owners.length === 0) { - await Promise.all([...instances().values()].filter((instance) => instance.client).map((instance) => fetchSessions(instance.id, { reset: true }).catch(() => undefined))) + await Promise.all([...instances().values()].filter((instance) => instance.client && getProjectAvailability(instance.id, "automation").allowed).map((instance) => fetchSessions(instance.id, { reset: true }).catch(() => undefined))) owners = findOwners() } const activeTab = activeAppTab() @@ -283,11 +287,13 @@ const App: Component = () => { }) return } - if (!await claimNativeBrowserOpen(requestID)) return + const current = captureInstanceRequestAuthority(owner.id) + if (!current() || !getProjectAvailability(owner.id, "automation").allowed || !await claimNativeBrowserOpen(requestID)) return try { const instance = owner + if (!current() || !getProjectAvailability(instance.id, "automation").allowed) { await releaseNativeBrowserOpen(requestID); return } await openSessionPreview(sessionID, url, instance.folder) - if (disposed) { + if (disposed || !current() || !getProjectAvailability(instance.id, "automation").allowed) { await releaseNativeBrowserOpen(requestID) return } @@ -459,19 +465,22 @@ const App: Component = () => { return recent?.projectName?.trim() || getPathBasename(folderPath) } - async function handleSelectFolder(folderPath: string): Promise { + async function handleSelectFolder(folderPath: string, serverId?: string): Promise { if (!folderPath) { return false } const selectedBinary = serverSettings().opencodeBinary || "opencode2" - const projectName = getProjectNameForFolder(folderPath) + // prototype-1236: a server folder is not a local recent folder. + const projectName = serverId ? getPathBasename(folderPath) : getProjectNameForFolder(folderPath) clearLaunchError() setIsSelectingFolder(true) try { - const result = await createInstance(folderPath, projectName) - recordWorkspaceLaunch(instances().get(result.instanceId)?.folder ?? folderPath, folderPath) + const result = await createInstance(folderPath, projectName, serverId ? { serverId } : undefined) + // prototype-1236 (R11): a server folder joins that server's recent folders only. + if (serverId) recordWorkspaceLaunch(folderPath, undefined, serverId) + else recordWorkspaceLaunch(instances().get(result.instanceId)?.folder ?? folderPath, folderPath) if (result.reused) { selectInstanceTab(result.instanceId) setShowFolderSelection(false) @@ -495,7 +504,7 @@ const App: Component = () => { t("opencodeBinarySelector.validation.v2Required"), ) const missingBinary = isMissingBinaryMessage(message) - if (missingBinary || message.includes("opencode_update_required")) { + if (!serverId && (missingBinary || message.includes("opencode_update_required"))) { openOpenCodeSetup(() => handleSelectFolder(folderPath)) return false } @@ -538,7 +547,10 @@ const App: Component = () => { function handleSelectExistingInstance(instanceId: string, recentPath: string) { const instance = instances().get(instanceId) if (!instance) return - recordWorkspaceLaunch(instance.folder, recentPath) + // prototype-1236: a server project stays in that server's recent folders. + const serverId = instance.binding?.serverId + if (serverId && serverId !== "local-shared") recordWorkspaceLaunch(instance.folder, undefined, serverId) + else recordWorkspaceLaunch(instance.folder, recentPath) selectInstanceTab(instanceId) setShowFolderSelection(false) log.info("Selected existing instance", { instanceId, folderPath: instance.folder }) @@ -883,7 +895,7 @@ const App: Component = () => { anchor={launcherAnchor()} isLoading={isSelectingFolder()} onOpenChange={setLauncherOpen} - onSelectFolder={(path) => void handleSelectFolder(path)} + onSelectFolder={(path, serverId) => void handleSelectFolder(path, serverId)} onSelectExistingInstance={handleSelectExistingInstance} onNewTemporaryInstance={() => void handleNewTemporaryInstance()} /> diff --git a/packages/ui/src/components/command-palette.tsx b/packages/ui/src/components/command-palette.tsx index 1642092585..99788f2654 100644 --- a/packages/ui/src/components/command-palette.tsx +++ b/packages/ui/src/components/command-palette.tsx @@ -49,7 +49,7 @@ const CommandPalette: Component = (props) => { type ProcessedCommands = { groups: CommandGroup[]; ordered: Command[] } const processedCommands = createMemo(() => { - const source = props.commands ?? [] + const source = (props.commands ?? []).filter(command => !command.hidden || !resolveResolvable(command.hidden)) const q = query().trim().toLowerCase() const filtered = q @@ -262,13 +262,13 @@ const CommandPalette: Component = (props) => { {(command, localIndex) => { const commandIndex = group.startIndex + localIndex() - const disabled = isCommandDisabled(command) + const disabled = () => isCommandDisabled(command) return ( @@ -784,6 +797,13 @@ const FolderSelectionView: Component = (props) => { + {/* prototype-1236 (R27): remote OpenCode servers and their folders, inline. */} + handleFolderSelect(path, serverId)} + /> + - diff --git a/packages/ui/src/components/git-diff-view.tsx b/packages/ui/src/components/git-diff-view.tsx index b5ef2077bc..7f7463a627 100644 --- a/packages/ui/src/components/git-diff-view.tsx +++ b/packages/ui/src/components/git-diff-view.tsx @@ -14,6 +14,7 @@ import { writeClientLayoutValue } from "../stores/client-state" import { readStoredEnum, RIGHT_PANEL_CHANGES_DIFF_VIEW_MODE_KEY, RIGHT_PANEL_CHANGES_DIFF_CONTEXT_MODE_KEY, RIGHT_PANEL_CHANGES_DIFF_WORD_WRAP_KEY } from "./instance/shell/storage" import { preferences } from "../stores/preferences" import { classifyHiddenDiffChange } from "./file-viewer/diff-whitespace" +import { remoteReadErrorText } from "../lib/remote-read-error" const MonacoDiffViewer = lazy(() => import("./file-viewer/monaco-diff-viewer").then(module => ({ default: module.MonacoDiffViewer }))) @@ -59,7 +60,7 @@ export function GitDiffView(props: { instanceId: string; target: FilePreviewTarg if (result.isBinary && !result.image) { setContent(null); setError(t("instanceShell.gitChanges.binaryViewer")) } else setContent(result) } catch (cause) { - if (!request.signal.aborted) setError(cause instanceof Error ? cause.message : String(cause)) + if (!request.signal.aborted) setError(remoteReadErrorText(cause instanceof Error ? cause.message : String(cause), t)) } finally { if (controller === request) { setLoading(false) diff --git a/packages/ui/src/components/history-message-preview.tsx b/packages/ui/src/components/history-message-preview.tsx index 94814bb1a2..fc46b80ac0 100644 --- a/packages/ui/src/components/history-message-preview.tsx +++ b/packages/ui/src/components/history-message-preview.tsx @@ -7,12 +7,14 @@ import { getOpenCodeInstanceGeneration, getOpenCodeMutationRevision } from "../s import { HistorySearchExcerpt, HistoryWorktreeBadge } from "./history-search-results" import type { SessionSearchMatch } from "../lib/session-search" import { rankedSearchTerms } from "../lib/ranked-search" +import { isExplicitHistory, requireHistoryEnrichment } from "../stores/session-history-capability" // An explicit result click reads only that native message. Keep it outside the // transcript store so opening historical results cannot displace its window. export default function HistoryMessagePreview(props: { instanceId: string; sessionId: string; messageId: string; highlight?: { query: string; match: SessionSearchMatch } }) { const { t, locale } = useI18n() + const explicit = createMemo(() => isExplicitHistory(props.instanceId)) const [title, setTitle] = createSignal("") const [directory, setDirectory] = createSignal() const [created, setCreated] = createSignal() @@ -26,6 +28,7 @@ export default function HistoryMessagePreview(props: { instanceId: string; sessi onCleanup(() => { target += 1 }) createEffect(() => { const instanceId = props.instanceId, sessionID = props.sessionId, messageID = props.messageId + if (explicit()) { setPending(false); return } const generation = getOpenCodeInstanceGeneration(instanceId) const revision = getOpenCodeMutationRevision(instanceId, sessionID) const controller = new AbortController() @@ -58,6 +61,7 @@ export default function HistoryMessagePreview(props: { instanceId: string; sessi onCleanup(() => controller.abort()) }) async function open() { + requireHistoryEnrichment(props.instanceId) const opened = target const current = () => opened === target setOpening(true) @@ -68,6 +72,7 @@ export default function HistoryMessagePreview(props: { instanceId: string; sessi setOpenFailed(!result) } return
+
{title()} @@ -81,5 +86,6 @@ export default function HistoryMessagePreview(props: { instanceId: string; sessi {t("messageSection.search.failed")} {t("history.openFailed")} {text =>
}
+ }>{t("history.explicit.enrichmentUnavailable")}
} diff --git a/packages/ui/src/components/instance-service-status.tsx b/packages/ui/src/components/instance-service-status.tsx index d08c82faad..e8122119c2 100644 --- a/packages/ui/src/components/instance-service-status.tsx +++ b/packages/ui/src/components/instance-service-status.tsx @@ -6,6 +6,8 @@ import { useI18n } from "../lib/i18n" import { getLogger } from "../lib/logger" import { PluginActivationControls } from "./plugin-activation-controls" import { createIntegrationContext } from "./integration-context" +import { getProjectAvailability } from "../stores/project-capability" +import { captureInstanceRequestAuthority } from "../stores/session-api" const log = getLogger("session") @@ -79,6 +81,8 @@ const InstanceServiceStatus: Component = (props) => } const toggleMcpServer = async (serverName: string, shouldEnable: boolean) => { + if (!getProjectAvailability(instance().id, "plugins").allowed) return + const current = captureInstanceRequestAuthority(instance().id) const client = instance().client if (!client?.mcp) return const action: "connect" | "disconnect" = shouldEnable ? "connect" : "disconnect" @@ -93,7 +97,7 @@ const InstanceServiceStatus: Component = (props) => } else { await client.mcp.disconnect({ server: serverName, location }) } - await refreshMetadata() + if (current() && getProjectAvailability(instance().id, "plugins").allowed) await refreshMetadata() } catch (error) { log.error("Failed to toggle MCP server", { serverName, action, error }) } finally { @@ -152,17 +156,18 @@ const InstanceServiceStatus: Component = (props) =>
- { if (!getProjectAvailability(instance().id, "plugins").allowed) event.preventDefault() }} onChange={(_, checked) => { if (switchDisabled()) return void toggleMcpServer(server.name, Boolean(checked)) }} - /> + />
diff --git a/packages/ui/src/components/instance-tab.tsx b/packages/ui/src/components/instance-tab.tsx index 4c9909afd3..afc313e08d 100644 --- a/packages/ui/src/components/instance-tab.tsx +++ b/packages/ui/src/components/instance-tab.tsx @@ -2,7 +2,7 @@ import { ContextMenu } from "@kobalte/core/context-menu" import { Component, Show, createMemo, createSignal, onCleanup } from "solid-js" import type { Instance } from "../types/instance" import { getInstanceIdleFadeClass, getInstanceSessionIndicatorStatus } from "../stores/session-status" -import { FolderCheck, FolderOpen, Hourglass, Pencil, ShieldAlert, X } from "lucide-solid" +import { FolderCheck, FolderOpen, Hourglass, Pencil, Server, ShieldAlert, X } from "lucide-solid" import { useI18n } from "../lib/i18n" import { useConfig } from "../stores/preferences" import { keepTemporaryInstance } from "../stores/temporary-instances" @@ -80,7 +80,12 @@ const InstanceTab: Component = (props) => { role="tab" aria-selected={props.active} > - }> + }> + + + }> diff --git a/packages/ui/src/components/instance-tabs.tsx b/packages/ui/src/components/instance-tabs.tsx index c6f8268f02..dad6beb4f1 100644 --- a/packages/ui/src/components/instance-tabs.tsx +++ b/packages/ui/src/components/instance-tabs.tsx @@ -20,6 +20,7 @@ import { withHotkey } from "../lib/hotkeys" import { createLongPressHandlers } from "../lib/long-press" import { useI18n } from "../lib/i18n" import type { AppTabRecord } from "../stores/app-tabs" +import { LOCAL_SERVER_ID } from "../lib/project-identity" interface InstanceTabsProps { tabs: AppTabRecord[] @@ -38,7 +39,7 @@ interface SortableAppTabProps { activeTabId: string | null onSelect: (tabId: string) => void onClose: (tabId: string) => void - onRename: (folder: string, label: string) => void + onRename: (target: { directory: string; serverId: string }, label: string) => void } const AppTabContent: Component = (props) => { @@ -51,7 +52,9 @@ const AppTabContent: Component = (props) => { active={props.tab.id === props.activeTabId} onSelect={() => props.onSelect(props.tab.id)} onClose={() => props.onClose(props.tab.id)} - onRename={(label) => props.tab.kind === "instance" && props.onRename(props.tab.instance.folder, label)} + onRename={(label) => props.tab.kind === "instance" && props.onRename({ + directory: props.tab.instance.folder, serverId: props.tab.instance.binding?.serverId ?? LOCAL_SERVER_ID, + }, label)} /> ) : (
= (props) => { }) }) - // Renaming a tab renames its project folder, like the home page: every tab of - // that folder and its recent-folder entry share one name. - const [renameTarget, setRenameTarget] = createSignal<{ folder: string; label: string } | null>(null) + // Capture the initiating tab's binding: selection may change while the dialog is open. + const [renameTarget, setRenameTarget] = createSignal<{ directory: string; serverId: string; label: string } | null>(null) const [isRenaming, setIsRenaming] = createSignal(false) - const openRename = (folder: string, label: string) => setRenameTarget({ folder, label }) + const openRename = (target: { directory: string; serverId: string }, label: string) => setRenameTarget({ ...target, label }) const submitRename = async (name: string) => { const target = renameTarget() if (!target) return setIsRenaming(true) try { - await renameProject(target.folder, name) + await renameProject(target.directory, name, target.serverId) setRenameTarget(null) } finally { setIsRenaming(false) diff --git a/packages/ui/src/components/instance/instance-shell2.tsx b/packages/ui/src/components/instance/instance-shell2.tsx index f1f53d22d0..179e8ec630 100644 --- a/packages/ui/src/components/instance/instance-shell2.tsx +++ b/packages/ui/src/components/instance/instance-shell2.tsx @@ -44,6 +44,7 @@ import { getInterruptionQueue } from "../../stores/interruption-scope" import SessionSidebar from "./shell/SessionSidebar" import { useSessionSidebarRequests } from "./shell/useSessionSidebarRequests" import RightPanel from "./shell/right-panel/RightPanel" +import { getProjectAvailability } from "../../stores/project-capability" import { registerViewMenuPanels } from "../../lib/native/view-menu" import { useDrawerChrome } from "./shell/useDrawerChrome" import { useFilePreviewLifetime } from "./shell/file-preview-lifetime" @@ -90,6 +91,9 @@ import { readClientLayoutValue, writeClientLayoutValue } from "../../stores/clie import { runtimeEnv } from "../../lib/runtime-env" import { getServerMeta, previewsUnavailable } from "../../lib/server-meta" import { useInterruptionViewport } from "./shell/useInterruptionViewport" +import { captureInstanceRequestAuthority } from "../../stores/session-api" +import { isSessionActionInterrupted, sessionActionSuperseded } from "../../stores/session-action-queue" +import { getOpencodeErrorMessage } from "../../lib/opencode-api" const log = getLogger("session") const NO_SESSION_DRAFT_SESSION_ID = "__no_session_draft__" @@ -123,6 +127,8 @@ interface InstanceShellProps { } const InstanceShell2: Component = (props) => { + let disposed = false + onCleanup(() => { disposed = true }) const { t, locale } = useI18n() const { preferences } = useConfig() const isRTL = () => locale() === "he" @@ -149,7 +155,8 @@ const InstanceShell2: Component = (props) => { const [now, setNow] = createSignal(Date.now()) const [sessionPromptApis, setSessionPromptApis] = createSignal>({}) - const pendingFirstPromptText = new Map() + const firstPromptAttempts = new Map boolean; recover?: () => void }>() + onCleanup(() => firstPromptAttempts.clear()) const [draftAgent, setDraftAgent] = createSignal("") const [draftModel, setDraftModel] = createSignal({ providerId: "", modelId: "" }) const [draftModelManuallySelected, setDraftModelManuallySelected] = createSignal(false) @@ -451,21 +458,26 @@ const InstanceShell2: Component = (props) => { ...current, [sessionId]: api, })) - const text = api ? pendingFirstPromptText.get(sessionId) : undefined - if (api && text !== undefined) { - pendingFirstPromptText.delete(sessionId) - api.setPromptText(text, { focus: true }) + const attempt = firstPromptAttempts.get(sessionId) + if (api && attempt && !attempt.api) { + attempt.api = api + attempt.unchanged = api.captureDraft() + attempt.recover?.() } } async function handleOpenPreview() { + if (!getProjectAvailability(props.instance.id, "automation").allowed) return + const current = captureInstanceRequestAuthority(props.instance.id) const sessionId = activeSessionIdForInstance() if (!sessionId || sessionId === "info") return try { const restored = await restoreSessionPreview(sessionId, props.instance.folder) + if (!current() || !getProjectAvailability(props.instance.id, "automation").allowed) return if (restored) showSessionPreview(restored.storageKey) else await openSessionPreview(sessionId, DEFAULT_PREVIEW_URL, props.instance.folder) } catch (error) { + if (!current() || !getProjectAvailability(props.instance.id, "automation").allowed) return showAlertDialog(t("sessionPreview.open.title"), { title: t("sessionPreview.open.title"), detail: error instanceof Error ? error.message : String(error), @@ -475,6 +487,7 @@ const InstanceShell2: Component = (props) => { } function handlePreviewButtonClick() { + if (!getProjectAvailability(props.instance.id, "automation").allowed) return const sessionId = activeSessionIdForInstance() if (!sessionId || sessionId === "info") return @@ -575,6 +588,7 @@ const InstanceShell2: Component = (props) => { } const renderYoloModePill = () => { + if (!getProjectAvailability(props.instance.id, "yolo").allowed) return null if (!yoloModeEnabled()) return null return ( = (props) => { ) const renderPreviewToggleButton = () => ( - + = (props) => { } const handleChatSearchClick = () => { + if (!getProjectAvailability(props.instance.id, "historyEnrichment").allowed) return const id = activeSessionIdForInstance() if (id && id !== "info") setSessionSearchOpen(props.instance.id, id, !isSessionSearchOpen(props.instance.id, id)) } @@ -658,7 +673,7 @@ const InstanceShell2: Component = (props) => { onSelect: handleCommandPaletteClick, }] if (showingInfoView()) return items - items.push({ + if (getProjectAvailability(props.instance.id, "historyEnrichment").allowed) items.push({ key: "search", checked: searchOpen(), label: t("instanceShell.chatSearch.openAriaLabel"), @@ -666,7 +681,7 @@ const InstanceShell2: Component = (props) => { icon: - = (props) => { size="small" > + {renderPreviewToggleButton()} {renderFullscreenButton()} = (props) => { } >
- + />
diff --git a/packages/ui/src/components/instance/shell/SessionSidebar.tsx b/packages/ui/src/components/instance/shell/SessionSidebar.tsx index 51ae73d3a2..33faace2d4 100644 --- a/packages/ui/src/components/instance/shell/SessionSidebar.tsx +++ b/packages/ui/src/components/instance/shell/SessionSidebar.tsx @@ -10,6 +10,7 @@ import { getLogger } from "../../../lib/logger" import { withHotkey } from "../../../lib/hotkeys" import { shouldMountSessionList } from "../../session-list-visibility" import { isCreatingSession } from "../../../stores/session-api" +import { getProjectAvailability } from "../../../stores/project-capability" const log = getLogger("session") @@ -77,17 +78,17 @@ const SessionSidebar: Component = (props) => { > - props.onSelectSession("info")} + onClick={() => { if (getProjectAvailability(props.instanceId, "serviceManagement").allowed) props.onSelectSession("info") }} > +
= (props) => { const extensions = usePanelExtensions(() => props.instanceId, props.isActive) const savedTab = readStoredRightPanelTab("files") const [rightPanelTab, setRightPanelTab] = createSignal(savedTab === "git-changes" ? "files" : savedTab) + let admissionFallback: RightPanelTab | undefined const defaultStatusSectionIds = CORE_STATUS_SECTION_ITEMS.map((section) => section.id) const [rightPanelExpandedItems, setRightPanelExpandedItems] = createSignal(defaultStatusSectionIds) const [rightPanelCustomizationOpen, setRightPanelCustomizationOpen] = createSignal(false) @@ -121,9 +124,18 @@ const RightPanel: Component = (props) => { const tabGroupId = `right-panel-${createUniqueId()}` const tabId = (id: string) => `${tabGroupId}-tab-${id}` const tabPanelId = (id: string) => `${tabGroupId}-panel-${id}` + let contentRoot: HTMLDivElement | undefined, lastFocused: HTMLElement | undefined + onMount(() => { + const focus = (event: FocusEvent) => { lastFocused = contentRoot?.contains(event.target as Node) ? event.target as HTMLElement : undefined } + const pointer = (event: PointerEvent) => { if (!contentRoot?.contains(event.target as Node)) lastFocused = undefined } + document.addEventListener("focusin", focus, true) + document.addEventListener("pointerdown", pointer, true) + onCleanup(() => { document.removeEventListener("focusin", focus, true); document.removeEventListener("pointerdown", pointer, true) }) + }) createEffect(() => { - writeClientLayoutValue(RIGHT_PANEL_TAB_STORAGE_KEY, rightPanelTab()) + const tab = rightPanelTab() + if (tab !== admissionFallback) writeClientLayoutValue(RIGHT_PANEL_TAB_STORAGE_KEY, tab) }) const handleAccordionChange = (values: string[]) => { @@ -171,7 +183,7 @@ const RightPanel: Component = (props) => { if (!target) return event.preventDefault() - setRightPanelTab(target.id) + selectRightPanelTab(target.id) queueMicrotask(() => document.getElementById(tabId(target.id))?.focus()) } @@ -227,19 +239,25 @@ const RightPanel: Component = (props) => { const extraStatusContent = createMemo(() => rightPanelModules().flatMap(module => module.renderStatusExtras ? [module.renderStatusExtras] : []), [], { equals: (left, right) => left.length === right.length && left.every((item, index) => item === right[index]) }) const allRightPanelTabs = createMemo(() => collectRightPanelItems(rightPanelModules(), "tabs")) + const tabAvailable = (tab: RightPanelTabModule) => { + if (tab.id === "files") return getProjectAvailability(props.instanceId, "files").allowed + if (tab.id === "missions") return getProjectAvailability(props.instanceId, "missions").allowed + const entry = extensionForTab(tab.id), feature = entry && extensionProjectFeature(entry) + return !feature || getProjectAvailability(props.instanceId, feature).allowed + } const visibleRightPanelTabs = createMemo(() => applyRightPanelItemCustomization( - allRightPanelTabs().filter(tab => extensionForTab(tab.id)?.enabled ?? true), + allRightPanelTabs().filter(tab => tabAvailable(tab) && (extensionForTab(tab.id)?.enabled ?? true)), rightPanelCustomization().tabOrder, // Addons have one profile-wide activation, not a second per-window visibility gate. rightPanelCustomization().hiddenTabIds.filter(id => !id.startsWith("extension:")), ), ) - const orderedRightPanelTabs = createMemo(() => applyRightPanelItemCustomization(allRightPanelTabs(), rightPanelCustomization().tabOrder, [])) + const orderedRightPanelTabs = createMemo(() => applyRightPanelItemCustomization(allRightPanelTabs().filter(tab => extensionForTab(tab.id) || tabAvailable(tab)), rightPanelCustomization().tabOrder, [])) // Same sections, same array: Status keeps its rows mounted across unrelated module updates. const extraStatusSections = createMemo(() => collectRightPanelItems(rightPanelModules(), "statusSections"), [], { equals: (left, right) => left.length === right.length && left.every((item, index) => item === right[index]) }) - const allStatusSections = createMemo(() => [...CORE_STATUS_SECTION_ITEMS, ...extraStatusSections()]) + const allStatusSections = createMemo(() => [...CORE_STATUS_SECTION_ITEMS, ...extraStatusSections()].filter(section => statusSectionAvailable(props.instanceId, section.id))) const orderedStatusSections = createMemo(() => applyRightPanelItemCustomization(allStatusSections(), rightPanelCustomization().statusSectionOrder, [])) const visibleStatusSections = createMemo(() => applyRightPanelItemCustomization( @@ -249,16 +267,34 @@ const RightPanel: Component = (props) => { ), ) const activeRightPanelTab = createMemo(() => visibleRightPanelTabs().find((tab) => tab.id === rightPanelTab()) ?? visibleRightPanelTabs()[0]) + function selectRightPanelTab(id: RightPanelTab) { + const tab = allRightPanelTabs().find(tab => tab.id === id) + if (!tab || !tabAvailable(tab)) return + const unchanged = rightPanelTab() === id + admissionFallback = undefined + setRightPanelTab(id) + if (unchanged) writeClientLayoutValue(RIGHT_PANEL_TAB_STORAGE_KEY, id) + } createEffect(() => { const active = activeRightPanelTab() + // Admission may remove a focused reader without changing the selected tab. + getOpenCodeInstanceGeneration(props.instanceId) + getProjectAvailability(props.instanceId, "executionSettings") if (active && active.id !== rightPanelTab()) { + const previous = allRightPanelTabs().find(tab => tab.id === rightPanelTab()) + admissionFallback = previous && !tabAvailable(previous) ? active.id : undefined setRightPanelTab(active.id) } + const focused = lastFocused + queueMicrotask(() => { + if (active && props.isActive() && contentRoot?.isConnected && focused && !focused.isConnected + && document.hasFocus() && document.activeElement === document.body) document.getElementById(tabId(active.id))?.focus({ preventScroll: true }) + }) }) return ( -
+
{ contentRoot = element; props.setContentEl(element) }}>
@@ -290,7 +326,7 @@ const RightPanel: Component = (props) => { label={tab.label ?? props.t(tab.labelKey)} dragTitle={props.t("instanceShell.rightPanel.customize.dragToReorder")} tabIndex={rightPanelTab() === tab.id ? 0 : -1} - onSelect={() => setRightPanelTab(tab.id)} + onSelect={() => selectRightPanelTab(tab.id)} onKeyDown={(event) => handleTabKeyDown(event, tab.id)} /> )} diff --git a/packages/ui/src/components/instance/shell/right-panel/components/WorkspaceTree.tsx b/packages/ui/src/components/instance/shell/right-panel/components/WorkspaceTree.tsx index a651e08b5d..d8d9fd590f 100644 --- a/packages/ui/src/components/instance/shell/right-panel/components/WorkspaceTree.tsx +++ b/packages/ui/src/components/instance/shell/right-panel/components/WorkspaceTree.tsx @@ -1,11 +1,13 @@ -import { For, Show, createMemo } from "solid-js" +import { For, Show, createMemo, onCleanup } from "solid-js" import { ChevronDown, ChevronRight, Copy, ExternalLink, Eye, Folder, FolderOpen, FileCode, FileText, Image, File, RefreshCw, TerminalSquare } from "lucide-solid" import type { useWorkspaceTree } from "../useWorkspaceTree" import type { ActionOverflowMenuItem } from "../../../../action-overflow-menu" import FileRowActions from "../FileRowActions" import { copyToClipboard } from "../../../../../lib/clipboard" import { showToastNotification } from "../../../../../lib/notifications" -import { canOpenWorkspacePaths, openWorkspacePath } from "../../../../../lib/workspace-open" +import { canOpenWorkspacePaths, openWorkspacePath, WorkspacePathUnavailableError } from "../../../../../lib/workspace-open" +import { getProjectAvailability } from "../../../../../stores/project-capability" +import { captureInstanceRequestAuthority } from "../../../../../stores/session-api" export function WorkspaceTree(props: { tree: ReturnType @@ -17,6 +19,10 @@ export function WorkspaceTree(props: { previewPath?: string onOpen: (path: string) => void }) { + const current = captureInstanceRequestAuthority(props.instanceId) + let disposed = false + onCleanup(() => { disposed = true }) + const admitted = () => !disposed && current() && getProjectAvailability(props.instanceId, "files").allowed const icon = (name: string) => /\.(png|jpe?g|gif|webp|svg|ico|bmp|avif)$/i.test(name) ? Image : /\.(md|mdx|txt|rst)$/i.test(name) ? FileText : /\.(tsx?|jsx?|json|ya?ml|css|html|py|rs|sh)$/i.test(name) ? FileCode : File @@ -50,7 +56,9 @@ export function WorkspaceTree(props: { } const handleCopyPath = async (path: string) => { + if (!admitted()) return const ok = await copyToClipboard(path) + if (!admitted()) return showToastNotification({ category: "copy", message: ok ? props.t("instanceShell.filesShell.toast.copyPathSuccess") : props.t("instanceShell.filesShell.toast.copyPathError"), variant: ok ? "success" : "error", @@ -58,9 +66,11 @@ export function WorkspaceTree(props: { } const handleNativeOpen = async (target: "default" | "reveal" | "terminal", path: string) => { + if (!admitted() || !canOpenWorkspacePaths(props.instanceId)) return try { await openWorkspacePath({ target, instanceId: props.instanceId, worktreeSlug: props.worktreeSlug, path }) } catch (error) { + if (!admitted() || error instanceof WorkspacePathUnavailableError) return showToastNotification({ category: "files", message: props.t("instanceShell.filesShell.toast.openError", { message: error instanceof Error ? error.message : String(error), @@ -77,7 +87,7 @@ export function WorkspaceTree(props: { get icon() { return }, disabled: !props.canOpen, checked: props.previewPath === row.path, onSelect: () => props.onOpen(row.path), }) - if (canOpenWorkspacePaths()) { + if (canOpenWorkspacePaths(props.instanceId)) { if (row.type === "directory") { const isMacApp = isMacDesktop && row.path.toLowerCase().endsWith(".app") items.push( diff --git a/packages/ui/src/components/instance/shell/right-panel/core-runtime.tsx b/packages/ui/src/components/instance/shell/right-panel/core-runtime.tsx index 620ef3e596..2b181ad513 100644 --- a/packages/ui/src/components/instance/shell/right-panel/core-runtime.tsx +++ b/packages/ui/src/components/instance/shell/right-panel/core-runtime.tsx @@ -1,4 +1,4 @@ -import { createEffect, createMemo, createSignal, lazy, on, type Accessor, type JSX } from "solid-js" +import { createEffect, createMemo, createSignal, lazy, on, onCleanup, untrack, type Accessor, type JSX } from "solid-js" import type { Instance } from "../../../../types/instance" import type { Session } from "../../../../types/session" import type { PromptInputApi } from "../../../prompt-input/types" @@ -16,6 +16,11 @@ import { useGitInit } from "./useGitInit" import { FILES_PANEL_MODE_KEY, type FilesPanelMode } from "./files-panel-state" import { readStoredEnum } from "../storage" import { writeClientLayoutValue } from "../../../../stores/client-state" +import { ProjectCapabilityBoundary } from "../../../project-capability-gate" +import { captureInstanceRequestAuthority } from "../../../../stores/session-api" +import { createProjectAdmission, getProjectAvailability } from "../../../../stores/project-capability" +import { getRootClient } from "../../../../stores/opencode-client" +import { filesystemInvalidationVersion } from "../../../../lib/filesystem-events" const LazyFilesPanel = lazy(() => import("./tabs/FilesPanel")) const LazyStatusTab = lazy(() => import("./tabs/StatusTab")) @@ -41,6 +46,24 @@ interface CoreRightPanelRuntimeOptions { } export function createCoreRightPanelRuntime(options: CoreRightPanelRuntimeOptions) { + const admission = createProjectAdmission(() => options.instanceId, () => "files") + const files = createMemo(() => admission() ? untrack(() => createFilesRuntime(options)) : undefined) + return createCoreRightPanelModule({ + renderFilesTab: () => + {files()?.()} + , + renderStatusTab: () => options.isActive() && options.rightPanelTab() === "status"} + expandedItems={options.expandedItems} onExpandedItemsChange={options.onExpandedItemsChange} + customization={options.customization} onCustomizationChange={options.onCustomizationChange} extraSections={options.extraStatusSections()} + extraContent={options.extraStatusContent?.()} />, + }) +} + +function createFilesRuntime(options: CoreRightPanelRuntimeOptions) { + let disposed = false + const sourceCurrent = captureInstanceRequestAuthority(options.instanceId) + onCleanup(() => { disposed = true }) const [mode, setMode] = createSignal(readStoredEnum(FILES_PANEL_MODE_KEY, ["workspace", "changes", "history"] as const) ?? "workspace") createEffect(() => writeClientLayoutValue(FILES_PANEL_MODE_KEY, mode())) const [browsedWorktree, setBrowsedWorktree] = createSignal(null) @@ -54,37 +77,44 @@ export function createCoreRightPanelRuntime(options: CoreRightPanelRuntimeOption createEffect(() => { if (browsedWorktree() && worktrees().length && !worktree()) setBrowsedWorktree(null) }) - const active = () => options.isActive() && options.rightPanelTab() === "files" + const active = () => !disposed && sourceCurrent() && getProjectAvailability(options.instanceId, "files").allowed && options.isActive() && options.rightPanelTab() === "files" // A known non-repository keeps Changes/Commits reachable for their Initialize // Git empty state, without Git reads. Unknown status (including no-Git // directory-only mode) retains the existing behavior. const gitAvailable = () => getGitRepoStatus(options.instanceId) !== false const directory = () => worktree()?.directory ?? options.instance.folder + // prototype-1236: an explicit server's project reads its working changes only (no history, index or commit). + const readOnly = () => !getProjectAvailability(options.instanceId, "hostGit").allowed + const shownMode = (): FilesPanelMode => readOnly() && mode() === "history" ? "changes" : mode() const gitInit = useGitInit({ instanceId: options.instanceId, directory, t: options.t }) - const tree = useWorkspaceTree(options.instanceId, directory, () => active() && mode() === "workspace") - const history = useGitHistory(options.instanceId, slug, () => active() && gitAvailable() && mode() === "history") + const tree = useWorkspaceTree(options.instanceId, directory, () => active() && shownMode() === "workspace") + const history = useGitHistory(options.instanceId, slug, () => active() && !readOnly() && gitAvailable() && shownMode() === "history") const git = useGitChanges({ - ...options, isActive: () => active() && gitAvailable() && mode() === "changes", rightPanelTab: () => "git-changes", + ...options, isActive: () => active() && gitAvailable() && shownMode() === "changes", rightPanelTab: () => "git-changes", worktreeSlug: slug, closeGitList: () => {}, externalDiff: true, }) + // The branch of an explicit server's folder, read natively; refreshed with its files. + const [remoteBranch, setRemoteBranch] = createSignal(null) + createEffect(() => { + if (!readOnly() || !active()) return + filesystemInvalidationVersion(options.instanceId) + const location = { directory: directory() }, current = sourceCurrent + void Promise.resolve().then(() => getRootClient(options.instanceId).vcs.get({ location })) + .then(result => { if (!disposed && current() && result.location?.directory === location.directory) setRemoteBranch(result.data?.branch?.current ?? null) }) + .catch(() => {}) + }) const openFile = (file: Pick) => { + if (!active()) return const sessionId = options.activeSessionId() if (!sessionId || sessionId === "info") return const preview = getSessionPreview(sessionId, options.instance.folder) if (preview) showSessionChat(preview.storageKey) openFilePreview(options.instanceId, { ...file, sessionId, slug: slug(), directory: directory(), serviceDirectory: worktree()?.serviceDirectory }) } - return createCoreRightPanelModule({ - renderFilesTab: () => { + readOnly={readOnly()} branch={worktree()?.branch ?? (readOnly() ? remoteBranch() : null)} onWorktreeChange={value => { setBrowsedWorktree(value) closeFilePreview(options.instanceId) - }} onOpenFile={openFile} canOpenFile={Boolean(options.activeSessionId() && options.activeSessionId() !== "info")} />, - renderStatusTab: () => options.isActive() && options.rightPanelTab() === "status"} - expandedItems={options.expandedItems} onExpandedItemsChange={options.onExpandedItemsChange} - customization={options.customization} onCustomizationChange={options.onCustomizationChange} extraSections={options.extraStatusSections()} - extraContent={options.extraStatusContent?.()} />, - }) + }} onOpenFile={openFile} canOpenFile={Boolean(options.activeSessionId() && options.activeSessionId() !== "info")} /> } diff --git a/packages/ui/src/components/instance/shell/right-panel/integration-status-module.tsx b/packages/ui/src/components/instance/shell/right-panel/integration-status-module.tsx index 699ea52646..281b8eecc4 100644 --- a/packages/ui/src/components/instance/shell/right-panel/integration-status-module.tsx +++ b/packages/ui/src/components/instance/shell/right-panel/integration-status-module.tsx @@ -17,6 +17,7 @@ import { import { INTEGRATION_SECTION_ORDER, integrationSectionId, integrationSectionIds } from "./integration-sections" import type { RightPanelModule, RightPanelSectionModule } from "./registry" import "../../../../stores/plugin-controls-events" +import { createProjectAdmission } from "../../../../stores/project-capability" interface IntegrationStatusModuleOptions { instanceId: string @@ -34,6 +35,13 @@ export const INTEGRATION_ANNOUNCE_DELAY_MS = 500 * the single attachment (picker, bindings, receipts) of the displayed conversation that they share. */ export function createIntegrationStatusModule(options: IntegrationStatusModuleOptions): Accessor { + const admission = createProjectAdmission(() => options.instanceId, () => "plugins") + const runtime = createMemo(() => admission() ? untrack(() => createAdmittedIntegrationStatusModule(options)) : undefined) + const unavailable: RightPanelModule = { id: "integration-status", displayNameKey: "", origin: "first-party", statusSections: [] } + return createMemo(() => runtime()?.() ?? unavailable) +} + +function createAdmittedIntegrationStatusModule(options: IntegrationStatusModuleOptions): Accessor { let statusMarker: HTMLDivElement | undefined const pluginsTrigger = () => { const root = statusMarker?.closest(".status-tab-container") @@ -61,23 +69,30 @@ export function createIntegrationStatusModule(options: IntegrationStatusModuleOp announceTimer = setTimeout(() => { setAnnouncement(queued.join(" ")); queued = [] }, INTEGRATION_ANNOUNCE_DELAY_MS) } onCleanup(() => clearTimeout(announceTimer)) - const attachment = createIntegrationAttachment({ - instanceId: options.instanceId, - get directory() { return directory() }, - get session() { return session() }, - get active() { return options.isActive() }, - onMessage: announce, - focusFallback: () => pluginsTrigger(), - }) - const installation = createIntegrationHostInstallation({ - instanceId: options.instanceId, - get directory() { return directory() }, - get sessionId() { return session()?.id }, - get active() { return options.isActive() }, - entries: attachment.entries, - }) + // Read-only remote status never constructs host controllers or binding demand. + const hostAdmission = createProjectAdmission(() => options.instanceId, () => "pluginWrite") + const controllers = createMemo(() => hostAdmission() ? untrack(() => { + const attachment = createIntegrationAttachment({ + instanceId: options.instanceId, + get directory() { return directory() }, + get session() { return session() }, + get active() { return options.isActive() }, + onMessage: announce, + focusFallback: () => pluginsTrigger(), + }) + const installation = createIntegrationHostInstallation({ + instanceId: options.instanceId, + get directory() { return directory() }, + get sessionId() { return session()?.id }, + get active() { return options.isActive() }, + entries: attachment.entries, + }) + return { attachment, installation } + }) : undefined) const context: IntegrationSectionContext = { - instanceId: options.instanceId, location, session, active: options.isActive, attachment, installation, + instanceId: options.instanceId, location, session, active: options.isActive, + get attachment() { return controllers()?.attachment }, + get installation() { return controllers()?.installation }, pluginsTrigger: () => pluginsTrigger(), } const entry = (id: string): IntegrationView | undefined => response()?.integrations.find(item => item.id === id) @@ -151,7 +166,7 @@ export function createIntegrationStatusModule(options: IntegrationStatusModuleOp }, { defer: true })) const renderStatusExtras = () => <> - {attachment.picker()} + {controllers()?.attachment.picker()}
{announcement()}
return createMemo(() => ({ diff --git a/packages/ui/src/components/instance/shell/right-panel/tabs/FilesPanel.tsx b/packages/ui/src/components/instance/shell/right-panel/tabs/FilesPanel.tsx index 2e4500cb14..8377245fe9 100644 --- a/packages/ui/src/components/instance/shell/right-panel/tabs/FilesPanel.tsx +++ b/packages/ui/src/components/instance/shell/right-panel/tabs/FilesPanel.tsx @@ -20,6 +20,7 @@ import type { GitChangeListItem, GitChangeSection } from "../types" import type { useWorkspaceTree } from "../useWorkspaceTree" import { WorkspaceTree } from "../components/WorkspaceTree" import type { FilesPanelMode } from "../files-panel-state" +import { remoteReadErrorText } from "../../../../../lib/remote-read-error" interface FilesPanelProps { t: (key: string, vars?: Record) => string @@ -39,6 +40,8 @@ interface FilesPanelProps { onWorktreeChange: (slug: string) => void onOpenFile: (file: Pick) => void canOpenFile: boolean + /** prototype-1236: explicit server: working changes only, no history, index, commit or init. */ + readOnly?: boolean } const FilesPanel: Component = props => { @@ -67,7 +70,7 @@ const FilesPanel: Component = props => { const commits = createMemo(() => (props.history.page()?.commits ?? []).filter(commit => `${commit.subject} ${commit.author} ${commit.id}`.toLowerCase().includes(filter().toLowerCase()))) const handleStageDragEnd = ({ draggable, droppable }: SolidDndDragEvent) => { - if (!droppable) return + if (!droppable || props.readOnly) return const target = String(droppable.id) if (target !== "staged" && target !== "unstaged") return const item = items().find(entry => entry.id === String(draggable.id)) @@ -76,7 +79,8 @@ const FilesPanel: Component = props => { else props.git.unstageGitFile(item) } const loading = () => props.mode === "workspace" ? props.tree.busy().size > 0 : props.mode === "history" ? props.history.loading() || props.history.detailLoading() : props.git.gitStatusLoading() - const error = () => props.mode === "workspace" || !props.gitAvailable ? null : props.mode === "history" ? props.history.error() : props.git.gitStatusError() + const rawError = () => props.mode === "workspace" || !props.gitAvailable ? null : props.mode === "history" ? props.history.error() : props.git.gitStatusError() + const error = () => { const value = rawError(); return value && remoteReadErrorText(value, props.t) } const basename = (path: string) => path.replace(/\\/g, "/").split("/").pop() || path const date = (value: string) => new Date(value).toLocaleDateString(document.documentElement.lang || undefined, { month: "short", day: "numeric" }) @@ -100,7 +104,7 @@ const FilesPanel: Component = props => {
- +
{props.t("gitPanel.files", { count: props.git.gitStatusEntries()?.length ?? 0 })} @@ -116,11 +120,11 @@ const FilesPanel: Component = props => {

{props.t("filesPanel.gitInit.notRepository")}

- +
@@ -162,8 +166,8 @@ const FilesPanel: Component = props => {

{props.git.gitStatusLoading() ? props.t("instanceInfo.loading") : props.t("instanceShell.gitChanges.empty")}

- {section => - {section => +
@@ -199,6 +203,7 @@ const ChangeSection: Component<{ onOpenFile: FilesPanelProps["onOpenFile"] previewActive: (file: Parameters[0]) => boolean children?: JSX.Element + readOnly?: boolean }> = sectionProps => { const droppable = createDroppable(sectionProps.section) const [open, setOpen] = createSignal(true) @@ -226,7 +231,7 @@ const ChangeSection: Component<{ @@ -141,7 +148,9 @@ const StatusTab: Component = (props) => { } const removeShell = async (shellId: string, command: string, running: boolean) => { + if (!getProjectAvailability(props.instanceId, "backgroundShells").allowed) return const instanceId = props.instanceId + const current = captureInstanceRequestAuthority(instanceId) const location = { ...shellLocation() } const confirmed = await showConfirmDialog( props.t("instanceShell.backgroundProcesses.remove.message", { title: command }), @@ -152,7 +161,9 @@ const StatusTab: Component = (props) => { : "instanceShell.backgroundProcesses.actions.remove"), }, ) - if (confirmed && !await shellStore.remove(instanceId, location.directory, shellId, location.workspaceID)) { + if (!confirmed || !current() || !getProjectAvailability(instanceId, "backgroundShells").allowed) return + const removed = await shellStore.remove(instanceId, location.directory, shellId, location.workspaceID) + if (current() && getProjectAvailability(instanceId, "backgroundShells").allowed && !removed) { showToastNotification({ category: "sessions", message: props.t("instanceShell.backgroundProcesses.error"), variant: "error" }) } } @@ -196,7 +207,7 @@ const StatusTab: Component = (props) => { + {action => ( + )}

{t("integrations.installHost.machine")}

@@ -185,14 +185,14 @@ function IntegrationSectionBody(props: { t: Translate; entry: Accessor )} - {row => ( + {row => ( {conversationText()} {identity => {action => ( )}} diff --git a/packages/ui/src/components/interruption-dock.tsx b/packages/ui/src/components/interruption-dock.tsx index 3c9a2f3680..fb267fbd68 100644 --- a/packages/ui/src/components/interruption-dock.tsx +++ b/packages/ui/src/components/interruption-dock.tsx @@ -1,8 +1,10 @@ -import { For, Show, createEffect, createMemo, on, onCleanup, untrack } from "solid-js" +import { For, Show, createEffect, createMemo, createUniqueId, on, onCleanup, untrack } from "solid-js" import { ChevronLeft, ChevronRight, ChevronDown, ChevronUp, MessageCircleQuestion, ShieldCheck, ShieldAlert } from "lucide-solid" import { useI18n } from "../lib/i18n" -import { getPermissionQueue, sendFormCancel, sendFormReply } from "../stores/instances" +import { getPermissionQueue, getInterruptionContext, sendFormCancel, sendFormReply } from "../stores/instances" +import { canAnswerInterruption, isLiveOnlyInterruption } from "../stores/interruption-authority" import { getFormQueue } from "../stores/forms" +import { canVerifyKnownForm, formVerificationStatus, verifyKnownForm } from "../stores/form-verification" import { sessions } from "../stores/sessions" import { focusInterruption, interruptionFocus } from "../stores/interruption-navigation" import FormRequest from "./form-request" @@ -12,6 +14,8 @@ import { useInterruptionDockState } from "./interruption-dock-state" export function InterruptionDock(props: { instanceId: string; sessionId?: string | null; active?: boolean; onExpandedChange?: (expanded: boolean) => void; onViewConversation?: (sessionId: string) => void }) { const { t } = useI18n() + const domId = createUniqueId() + const bodyId = `interruption-body-${domId}` const { pending, current, expanded, select, index, move, previews, scope } = useInterruptionDockState(props) let root: HTMLElement | undefined const byKey = createMemo(() => new Map(pending().map(item => [item.key, item]))) @@ -51,7 +55,7 @@ export function InterruptionDock(props: { instanceId: string; sessionId?: string
@@ -68,7 +72,7 @@ export function InterruptionDock(props: { instanceId: string; sessionId?: string
@@ -89,7 +93,7 @@ export function InterruptionDock(props: { instanceId: string; sessionId?: string {preview => }
-