Skip to content

Desktop: switching chats is slow because every switch re-reads the whole transcript and decodes inline base64 images (59-62% of the file); git probe blocks render #1176

Todo

Description

@xtalia

Summary

Switching to another chat in a project gets slow in proportion to that session's size, because roughly 60% of the bytes in the slow sessions are inline base64 images embedded in tool_result parts that are re-decoded and re-laid-out on every switch, and because the resident-chat cache is a count-based LRU sized 8 — smaller than the working set — so most switches miss it and re-read and re-parse the entire .jsonl transcript.

Three independent costs stack up before content appears:

  1. On a cache miss, full transcript read + parse + IPC transfer.
  2. Inline base64 images in tool_result content (59–62% of the file in the affected sessions), paid even on a cache hit.
  3. A serialized git round-trip (gitListBranches(..., {fresh:true}), then possible gitCheckoutBranch / gitCreateWorktree) that must finish before the chat renders.

Expected Behavior

  • Switching between chats that are in active rotation should not re-read and re-parse the whole transcript from disk each time. Either the resident set should cover the working set, or the cache should be byte/memory-bounded rather than count-bounded at a fixed 8.
  • Large tool payloads (images, screenshots) should not be stored as inline base64 inside the transcript, or at least should be materialized to files and referenced, so switching and rendering do not pay for them repeatedly — on cache hits too.
  • The git branch check on switch should not block rendering the conversation, and should not run git at all when the thread has no gitBranch.

Actual Behavior

Measured on a real profile (Windows, desktop 0.1.63). Session fd22777b-… (UI And Engine Tasks, project C:\Users\sergsinist\.hermes\interestingthings):

fd22777b-…jsonl — 13.04 MB, 1615 lines, 1613 messages, 965 tool_result parts.

Standalone Node timings for the work session-load performs on a cache miss:

Step Time Notes
readFileSync (13.04 MB) 43 ms
split('\n') 15 ms 1615 lines
JSON.parse per line 31 ms
JSON.stringify payload for IPC 44 ms 13.04 MB out
parse-back (IPC clone approximation) 21 ms

That is ~150 ms of pure CPU in one process, paid twice (main → renderer over structured clone of 13 MB) per cache miss.

Correcting an earlier version of this report: there is a cache, and it is count-bounded at 8.

The renderer keeps materialized threads in memory and evicts with LRU. In workspace-screen-*.js:

const Hue = 8, aP = globalThis.window?.electronAPI?.residentChatLimit ?? Hue;

function Bue({threads, activeThreadId, streamingThreadIds, recentlyUsed, limit = aP}) {
  const a = threads.filter(h => (h.messages?.length ?? 0) > 0 && Ql(h));
  if (a.length <= limit) return [];
  // oldest first by recentlyUsed; never evict the active thread, a streaming
  // thread, or one with a live background sub-agent (zue)
  const c = [...a].sort((h, p) => (recentlyUsed.get(h.id) ?? -1) - (recentlyUsed.get(p.id) ?? -1));
  ...
}

Eviction (lP) does not delete the chat — it strips the payload and keeps the "there is a transcript" marker, so the chat is re-loadable on demand:

{...oP(e, t), messages: [], hasTranscript: true}   // Vue()

The main process enforces the same idea independently, with the limit derived from RAM and hardcoded:

function zw(e) { return e <= 8 * 2 ** 30 ? 3 : 8; }   // ≤8 GB → 3, else 8
const BY = zw(Pw());                                   // Pw = os.totalmem()
async function qY() {
  if (!HY()) return;                                   // HY = !DISABLE_SESSION_EVICTION
  for (; W.size > BY; ) { /* evict LRU by lastUsedAt, skip busy/pinned */ }
}

There is also a second, content-driven release path: SESSION_RELEASE_IDLE → VA() in main, driven from the renderer by rde(), which releases sessions whose on-disk feed changed underneath (message count / activity changed and not currently being written). Evicted chats come back through sessionLoad, and the load guard $7 re-issues a load when a thread has a transcript but no materialized messages (attempt counter capped at 5).

So the mechanism the report originally asked for already exists. The problem is that the bound is a small fixed count, not the working set or memory:

  • On the measured profile, thread-index.db has 19 rows, 18 with has_transcript = 1, against a limit of 8.
  • Walking the sidebar therefore misses the cache on most switches and pays the full read + parse + IPC for a multi-MB transcript.
  • The limit is not user-configurable: residentChatLimit is injected by main as additionalArguments: ["--resident-chat-limit=" + zw(os.totalmem())], so the number comes from installed RAM (3 or 8) and a command-line flag in a shortcut is ignored. The only real switch is CC_DISABLE_SESSION_EVICTION=1 / CMD_DISABLE_SESSION_EVICTION=1, which disables eviction entirely and leaves memory unbounded.

Inline base64 is the dominant term — and it is paid even on a cache hit. Lines containing base64 account for the bulk of these files:

