Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
6 changes: 6 additions & 0 deletions dev-docs/BROWSER_AUTOMATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.
193 changes: 181 additions & 12 deletions dev-docs/CACHE_REFRESH_CONVENTIONS.md

Large diffs are not rendered by default.

17 changes: 16 additions & 1 deletion dev-docs/COMPOSER.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
85 changes: 85 additions & 0 deletions dev-docs/DESKTOP_DATA_PROFILES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<name>` — explicit profile.
Expand All @@ -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 `<scope> = <key>-sha256(key + "\0" + configIdentity)[0..16]`, i.e. `%APPDATA%/CodeNomad/scopes/<scope>` (Electron `userData` and both hosts' client state) and `…-v2/scopes/<scope>` (Tauri WebView), plus a scoped Tauri identifier. The default profile's key is `stable`, so existing folders such as `dev-<hash>` and `dev-v2-<hash>` 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\<identifier>` (`DisplayName` CodeNomad, `IconUri` the bundled web app icon `resources\server\public\pwa-192x192.png`; `windows_notification_identity.rs`). Electron always uses the stable ID.
Expand All @@ -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=<profile key>`, `CODENOMAD_PROFILE_CONFIG_IDENTITY=<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-<UUID>` 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:
Expand Down Expand Up @@ -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).
Expand Down
Loading
Loading