Title: Feature request: make chat sessions server-side so they follow the user across browsers, and let them be archived · Issue #7948 · coder/code-server · GitHub
Open Graph Title: Feature request: make chat sessions server-side so they follow the user across browsers, and let them be archived · Issue #7948 · coder/code-server
X Title: Feature request: make chat sessions server-side so they follow the user across browsers, and let them be archived · Issue #7948 · coder/code-server
Description: Summary Chat session content already lives on the server, but the index that makes sessions visible lives in the browser's IndexedDB. The result is that chat history is silently browser-local: open the same code-server from a second brow...
Open Graph Description: Summary Chat session content already lives on the server, but the index that makes sessions visible lives in the browser's IndexedDB. The result is that chat history is silently browser-local: open...
X Description: Summary Chat session content already lives on the server, but the index that makes sessions visible lives in the browser's IndexedDB. The result is that chat history is silently browser-local: ...
Opengraph URL: https://github.com/coder/code-server/issues/7948
X: @github
Domain: github.com
IPv4 address: 140.82.112.3
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Feature request: make chat sessions server-side so they follow the user across browsers, and let them be archived","articleBody":"## Summary\n\nChat session **content** already lives on the server, but the **index that makes\nsessions visible** lives in the browser's IndexedDB. The result is that chat\nhistory is silently browser-local: open the same code-server from a second\nbrowser (or a phone) and the chat list is empty, even though every message is\nsitting on the server's disk.\n\nI'd like code-server to (1) serve that index from the server so sessions follow\nthe user, and (2) offer an opt-in archive so sessions survive deletion.\n\nI've been running a working implementation of both for a while — details and\nmeasurements below, in case they're useful for scoping.\n\n## Current behaviour\n\nSession content is on the server:\n\n```\n\u003cuser-data-dir>/User/workspaceStorage/\u003cworkspaceHash>/chatSessions/\u003cuuid>.jsonl\n```\n\nBut the list of sessions is stored in the browser:\n\n```\nIndexedDB: vscode-web-state-db-\u003cworkspaceId>\nstore: ItemTable\nkey: chat.ChatSessionStore.index\n```\n\nEach entry is small metadata — no message content:\n\n```json\n{\n \"sessionId\": \"6d8bcdfd-...\",\n \"title\": \"…\",\n \"lastMessageDate\": 1786645548589,\n \"timing\": { \"created\": …, \"lastRequestStarted\": …, \"lastRequestEnded\": … },\n \"initialLocation\": \"panel\",\n \"hasPendingEdits\": false,\n \"isEmpty\": false,\n \"isExternal\": false,\n \"lastResponseState\": 1\n}\n```\n\nSo the index is a pure derivative of files the server already has.\n\n### Steps to reproduce\n\n1. Open code-server in browser A, have a few chats.\n2. Open the same code-server URL in browser B (or a different device).\n3. Browser B shows an empty chat list.\n4. On the server, `…/chatSessions/*.jsonl` still contains everything.\n\n### Why this is worse than it sounds\n\n- **It looks like data loss.** Clearing site data, using a private window, or\n switching devices makes the history vanish with no message and no way back\n through the UI.\n- **The desktop expectation doesn't hold.** In desktop VS Code, chat history is\n tied to the machine you're sitting at. With code-server the \"machine\" is the\n server, so users reasonably expect history to be there from any browser — and\n it is, just not reachable.\n- **It's silent.** Nothing tells the user the sessions still exist server-side.\n\n## Proposal\n\n### 1. Serve the chat session index from the server\n\nThe server can rebuild that index by scanning `chatSessions/*.jsonl` — it needs\n`sessionId`, a title, and timestamps, all of which are in the files. The browser\nwould seed IndexedDB from that endpoint instead of starting empty.\n\nDeletion needs care: if the browser simply merges the server list back in, a\nsession the user deleted reappears. What works is treating the server as\nauthoritative for *existence*: an entry that is gone server-side is removed\nlocally, and a local entry that has no server file is dropped rather than\nresurrected.\n\n### 2. Opt-in archive\n\nA flag such as `--chat-archive \u003cdir>` that keeps a copy of each session as it\ngrows. Two things make it worth more than a plain backup:\n\n- Sessions get **reset in place** — VS Code reuses the same `sessionId` and\n truncates the file. A copier that mirrors the source loses the old content.\n Keeping the longest version seen, and saving post-reset content beside it,\n preserves both.\n- A **readable rendering** (Markdown) next to the raw `.jsonl` makes the archive\n greppable and readable without tooling.\n\n## Reference implementation\n\nExtracted from a working setup and trimmed to the essentials. My version is\nPython (server) + plain JS (browser) because it runs as an injected script;\nupstream would presumably do the server half in TypeScript, but the algorithm is\nthe point.\n\n### 1. Rebuild the index by replaying the op logs\n\n`.jsonl` sessions are op logs, not documents. Three op kinds matter, and\nskipping any of them silently loses data — `kind: 2` in particular is how\nstreamed responses arrive, so handling only snapshots drops in-flight answers.\n\n```python\ndef replay(path):\n \"\"\"Rebuild session state from an op log. Returns the state dict, or None.\"\"\"\n state = {}\n with open(path, \"rt\", encoding=\"utf-8\", errors=\"replace\") as fh:\n for line in fh:\n line = line.strip()\n if not line:\n continue\n try:\n op = json.loads(line)\n except ValueError:\n continue # half-written line, still being appended\n kind, key, val = op.get(\"kind\"), op.get(\"k\"), op.get(\"v\")\n if kind == 0: # full snapshot\n state = val if isinstance(val, dict) else {}\n continue\n if not isinstance(key, list) or not key:\n continue\n cur = state\n try:\n for seg in key[:-1]:\n cur = cur[seg]\n last = key[-1]\n if kind == 2: # append to array (streamed responses)\n tgt = cur[last] if (last in cur if isinstance(cur, dict) else True) else None\n if isinstance(tgt, list) and isinstance(val, list):\n tgt.extend(val)\n else:\n cur[last] = val\n else: # kind == 1: set key\n cur[last] = val\n except (KeyError, IndexError, TypeError):\n continue # shape mismatch: skip this op, keep the session\n return state or None\n\n\ndef index_entry(state):\n \"\"\"One entry of chat.ChatSessionStore.index. Metadata only, no message content.\"\"\"\n reqs = state.get(\"requests\") or []\n created = state.get(\"creationDate\") or 0\n last = created\n for r in reqs:\n if isinstance(r, dict) and isinstance(r.get(\"timestamp\"), int):\n last = max(last, r[\"timestamp\"])\n return {\n \"sessionId\": state.get(\"sessionId\"),\n \"title\": session_title(state),\n \"lastMessageDate\": last,\n \"timing\": {\"created\": created,\n \"lastRequestStarted\": last,\n \"lastRequestEnded\": last},\n \"initialLocation\": state.get(\"initialLocation\") or \"panel\",\n \"hasPendingEdits\": False,\n \"isEmpty\": False,\n \"isExternal\": False,\n \"lastResponseState\": 1,\n }\n\n\ndef session_title(state):\n \"\"\"customTitle if the user renamed it, else derive from the first question.\"\"\"\n t = state.get(\"customTitle\") or state.get(\"title\")\n if t:\n return str(t)[:200]\n for r in state.get(\"requests\") or []:\n text = ((r.get(\"message\") or {}).get(\"text\") or \"\").strip()\n if text:\n return text.splitlines()[0][:200]\n return \"Untitled session\"\n```\n\n### 2. Only re-read what actually changed\n\nTwo layers. The first is a plain `(size, mtime_ns)` cache — note **`mtime_ns`,\nnot `int(st_mtime)`**: with second precision, an edit inside the same second\nthat happens to leave the size unchanged (renaming a session to an equal-length\ntitle does exactly that) is invisible forever.\n\n```python\nst = os.stat(src)\nprev = cache.get(src) or {}\nif prev.get(\"size\") == st.st_size and prev.get(\"mtime_ns\") == st.st_mtime_ns:\n reuse(prev) # nothing touched the file\n continue\n```\n\nThe second layer is what makes typing cheap. VS Code appends an `inputState` op\non every keystroke, so size and mtime change constantly while the content that\nmatters does not. Comparing a cheap content signature skips all of it:\n\n```python\ndef content_sig(state):\n \"\"\"(turns, last timestamp, response part count, total characters).\n\n All four are needed: turns catches add/delete, the timestamp catches a new\n turn, and the character count catches a streaming answer growing while turn\n count and timestamp both stay put — and edits to a message in the middle.\n\n Only string lengths are summed; str()-ing dicts here is real CPU on a 28 MB\n session.\n \"\"\"\n reqs = state.get(\"requests\") or []\n if not reqs:\n return (0, 0, 0, 0)\n parts = total = 0\n for r in reqs:\n if not isinstance(r, dict):\n continue\n total += len(((r.get(\"message\") or {}).get(\"text\") or \"\"))\n resp = r.get(\"response\") or []\n parts += len(resp)\n for part in resp:\n v = part.get(\"value\") if isinstance(part, dict) else part\n total += len(v) if isinstance(v, str) else 1\n last = reqs[-1] if isinstance(reqs[-1], dict) else {}\n return (len(reqs), last.get(\"timestamp\") or 0, parts, total)\n```\n\nTitle is compared separately rather than folded into the signature: renaming a\nsession changes nothing else about it, and adding a 5th element would invalidate\nevery stored signature at once.\n\n### 3. Seed IndexedDB, and let deletions propagate\n\nThe naive merge (union server ∪ local) resurrects sessions the user deleted. The\nnaive fix (server is authoritative, drop anything missing) deletes sessions that\nare merely *new*, or that the server briefly failed to read.\n\nBoth failure modes bit me in practice — reading a session while it is being\nwritten fails often enough to matter (~25 % of reads during active chat) — so\nmissing-from-server is treated as a *suspicion* that has to survive a time\nwindow before it becomes a deletion:\n\n```js\nconst KEY = 'chat.ChatSessionStore.index';\nconst DELETE_GRACE_MS = 300000; // newer than the server's rebuild interval → never touch\nconst DELETE_CONFIRM_MS = 120000; // must stay missing this long before we act\n\nasync function mergeIndex(dbName, serverEntries, pending) {\n const db = await openWithStore(dbName); // creates ItemTable if absent\n const tx = db.transaction('ItemTable', 'readwrite');\n const store = tx.objectStore('ItemTable');\n const raw = await wrap(store.get(KEY));\n\n let index;\n try { index = raw ? JSON.parse(raw) : { version: 1, entries: {} }; }\n catch { index = { version: 1, entries: {} }; }\n if (!index.entries) index.entries = {};\n if (raw) await wrap(store.put(raw, KEY + '.backup')); // one-level undo\n\n let added = 0, removed = 0;\n const now = Date.now();\n\n for (const [id, entry] of Object.entries(serverEntries)) {\n if (!index.entries[id]) { index.entries[id] = entry; added++; }\n pending.delete(id); // it is back: cancel any suspicion\n }\n\n for (const [id, entry] of Object.entries(index.entries)) {\n if (serverEntries[id]) continue;\n const age = now - (entry.lastMessageDate || 0);\n if (age \u003c DELETE_GRACE_MS) continue; // too new for the server to know about\n const since = pending.get(id);\n if (since === undefined) { pending.set(id, now); continue; } // start watching\n if (now - since >= DELETE_CONFIRM_MS) { // still gone → really deleted\n delete index.entries[id];\n pending.delete(id);\n removed++;\n }\n }\n\n if (added || removed) await wrap(store.put(JSON.stringify(index), KEY));\n await new Promise((res, rej) => { tx.oncomplete = res; tx.onerror = () => rej(tx.error); });\n db.close();\n return { added, removed };\n}\n```\n\nTwo details that are easy to get wrong:\n\n- **Schedule a re-check when the window expires.** \"Confirm on the next poll\"\n never fires: after a deletion the server data stops changing, so there may be\n no next poll. The timer has to be explicit.\n- **`onblocked` must reject, not hang.** Another tab holding an old connection\n will otherwise wedge the open forever.\n\n### 4. Archive (the second half of the request)\n\nSessions get **reset in place** — VS Code reuses the `sessionId` and truncates\nthe file. A copier that mirrors the source loses everything that was there:\n\n```python\nsrc_turns = len(replay(src).get(\"requests\") or [])\narch_turns = len(replay(archived).get(\"requests\") or []) if exists(archived) else 0\n\nif arch_turns and src_turns \u003c arch_turns:\n # Source was reset. Keep the archive as-is (append-only), and save the\n # post-reset content beside it so both survive.\n side = f\"{sid}.reset-{creation_stamp}.jsonl\"\n if src_turns > side_turns: # keep the longest post-reset version\n copy(src, side)\nelse:\n copy(src, archived)\n```\n\nRendering each session to Markdown next to the raw `.jsonl` costs little and\nmakes the archive greppable. If you do that, note that model output frequently\ncontains unbalanced code fences; the archive has to close them itself or one bad\nanswer swallows the rest of the file. CommonMark rules apply — a closing fence\nmust be at least as long as the opener and carry no info string.\n\n## Notes from a working implementation\n\nI built both as an injected script plus a small server-side daemon, and have run\nit for a while on two code-server instances (562 session files, ~204 MB). A few\nthings that might save someone time:\n\n**Rebuilding the index is cheap if you cache by mtime.** Full rebuild over all\nsessions was ~1.7 s; with a `(size, mtime_ns)` cache the steady state is\neffectively free. Doing it unconditionally on a timer is what makes it expensive.\n\n**Watch out for typing.** VS Code appends an `inputState` op on *every\nkeystroke*, so the session file changes constantly while the content that matters\ndoes not. Reacting to raw file changes cost ~29 % CPU and rewrote megabytes per\nminute. Deriving a content signature — `(turns, last timestamp, response part\ncount, total characters)` — and skipping when it's unchanged brought that to\n~7 % and zero writes.\n\n**Push beats polling.** With `inotify` + SSE, a change is visible in other\nbrowsers in ~100 ms. Also worth handling the degraded path explicitly: when\n`inotify` is unavailable (instance limits are easy to hit when several\ncontainers share a host), falling back to a *real* poll loop matters — falling\nback to a 60 s safety rescan quietly makes sync 60× slower with no visible\nsymptom.\n\n**Snapshot ops.** `.jsonl` sessions are op logs: `kind: 0` is a full snapshot,\n`kind: 1` sets a key, `kind: 2` appends to an array (this is how streamed\nresponses arrive). Replaying needs all three; handling only snapshots silently\nloses in-flight answers.\n\n**Truncated files.** A file written when the process is killed raises\n`EOFError` / `zlib.error` on *read*, and neither is an `OSError` — a single bad\nfile can take down a whole pass if the handler is too narrow.\n\nI'm happy to open a PR for either piece, or to share the implementation if\nthat's more useful than a patch. Also happy to be told this belongs upstream in\n`microsoft/vscode` instead — my read is that it's specific to the web/remote\ndeployment shape that code-server has, which is why I'm raising it here.","author":{"url":"https://github.com/NevermoreN","@type":"Person","name":"NevermoreN"},"datePublished":"2026-08-14T12:24:58Z","url":"https://github.com/coder/code-server/issues/7948"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:f58e12f1-b1d2-4365-8f31-07bdcbec9ed4 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | A404:1525E:A435FA:E5E988:6B042EC7 |
| html-safe-nonce | 3879900cc2a8cd94fc1d1ea4e27dd2a352088749b83f20fc035dc5d831fe2de0 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBNDA0OjE1MjVFOkE0MzVGQTpFNUU5ODg6NkIwNDJFQzciLCJ2aXNpdG9yX2lkIjoiNTE4MDA3OTk4MjEzMDc2OTYwNyIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 385ec5d2216abf95cf6847667e5af236e5148c63a4ef8a36c02b9cebf7f352a9 |
| hovercard-subject-tag | issue:5151551970 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/coder/code-server/7948/issue_layout |
| twitter:image | https://opengraph.githubassets.com/067ad24887316df42c419352e1e3e53ffae3d1555ba471d8a6e8f71c54fe7405/coder/code-server/issues/7948 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/067ad24887316df42c419352e1e3e53ffae3d1555ba471d8a6e8f71c54fe7405/coder/code-server/issues/7948 |
| og:image:alt | Summary Chat session content already lives on the server, but the index that makes sessions visible lives in the browser's IndexedDB. The result is that chat history is silently browser-local: open... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | NevermoreN |
| hostname | github.com |
| expected-hostname | github.com |
| None | b7a1d2b9101496921b08579fbee988d014345aef2f5bd660d1f8c7332d81560e |
| turbo-cache-control | no-preview |
| go-import | github.com/coder/code-server git https://github.com/coder/code-server.git |
| octolytics-dimension-user_id | 95932066 |
| octolytics-dimension-user_login | coder |
| octolytics-dimension-repository_id | 172953845 |
| octolytics-dimension-repository_nwo | coder/code-server |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 172953845 |
| octolytics-dimension-repository_network_root_nwo | coder/code-server |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | c3dd496c3da6ea6b77e69c09279d2b81604654f1 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | max-age=0, private, must-revalidate |
Viewport: width=device-width