Session Size base64 bytes Share
fd22777b-… 13.04 MB 7.67 MB (19 lines, 23 images) 58.9%
be229483-… 5.03 MB 3.12 MB 62%
1594e4f1-… 2.79 MB 1.66 MB 59%
f6f17b63-… 2.02 MB 0 MB 0%

f6f17b63-… is the control: same order of magnitude in size, zero base64, and it switches dramatically faster — the slowdown tracks base64 content, not line count.

A single record concentrates the worst case: one message record is 1.83 MB, containing three tool_result parts of 539.7 KB / 618.3 KB / 672.1 KB, each of the shape:

{ "type": "tool_result", "tool_use_id": "call_…",
  "content": [ { "type": "text", "text": "…" },
               { "type": "image", "source": { "type": "base64",
                 "media_type": "image/jpeg", "data": "/9j/4AAQSkZJRg…" } } ] }

Those images stay resident as base64 in memory and are decoded and laid out again on every switch into that chat, cache hit or not.

Git round-trip blocks the switch. The switch handler runs the workspace claim first and only then shows the conversation. For a thread with git_branch set, it calls gitListBranches(path, { fresh: true }), and if the current branch differs it calls gitCheckoutBranch or creates a worktree. Measured on E:\gitreps\chizhik-menu: git branch 56 ms + git status --porcelain=v2 64 ms ≈ 120 ms per switch just for the branch probe. A branch mismatch (or dirty tree) escalates to worktree creation, which writes to disk and takes seconds. Threads in non-git project paths return early and do not pay this.

Supporting state store is unmaintained. thread-index.db is 16 KB (page_count = 4) with a 4.12 MB -wal that is never truncated, so every connection replays it. integrity_check is ok and the 19 thread rows are intact — this is a maintenance gap, not corruption, and its impact is small next to the transcript cost.

Steps to reproduce the issue

  1. Build up a long chat in which the agent reads or views images, so the transcript contains inline base64 tool_result content (check with Select-String -Pattern '"base64"' on %USERPROFILE%\.commandcode\projects\<slug>\<id>.jsonl).
  2. Have more chats with content than the resident limit (more than 8 on a >8 GB machine, more than 3 on a ≤8 GB machine).
  3. Switch between a few of them; observe the pause before the conversation renders.
  4. Compare against a session of similar size but with no base64 in it — it switches noticeably faster.
  5. For the git part: switch to a chat whose git_branch in thread-index.db differs from the branch currently checked out in the project folder; the switch waits on git before rendering.

Command Code Version

0.1.63 (desktop, packaged: true; ProductVersion 0.1.63.0)

Operating System

Windows

Terminal/IDE

Command Code desktop app (Electron), launched from the Start Menu shortcut — not a terminal session.

Shell

N/A (desktop app)

Session file (optional)

The 13 MB transcript is private; I can share redacted structure (record shapes, byte offsets, base64 share) or the file itself on request.

Fix prompt (optional)

Three changes, in impact order.

  1. Move image payloads out of the transcript. In the session writer, persist tool_result image content as a file under a per-session asset directory and store a reference ({type:"image", asset:"…png", bytes, mediaType}) instead of base64 in data. On load, resolve references lazily in the renderer so an image is decoded only when it enters the viewport, and never hold decoded bytes for threads that are not on screen. For existing transcripts, a migration that extracts source.data to files and rewrites those records would shrink the current 13 MB file by ~59% with no user-visible change. This is the highest-impact change because it also helps cache hits and the main-process RSS.

  2. Make the resident bound match reality, and bound it by bytes rather than count. Bue()/lP() and qY()/BY currently cap the resident set at a hardcoded 8 (3 on ≤8 GB machines), which is below the working set on this profile (18 threads with a transcript). Either expose --resident-chat-limit / a setting that main actually honors instead of overwriting it with zw(os.totalmem()), or replace the count cap with a byte budget (e.g. total resident message bytes) so a few large chats and many small chats are treated sensibly. Keep the existing safety rules from WY/zA (never evict the active thread, a running/streaming session, one awaiting a permission answer, or one with live background sub-agents).

  3. Do not block rendering on git. In the switch handler (vee in workspace-screen-*.js), render the conversation as soon as the transcript is available and run the branch probe/checkout afterwards; skip the probe entirely when thread.gitBranch is empty. Cache gitListBranches results for a short TTL instead of {fresh: true} on every switch.

Verify by: asserting that a second switch to the same chat performs no transcript read when it is inside the resident set, that a base64-heavy session's .jsonl no longer contains inline source.data, and that the chat frame paints before any git subprocess completes.

Additional context

Distinct from the two issues filed earlier in this run (#1174 state-write EPERM / orphaned turn; #1175 hotkey warnings and backup schema drift) — this is purely the session-switch latency path. Related closed issue #925 covers a main-process crash on output-heavy turns; the large tool_result payloads here are the same kind of heavy output, so a cap on inline tool payload size would help both.

Activity

  1. vipulgupta2048 commented on Nov 24, 2026

    @vipulgupta2048
    Member

    Thanks for the detailled issue report, I will make sure this reaches our team and the issue gets fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions