Skip to content

Workspace close semantics: orphaned records, cross-window coupling, and the lifetime of unsent drafts #1513

Closed

Description

@heunghingwan

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

Directions we see

  1. 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 hydrateWorkspacePromptState rules (only existing sessions, respect authoritative state, clear on send, TTL ~7 days). Fixes Issue 3 without touching any contract.
  2. 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.stopped broadcast, occurrence independence docs, related tests).
  3. 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

  1. 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?
  2. 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?
  3. 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

  1. pascalandr commented on Nov 15, 2026

    @pascalandr
    Contributor

    @heunghingwan Thanks for the careful trace; I checked each point against dev and 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.

    1. Draft vault (direction 1): yes. Keep unsent drafts and attachments when a tab closes, keyed by the project identity (folder + backend), and rehydrate them through the existing rules on reopen. Multi-backend already treats drafts as part of the saved tab, so they can outlive the backend's workspace record.
    2. Orphaned records (issue 1): we won't reap records on connection liveness. With remote backends, a record without a live connection normally belongs to a desktop that is asleep, quit or offline, and its restoration expects to find it. Reaping it would close that tab when the client comes back. We'll treat the "Open" badge as a display problem instead.
    3. Cross-window close (issue 2): agreed, and it gets worse with remote backends (two machines on the same server close each other's tabs). The unit should be a durable per-window attachment that only an explicit close, a local window close or a removed server releases, never a dropped connection. That reworks the fix(workspaces): closing a project tab closes the project in CodeNomad #970 contract and the multi-backend restore, so it comes after multi-backend lands.
    4. Server-side drafts (direction 3): no; drafts stay in client-side tab state.
  2. heunghingwan commented on Nov 15, 2026

    @heunghingwan
    ContributorAuthor

    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):

    Stack Origin-based matching Notes
    Mobile browser / installed PWA ✅ works native browser context
    Android WebView — the #860 companion stack ⚠️ conditional the autofill service receives the page's real web origin, so it can work when the shell loads the backend's actual HTTPS origin — a custom/localhost proxy origin breaks matching (tauri-apps/tauri#14367); worth baking into the companion's transport design
    Windows WebView2 (Tauri) ⚠️ loses credentials browser-level password autofill exists and is origin-based, but credentials live in the WebView2 profile; the incognito store used for remote TLS-proxy windows discards them
    macOS/iOS WKWebView ❌ no Password AutoFill only suggests credentials for the app's associated domains (entitlement + apple-app-site-association) — cannot cover arbitrary user-chosen backends; relevant if the iOS handoff ever resumes
    Electron ❌ no no OS autofill bridge and no arbitrary extension support (docs)
    Linux WebKitGTK ❈ no form autofill integration libsecret is an app-side secret store, not a webview autofill source

    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:

    1. Is app-side per-backend credential storage (Electron safeStorage; OS keychain/keyring on Tauri) on the multi-backend roadmap, filled from the app's server-management UI?
    2. Or an RFC 8252-style system-browser login flow for direct-access servers: open the backend's real origin in the default browser (password managers and the visible address bar both work there), then hand the session back to the app via a loopback callback or a short-lived one-time code — composing with the existing pairing machinery rather than reinventing it.
    3. Minimum viable regardless of the above: always render the backend's real origin visibly in any embedded login surface (window title plus a non-spoofable origin line in the form), so users can at least match credentials manually — and so the phishing surface of an embedded login page is bounded.
  3. pascalandr commented on Nov 15, 2026

    @pascalandr
    Contributor

    @heunghingwan Thanks, here is where things stand on feat/multi-backend.

    1. Web state: multi-backend leaves the web client single-server, so the browser/PWA stays the mobile client, and I agree its ephemerality hurts there: mobile browsers reload the page after an app switch or screen lock, and the user lands back on the home page. I'll add a minimal web last-state (open projects, active session, reading position and unsent drafts), restored through the same rules as the desktop. I'll start with per-tab session storage and extend it if that doesn't survive real mobile use.
    2. Credentials: the local backend already stores each saved server's credential privately next to its configuration, and the UI never handles it. Pairing is the recommended path: a one-time code becomes a revocable device credential, with no password. System-browser login is a possible later addition. I'll show the exact origin in the Connect form.
  4. pascalandr commented on Nov 15, 2026

    @pascalandr
    Contributor

    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.

  5. heunghingwan commented on Nov 15, 2026

    @heunghingwan
    ContributorAuthor

    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 → isRemoteRequest in request-origin.ts), the pairing-code exchange sits behind the ingress gate's Host/Origin checks, and __Host-codenomad_device is Secure, 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, same Origin checks 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.

  6. pascalandr commented on Nov 15, 2026

    @pascalandr
    Contributor

    @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-backend already 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.

  7. heunghingwan commented on Nov 15, 2026

    @heunghingwan
    ContributorAuthor

    Thanks — that boundary works well for us. Looking forward to seeing multi-backend land.

  8. leodev-2022 commented on Nov 16, 2026

    @leodev-2022

    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

    • CodeNomad 1.0.1, opencode 2.2.1 (currentVersion/daemonVersion both 2.2.1, state=ready, serviceState=ready)
    • Linux node, engine started 2026-11-14 06:05, args: --workspace-root /opt/deer-flow --dangerously-skip-auth, HTTP on 9898, behind a reverse proxy
    • One client (a browser cockpit) unless stated otherwise

    Observed on 2026-11-16
    GET /api/workspaces returned 4 records, same name and same path, distinct ids, all status=ready:

    id name path createdAt (UTC)
    8a27b825-… deer-flow /opt/deer-flow 05:56:49
    3348f690-… deer-flow /opt/deer-flow 07:03:31
    c4b14d73-… deer-flow /opt/deer-flow 09:52:38
    d5777262-… deer-flow /opt/deer-flow 09:54:17
    • At ~12:35 local it was 2, by ~13:55 it was 4 (timestamps above are the record creations). Growth correlates with the operator reopening/refreshing the cockpit, not with any folder action.
    • ps shows a single opencode serve --service (pid 884762, listening 127.0.0.1:49374) → not a duplicated daemon.
    • ~/.config/codenomad/state.yaml contains one path in ui.recentFolders → the duplicates live in server memory, exactly as described in Issue 1.
    • No session or data loss observed. The user-visible part is a warning in the UI: deer-flow: вопросы и разрешения восстановлены не полностью / Сервер не ответил для: deer-flow (Failed to fetch).

    Questions from the operator (and from us)

    1. Is GET /api/workspaces expected to dedupe by path (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 already ready.
    2. Can the extras be cleaned without restarting the engine? 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.
    3. The Failed to fetch in 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.

  9. pascalandr commented on Nov 16, 2026

    @pascalandr
    Contributor

    @leodev-2022 In 1.0.1 a reload returns to the home page, where the folder row opens a new instance and the Open badge reattaches the existing one; dev reattaches tabs after a reload (#1515). DELETE /api/workspaces/<id> removes extras without touching sessions. Failed to fetch is most likely your proxy cutting GET /api/workspaces/<id>/pending-requests (up to 30 s): set its read timeout to at least 35 s. Also, --dangerously-skip-auth leaves the node open to anyone your proxy lets through.

  10. pascalandr commented on Nov 21, 2026

    @pascalandr
    Contributor

    @heunghingwan Multi-backend has landed on dev (#1629). Status of the points above:

    • Unsent drafts and attachments now survive closing a tab and come back when the folder is reopened
    • Web last-state: a browser tab restores its open projects, active session and drafts after a reload
    • Pairing over direct HTTPS works without the tunnel
  11. pascalandr commented on Nov 21, 2026

    @pascalandr
    Contributor

    All three problems, and the reload-to-Home point raised in the discussion, are fixed on dev by #1629, so I'm closing this. The cross-window part needed no attachment counting:

    1. Orphaned "Open" badge: the badge now only reflects tabs of the current window, so a record left by a closed window no longer shows as open.
    2. Closing a tab closes it in another window: a second window no longer shows Open for a folder open only in another window, so it can't join that tab; opening the folder from its row gives the window its own tab, and closing it elsewhere leaves it open. Verified natively with two Electron windows, local and remote.
    3. Unsent drafts: kept when a tab closes and restored when the folder is reopened.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions