Repository navigation
Description
Workspace close semantics: orphaned records, cross-window coupling, and the lifetime of unsent drafts
TL;DR
After tracing how "open" state, tab closing, and reopening work end-to-end (from the home-page badge to the workspace manager to the OpenCode daemon), we found three user-visible behaviors that trace back to a single root cause: the workspace record (occurrence id) is overloaded as the identity for things whose natural identity is the folder, and the unit of "close" is the record rather than the window's attachment to it. We're not proposing a specific PR yet — we'd like to discuss direction, especially since the current contract (#970) is only a month old.
Background: three different lifetimes
| Layer | Keyed by | Lifetime |
|---|---|---|
| OpenCode sessions (daemon) | directory/project | survives everything; CodeNomad never evicts locations |
| Workspace records (CodeNomad server) | occurrence id | until DELETE /api/workspaces/:id or backend shutdown |
| Live UI state (drafts, selection, expansion, scroll) | instanceId:sessionId, per window |
destroyed on tab close |
These are three separate concerns, and the first one is right. The issues below all live in layers 2 and 3.
Issue 1: A force-closed client leaves an orphaned "open" record forever
Closing a browser window that had a project open sends no DELETE. The record stays ready forever: the home page shows "Open", and subsequent open/close of the same folder operates on new occurrences, never the orphan. The only remedies are clicking the badge (to attach and then close it) or restarting the backend.
Notably, the server does know the client is gone: ClientConnectionManager detects socket close immediately and declares a connection dead after a 45-second heartbeat timeout (STALE_CONNECTION_TIMEOUT_MS). That liveness knowledge is currently used only for SSE bookkeeping, never for workspace lifetime. So this is a design decision, not a technical limitation.
Resource cost of the orphan is negligible (one shared daemon per backend; a Map entry; LRU-capped file watches) — the problem is state fidelity, not leakage.
Issue 2: Closing a tab kills the record for every window sharing it
If window A opens a folder and window B attaches via the "Open" badge, both hold tabs for the same record. Closing either tab sends DELETE, the workspace.stopped broadcast closes the other window's tab too (with the "closed from another window" notification).
This inverts user intuition: switch to existing (the badge — looks lighter) creates a shared, fragile lifecycle, while open new occurrence (the recent row — looks heavier) creates an independent, safe one. Two adjacent entries in the same row, opposite close semantics. There is no refcounting: closeInstanceTab always deletes, regardless of how many windows display the record.
Issue 3: Unsent drafts are destroyed by closing the tab
removeInstance calls clearInstanceDraftPrompts(id). Reopening the same folder creates a new instance id, so drafts (including the new-conversation draft, __no_session_draft__) and attachments are unrecoverable. This is the only real data loss in the whole flow — and it's exactly the thing users most likely expect to survive, since every conversation does survive.
Related nuance: the persistence machinery already keys captured tabs by folder+occurrence and app restarts restore drafts correctly. The loss window is precisely: an explicit tab close followed by reopening the folder in the same window. On the web client there is no persistence at all (client state is native-desktop-only; the legacy localStorage keys are actively removed), so browser drafts die with the page — which makes the upstream decision in "Open questions" below more significant.
Root cause
The occurrence id is a routing handle, but it is used as the identity for close semantics and for per-viewer live state. Sessions got this right (the daemon keys them by directory, which is why they never get lost). Layout got this right (window-level client layout keys). Live UI state and close semantics are the two places keyed to the ephemeral handle.
What should not change
- Sessions must keep outliving workspace records ("CodeNomad never evicts native Locations") — background work may be running; guessing is unsafe.
- No eviction-style destructiveness (the pre-fix(workspaces): closing a project tab closes the project in CodeNomad #970
debug.location.evictbehavior was correctly removed).
Directions we see
- Draft vault (small, UI-only): on workspace removal, preserve drafts/attachments into a per-window, folder-keyed store instead of destroying them; hydrate on reopen through the existing
hydrateWorkspacePromptStaterules (only existing sessions, respect authoritative state, clear on send, TTL ~7 days). Fixes Issue 3 without touching any contract. - Attachment-based close (larger): track per-window attachments server-side; close = detach; reap the record when the attachment set is empty, with the existing heartbeat liveness covering force-closed clients (≤45 s). Fixes Issues 1 and 2 together: orphans self-reap, closing never crosses windows. This rewrites the fix(workspaces): closing a project tab closes the project in CodeNomad #970 contract (
workspace.stoppedbroadcast, occurrence independence docs, related tests). - Server-side draft storage (only if cross-window/cross-device draft continuity is wanted): folder-keyed drafts on the backend. Real cost: conflict rules between concurrent windows, and it partially reverses the "web client keeps no persistent state" decision. We'd rather not do this without upstream buy-in.
History note
The current close semantics landed one month ago in #970 (db6685cb5), replacing "closing only hides the tab" + the destructive Stop Workspace/evict flow. The cross-window close was documented as deliberate in that PR. Our argument is that the unit chosen (the record) is one notch too coarse — the third option (attachment counting) was never tried, and the liveness infrastructure it needs predates #970 by a week (#668).
Open questions for maintainers
- Is attachment-based close (direction 2) a shape you'd accept for the workspace-lifetime contract, or is the single-owner-record model intentional for reasons we've missed?
- Should unsent drafts survive on the web client across page closes — i.e., is the removal of web client state a permanent stance, or is a scoped exception (drafts only) discussable?
- If drafts ever move server-side, what's the stance on conflict behavior for two windows editing the same folder's draft (last-writer-wins vs. per-window isolation)?
Activity
pascalandr commentedon Nov 15, 2026
@heunghingwan Thanks for the careful trace; I checked each point against
devand they hold. The decisions follow the multi-backend work in progress (feat/multi-backend), where one window holds projects from several CodeNomad backends and a project is one folder of one backend.heunghingwan commentedon Nov 15, 2026
Thanks — the sequencing makes sense, and we'll stay out of the way of the multi-backend work.
Two follow-up questions came out of the same investigation. They concern the multi-backend end state, so I'm adding them here rather than filing separately (happy to split them out if that fits the tracker better).
1. Will the web client stay fully stateless — given that the mobile companion inherits it?
Today the web client has no persistence at all (client state is native-desktop-only, and the legacy localStorage keys are actively removed). Until a companion ships, the PWA is the practical mobile client, and it inherits that ephemerality: every page close loses drafts and last-state, while the desktop keeps all of it.
We noticed the mobile research: the Android companion prototype (#860, closed) is a thin Tauri shell hosting the server-served UI over trusted HTTPS, and #861 is the iOS source handoff. If that remains the direction, the web client's state story becomes the mobile app's state story — a stateless web client would also mean a stateless companion. That raises the stakes of this question considerably.
So: is "web stays stateless" the intended end state, or is scoped web persistence (per-backend-origin drafts and basic last-state in localStorage/IndexedDB) reconsiderable once the multi-backend identity model lands?
2. Authentication across multiple backends, and password-manager interop
With backends run by different machines, distinct passwords per backend is the right security posture — which makes credential handling a first-class problem for the desktop app as a multi-backend client. Remote Control pairing covers paired devices, but direct-access servers use password sessions, and hand-typing N credentials into an embedded login surface that external password managers can't reach is the pain point.
We researched how an external password manager can obtain the target origin in each webview stack CodeNomad ships on (including the companion's stack):
Practical conclusion: on none of the three desktop webview stacks can external password managers be the primary credential path; the companion could be the one place they work, if it keeps loading real backend origins.
Worth noting this is a solved problem elsewhere: native apps that need login deliberately open the system browser instead of embedding the login page — RFC 8252 forbids embedded user agents for OAuth authorization for exactly these reasons (no shared credentials, no password-manager integration, no visible address bar to defeat phishing). VS Code, Git Credential Manager and Slack all do the system-browser flow, getting the result back via a loopback redirect (
127.0.0.1:{port}) or a private URI scheme. CodeNomad is close in shape already: the Remote Control pairing link is a one-time code handed through the browser, and the backend runs an HTTP listener that could receive a loopback handoff.Three asks, in decreasing order of ambition:
safeStorage; OS keychain/keyring on Tauri) on the multi-backend roadmap, filled from the app's server-management UI?pascalandr commentedon Nov 15, 2026
@heunghingwan Thanks, here is where things stand on
feat/multi-backend.pascalandr commentedon Nov 15, 2026
about the mobile App I gave up for the momment as they don't offer anything more than the PWA , an app would make sens if we want direct connection to opencode without the codenomad server, but then it's not codenomad anymore (#1296 it exists here but abandonned at the momment) I mean we loose many many features.
heunghingwan commentedon Nov 15, 2026
On the mobile app being shelved — understood. That actually raises the stakes of the web last-state plan: with the PWA as the only mobile client for the foreseeable future, that work is no longer just the web client's story, it is the mobile story. Per-tab session storage seems like the right starting point for the reload-after-app-switch pain; IndexedDB per backend origin is the natural escalation if it proves too thin on real devices.
One more gap we'd like to raise while we're here — pairing and network-restricted environments:
Pairing is currently tunnel-only, coupled in three places: device authentication is only consulted for tunnel sockets (
getSessionFromRequest→isRemoteRequestinrequest-origin.ts), the pairing-code exchange sits behind the ingress gate's Host/Origin checks, and__Host-codenomad_deviceisSecure, so a browser on plain-HTTP LAN cannot even hold it. That last point is also the correct threat-model outcome — a device token sent in cleartext would be replayable by anyone on the segment.The problem is the network environments where this leaves nothing: with corporate egress filtering blocking the tunnel and no inbound port possible, the only remaining path is a direct HTTPS deployment (reverse proxy + real certificate +
CODENOMAD_ALLOWED_ORIGINS) — and that path is password-only today. It misses exactly the things that make pairing the better credential model: per-device revocation, idle expiry, the 32-device inventory.The device registry itself (
devices.ts) is transport-agnostic — the coupling is all in admission. Would you consider accepting device credentials on verified direct HTTPS origins? Same registry, sameOriginchecks the direct listener already runs for mutations, and gated the way #1296's prototype gated its direct connections ("non-loopback connections require verified HTTPS; loopback HTTP is supported"). Plain-HTTP LAN would stay password-only, which is where it should stay. The pairing-code exchange would need to accept the direct origin too, so enrollment happens over the same TLS channel the credential will be used on.pascalandr commentedon Nov 15, 2026
@heunghingwan Agreed on the analysis, and the boundary you propose is the right one: device credentials only on verified direct HTTPS origins, enrollment over that same TLS channel, plain-HTTP LAN staying password-only. The device registry already supports it, and
feat/multi-backendalready admits server device credentials on the direct listener, so this mostly extends browser admission and the pairing exchange. Codes stay host-issued, single-use and rate-limited. I'll schedule it after multi-backend lands, since both touch device admission.heunghingwan commentedon Nov 15, 2026
Thanks — that boundary works well for us. Looking forward to seeing multi-backend land.
feat(ui): restore a browser tab's projects and drafts after a reload (#…
feat(ui): keep unsent drafts when a project tab closes (#1522)
feat(remote-control): pair browser devices on verified direct HTTPS o…
leodev-2022 commentedon Nov 16, 2026
Adding a live datapoint from a 4-node fleet (reported by the operator of one of them) — it looks exactly like Issue 1: records pile up for the same folder while the daemon stays single.
Environment
1.0.1, opencode2.2.1(currentVersion/daemonVersionboth 2.2.1,state=ready,serviceState=ready)2026-11-14 06:05, args:--workspace-root /opt/deer-flow --dangerously-skip-auth, HTTP on9898, behind a reverse proxyObserved on 2026-11-16
GET /api/workspacesreturned 4 records, samenameand samepath, distinct ids, allstatus=ready:8a27b825-…/opt/deer-flow3348f690-…/opt/deer-flowc4b14d73-…/opt/deer-flowd5777262-…/opt/deer-flowpsshows a singleopencode serve --service(pid 884762, listening127.0.0.1:49374) → not a duplicated daemon.~/.config/codenomad/state.yamlcontains one path inui.recentFolders→ the duplicates live in server memory, exactly as described in Issue 1.deer-flow: вопросы и разрешения восстановлены не полностью / Сервер не ответил для: deer-flow (Failed to fetch).Questions from the operator (and from us)
GET /api/workspacesexpected to dedupe bypath(i.e. return the existing occurrence), or is the client expected to reuse the record it already has? In this case each reopen created a new occurrence while the folder was alreadyready.DELETE /api/workspaces/<id>returns 204 and does not disturb sessions — but the operator cannot verify which record the live tab is attached to, so deleting the wrong one closes the tab (harmless but noisy). A server-side "drop orphans older than N minutes with no connection" or "same path → same record" would fix it.Failed to fetchin the permission-recovery message: is it a consequence of the duplicate attach, or a separate failure path? We can capture the failing request (URL + status) on the next occurrence if that helps.Happy to run a reproduction on our nodes (same box, 4 workspaces, one client) and attach logs / an SSE trace if that is useful.
pascalandr commentedon Nov 16, 2026
@leodev-2022 In
1.0.1a reload returns to the home page, where the folder row opens a new instance and the Open badge reattaches the existing one;devreattaches tabs after a reload (#1515).DELETE /api/workspaces/<id>removes extras without touching sessions.Failed to fetchis most likely your proxy cuttingGET /api/workspaces/<id>/pending-requests(up to 30 s): set its read timeout to at least 35 s. Also,--dangerously-skip-authleaves the node open to anyone your proxy lets through.pascalandr commentedon Nov 21, 2026
@heunghingwan Multi-backend has landed on
dev(#1629). Status of the points above:pascalandr commentedon Nov 21, 2026
All three problems, and the reload-to-Home point raised in the discussion, are fixed on
devby #1629, so I'm closing this. The cross-window part needed no attachment counting: