CrewCode stores replayable agent conversation history as per-session files under Electron userData:
~/.config/crewcode/conversations/
agent-conversations.<stable-session-digest>.jsonEach file contains one conversation using the same wrapper shape as the legacy monolith, but with only one session key:
{
"conversations": {
"workspace-tab-agent conversation key": [
{ "role": "user", "content": "..." },
{ "role": "assistant", "content": "..." }
]
}
}Older shards written as { "sessionId": "...", "messages": [...] } are still readable and are rewritten to the legacy wrapper shape on load.
The legacy monolithic file remains supported for migration:
~/.config/crewcode/agent-conversations.jsonOn first access, CrewCode copies legacy entries into sharded files and writes conversations/.agent-conversations-migrated. The legacy file is left in place as a backup, but new saves use only the per-session files.
If a sharded file is missing or unreadable, CrewCode can lazily recover that session from the legacy monolith. Explicitly cleared sessions are recorded in conversations/.agent-conversations-cleared.json so legacy fallback does not resurrect deleted conversations.
Remote browser replay history remains authoritative on the Brain, not in browser localStorage. The shared renderer supplies an opaque chat session id; the remote boundary namespaces it as web:<session> before AgentBridgeService reads or writes the same per-session conversation shards described above. This keeps desktop thread: keys and browser keys from aliasing each other.
Cross-thread browser handoff is a bounded Brain-side operation. The browser names a source chat and an already-owned destination bridge, but never downloads the source replay shard. The Brain summarizes the source with a disposable destination-provider bridge, appends only the resulting handoff packet to the destination shard, clears the destination's native resume id, and replays the combined destination history once on its next native-provider prompt. Stateless HTTP providers consume the updated shard directly. Missing source history, summary failure, a running destination, or lost destination ownership is an explicit failure and is never inferred as success.
src/main/agents/sessionStore.ts persists per-session bridge state under userData/agent-sessions.json, keyed by the tabId:agentId composite the renderer uses for bridge registration:
{
"sessions": { "tab:agent": "<upstream session id>" },
"usage": { "tab:agent": { "contextTokens": 42000, "contextWindow": 200000, "model": "claude" } }
}-
sessions— the upstream/provider-native resume id, written as soon as a bridge reports one so a crash mid-conversation still leaves a resumable session behind. -
usage— a minimal snapshot of the last known context usage. The context meter is rendered per agent bubble fromusage.contextTokens / usage.contextWindow, and the running floor that keeps that number monotonic (entry.lastUsage, applied bynormalizeContextUsage) is otherwise in-memory only. Without this snapshot a resumed session has no baseline, so the first new turn reports a tiny per-turn count and the meter collapses to ~0 even though the conversation context is unchanged. Onbridge:startthe entry seedslastUsagefrom this snapshot; everyturn_end/usage_updatewrites it back. This is provider-agnostic — it fixes the resume reset for Claude, Codex, OpenCode, pi, Ollama, OpenRouter, Hermes, and CrewCoder alike.contextTokensis an absolute/cumulative measure (each turn'sinputre-sends the whole conversation). When a turn under-reports it (a dip below the prior baseline — common on the first resumed turn),normalizeContextUsageholds the baseline and adds only the new output tokens. It must never addinput, or the re-sent history double-counts and the meter balloons (~35% → ~65% on the first resumed reply). The result is also capped atcontextWindow.
Both maps are cleared together when a session is explicitly reset (bridge:resetSession → clearSessionId), so a deliberate new session starts the meter fresh.
/compact is intercepted in useComposerSend and routed to the bridge:compact IPC (it is not sent as a normal prompt). The handler picks a strategy via compactionStrategy() and only the unsupported case returns { ok: false, unsupported: true } (UI shows a "doesn't support /compact yet" notice) rather than letting the agent answer the literal string /compact.
| Provider | Strategy | Mechanism |
|---|---|---|
| codex | native |
ACP thread/compact/start |
| opencode | native |
POST /session/:id/summarize (server-side) |
| claude | native |
/compact slash command via the Agent SDK → compact_boundary event |
| plugins | native |
plugin bridge compact() (local summary prompt) |
| ollama / openrouter (HTTP_ONLY) | local-summary |
LOCAL_COMPACT_PROMPT + compactLocalConversation replaces our owned replay history |
| pi / hermes / CrewCoder | summary-reset |
no native RPC → the agent summarizes its own live context, then we seed a fresh session with it (below) |
| any provider with no thread/conversation key | unsupported |
nowhere to persist a summary; reported instead of faked |
Native-session providers keep their context server-side and expose no compaction RPC, so we cannot shrink it directly. Instead:
bridge:compactsendsSUMMARY_RESET_PROMPT(the structured GOALS / KEY DECISIONS / PROGRESS / OPEN QUESTIONS / NEXT STEPS template) as a normal turn while the provider still holds the full live context, and setsentry.pendingSummaryReset. The prompt is pushed ontopendingPromptTextsso the turn is recorded into the replay shard. The summary streams back as a visible agent bubble.- On that turn's
turn_end(summary already recorded), the handler:compactLocalConversation()collapses the replay shard to[continue, summary];clearSessionId()drops the upstream resume id (and its usage snapshot); the replay marker is deleted;entry.lastUsageis cleared. - The bridge is torn down via the idle-stop path (
idle_stopped→ renderer drops its keys silently, no "agent exited" noise). Teardown + thecompletedevent are deferred to aqueueMicrotaskso ordering staysturn_end → completed → idle_stoppedand the bridge is never stopped re-entrantly from inside its own event. - The next prompt calls
bridge:startwith no resume id but local history present →injectHistoryOnNextPromptre-arms → the summary is injected as<conversation_history>into a fresh, small upstream session.
History note: previously every provider without a native
compact()fell through toprompt('/compact'). Codex/HTTP-only/plugins worked, but pi/hermes/opencode/claude received the literal string/compact, which the agent simply answered. opencode and claude now compact natively; pi/hermes/CrewCoder use summary-reset.
The rich UI thread (the full renderer Message[] — user/agent/thinking/toolcall/system bubbles with timestamps, turn ids, tool-call state) is not the same as the agent replay history above. Replay shards store only { role, content } for rebuilding model context; transcripts store everything the chat surface renders. The transcript is persisted in two layers:
src/main/transcript-store.ts writes one file per scope under Electron userData:
~/.config/crewcode/transcripts/
transcript.<scope-digest>.json → { "scopeId": "...", "messages": [ ...full Message[]... ] }Messages are stored opaquely — the main process never inspects their shape, so the renderer Message type stays renderer-only. IPC surface: transcripts:loadAll, transcripts:save, transcripts:remove, and a synchronous transcripts:saveSyncBatch used only on window teardown (an async invoke can be dropped before the renderer dies, so the last turn is written synchronously).
src/renderer/src/stores/chat-messages-store.ts keeps a synchronous localStorage copy so the transcript paints instantly on launch. localStorage has a hard ~5MB per-origin quota; the cache therefore caps each scope's tail (MAX_PERSISTED_MESSAGES_PER_SCOPE) and, on QuotaExceededError, evicts the least-recently-touched scopes so the newest conversation always wins the remaining space.
History note: the original bug was
persist()silently swallowingQuotaExceededError. Once the unbounded map crossed the quota, every new turn's write failed silently — old conversations (already on disk) survived, new ones vanished on restart. Do not reintroduce a silent quota catch, and do not treat localStorage as the source of truth.
- Launch: L1 paints from localStorage immediately; the store then hydrates from L2 (
transcripts:loadAll), backfilling any scope L1 evicted and restoring full history for scopes L1 trimmed. Hydration never clobbers an in-memory scope that is already longer (a turn that arrived during the async load wins). - Writes: L2 disk is authoritative and writes changed scopes promptly (settled/structural changes immediately; in-progress token deltas debounced). L1 localStorage is only a fast-paint cache and is refreshed during idle/debounce/teardown so large
JSON.stringifywork does not block composer typing or sidebar interactions. Both layers flush onpagehide/beforeunload/hidden visibility (L2 via the synchronous batch). - Deletion: explicit session deletion (
removeSession) callstranscripts:removeso a deleted thread doesn't resurrect from L2. The startup reconciliation prune deliberately does not delete disk files.