Repository navigation
#1033 Keep tool output out of Session Chat projection, route keys and cache flushes - #1051
Conversation
… cache flushes Session Chat ran out of memory on Android with long sessions. Three causes: - Every timeline projection built a per-line inspector body for every tool card and copied each output into the card. Cards now keep only what the collapsed row draws and a flag; the detail (body and inspector) is built from the tool part when it opens. A write's +N is counted, not split. - The tool group navigation key carried every member's output and inspector lines, and Navigation3 prints and saves the key. It now names the members by block id; the route reads them from the message store. - The session cache encoded the whole transcript into one string and swallowed the OutOfMemoryError. It now encodes one message at a time and keeps the newest whole messages within about 2 MB; Errors propagate. iOS: the tool card keeps the classifier inputs (shared string storage) and classifies on open; the write line count no longer splits; the cache encode uses the same per-message budget. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@cursor review |
There was a problem hiding this comment.
Automated review: no finding that 2+ of 2 passes agreed on.
1 finding(s) from a single pass, not posted
android/app/src/main/java/dev/opencode/mobile/domain/sessioncache/SessionCacheCodec.kt:80medium: Newest message is always encoded whole, so a single huge message still builds the 70 MB flush allocation the fix targets (deepseek-v4.1-flash)
opencode pr-review · passes: muse-spark-1.3-contributor, glm-5.3-flash, deepseek-v4.1-flash · $0.141 · 1 pass(es) failed
Android's cursor window holds 2 MB, so a session cache row larger than that throws SQLiteBlobTooBigException on read. Earlier builds wrote whole transcripts (4.3 MB for a heavy session), and commit and retain read the existing row first, so that row could never be replaced and the session never painted from cache again. - commit and retain read only the row's retain time and payload size. - load skips a row over the window instead of throwing. - The message timeline budget counts UTF-8 bytes, as SQLite stores them and as iOS already does, and stays under the window (1.8 MB). Co-Authored-By: Claude Opus 5.5 <[email protected]>
OpenCode emits each tool step as its own assistant message, and the timeline merges a run of them into one group under one message id. The route looked members up only in that message, so a 78-tool group opened with one member. Look each member up by block id across the transcript. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Device verification (#1033)Real apps against the scenario harness on a v2 server only (opencode 2.2.5; no v1 binary is installed, so v1 was not run). All content is generated filler from the throwaway Android: emulator, API 37, Java heap limit 192 MB, debug build with a local-only heap sampler (500 ms) that is not committed. iOS: simulator, iOS 27.2, Head verified: Android heap, before and afterSession sizes:
What owns the heap now (dump after iOS memory,
|
main (merge base 5561981) |
This PR | |
|---|---|---|
| Home | 70 MB | 71–78 MB |
oom-l, highest in the first 45 s |
138 MB | 109 MB |
oom-l settled |
138 MB | 108–109 MB |
Fixed during verification
0b5de7d92Android session cache rows over 2 MB could not be read or replaced. Android's cursor window holds 2 MB.mainwroteoom-mas a 4.3 MB row, and every read failed withSQLiteBlobTooBigException(retain opened,load messages). So onmain, heavy sessions never painted from cache at all. With this PR as first pushed,commitalso read the old row first, so the oversized row could never be replaced: no cached paint, ever, for any session cached by an earlier build. Nowcommitandretainread only the retain time and size,loadskips a row over the window, and the budget counts UTF-8 bytes (1.8 MB, as iOS already counts bytes). After upgrading frommain, theoom-mrow went from 4.34 MB to 1.80 MB and painted offline.38ef67fb2Android tool-group screen showed one member of 78. The timeline merges a run of tool-only step messages into one group, but the route looked members up only in the message whose id it carries. It now looks each member up by block id across the transcript.
Screenshots
Cold paint: oom-m shows the newest 22 steps offline on Android and 24 tools on iOS, then fills to the full timeline when the server answers. A small session (oom-s) paints in full from cache on both, and from a cache written by main on Android.
Still open (not changed here)
- A fatal Android OOM remains reachable. After opening the 10
oom-lchildren (94 MB live in the message store), opening the turn's Changes screen and a 1 MB file in the File Viewer took the heap to 191 MB and the process aborted (JNI DETECTED ERROR … pending exception java.lang.OutOfMemoryError). Tool details were not involved. The cause is the retained child transcripts plus the Changes/File Viewer load, neither touched by this PR. oom-xlcaches only its last message: the next-newest message is over 2 MB, so a cold paint before REST answers shows one message.- The collapsed timeline group for an interrupted run shows "Stopped" in red, while the member inside shows the gray interrupted style. This is the group's existing worst-status chrome.
Not checked: v1 protocol; the activity card while a subagent runs with large tool outputs (checked with small ones: heap flat at 14–25 MB for 45 s); a running tool's live detail (a running v2 shell carries no output in its tool part, so no detail opens until it settles, by the same rule as main).
A seed is only a first paint, but on Android an OutOfMemoryError from decoding an oversized legacy timeline row escaped seed() and aborted observeMessages before the live load ran. - seed() loads and decodes in a helper and reads any failure, including OutOfMemoryError and StackOverflowError, as a miss. The row and the decode's allocations are unreachable by the time it logs. - observeMessages guards seed() the same way, so no cache failure stops ensureFresh. - encodeMessages no longer always keeps the newest message: a message whose text alone is over the remaining budget is not encoded at all, and when the newest does not fit the timeline keeps none (a seed miss). One huge tool output no longer builds its whole JSON string for a row Android could not read back. - iOS: the pipeline characterization test waits longer for the first frame and no longer indexes emissions it may not have, so a slow runner fails the expectation instead of crashing the test host. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Behavior change in 31ffdee: the Android message timeline cache no longer always keeps the newest message. If the newest message's JSON is over the 1.8 MB timeline budget, the cache keeps no messages and that session opens without a cached first paint; it still loads live as usual. A message whose text alone is over the remaining budget is skipped without being encoded, so one huge tool output no longer builds its full JSON string during a flush. Seed failures, including The iOS |
|
/review |
|
bugbot run |
There was a problem hiding this comment.
Automated review: 1 finding(s) that 2+ of 2 passes agreed on.
Outside the diff lines:
ios/OpenCode Mobile/OpenCode Mobile/Domain/SessionCache/SessionCacheCodec.swift:69high: iOS always keeps newest message even when over budget
4 finding(s) from a single pass, not posted
android/app/src/main/java/dev/opencode/mobile/domain/sessioncache/SessionCacheCodec.kt:128high: Cache budget floor ignores tool input, huge write still encoded (muse-spark-1.3-contributor)android/app/src/main/java/dev/opencode/mobile/ui/sessionchat/timeline/SessionChatTimelineBlocks.kt:2065medium: detailRevision uses only lengths, same-length edits are invisible (muse-spark-1.3-contributor)android/app/src/main/java/dev/opencode/mobile/ui/sessionchat/SessionToolGroupViewModel.kt:58medium: Tool-group route ignores load failures and stays Loading forever (deepseek-v4.1-flash)android/app/src/main/java/dev/opencode/mobile/ui/sessionchat/ToolResultPresentation.kt:270low: hasResult says a write opens a detail that classify cannot build (deepseek-v4.1-flash)
opencode pr-review · passes: muse-spark-1.3-contributor, glm-5.3-flash, deepseek-v4.1-flash · $0.157 · 1 pass(es) failed
…l group - The pre-encode size floor counts tool input and metadata, so a large write is not encoded just to learn it does not fit. - iOS matches Android: the same floor before encoding, no always-kept newest message, and an empty cached timeline seeds as a miss. - The tool group route paints from cache only when the cached frame holds every member (the cache keeps only the newest messages that fit). It settles on what it has once the live load confirms the cached frame or fails, instead of loading forever. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
/review |
|
bugbot run |
A failed live load with none of the group in the cached frame left the route Loading forever on an empty group; it now goes back. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
/review |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 3fd64a7. Configure here.
There was a problem hiding this comment.
Automated review: no finding that 2+ of 3 passes agreed on.
5 finding(s) from a single pass, not posted
android/app/src/main/java/dev/opencode/mobile/ui/sessionchat/SessionToolGroupViewModel.kt:73high: Live window without the group forces Gone and pops the route (muse-spark-1.3-contributor)android/app/src/main/java/dev/opencode/mobile/ChatFlowEntries.kt:213high: Tool-group ViewModel keyed by session only is reused across groups (muse-spark-1.3-contributor)ios/OpenCode Mobile/OpenCode Mobile/UI/SessionChat/Timeline/SessionChatTimelineBlocks.swift:2964medium: Patch fallback scans the whole output per card on iOS (muse-spark-1.3-contributor)android/app/src/main/java/dev/opencode/mobile/ui/sessionchat/ToolResultPresentation.kt:270low: hasResult treats a write with empty content as opening a detail that toolDetail cannot build (deepseek-v4.1-flash)android/app/src/main/java/dev/opencode/mobile/domain/sessioncache/SessionCacheCodec.kt:560low: Cached timeline is dropped entirely when the newest message is over the budget, so an oversized newest message leaves the session with no cached first paint (deepseek-v4.1-flash)
opencode pr-review · passes: muse-spark-1.3-contributor, glm-5.3-flash, deepseek-v4.1-flash · $0.147 · 2 pass(es) stopped early




















Summary
Two fatal
OutOfMemoryErrors in Android Session Chat (#1033). The reproduction on a debug build ofmain, on an emulator with a 192 MB Java heap, found three causes. This pull request fixes all three on Android and makes the matching changes on iOS where the same cost exists.1. Eager per-line tool presentation (the biggest consumer)
Cause.
toToolCardcalledToolResultInspector.fromToolfor every tool on every timeline projection. That split each body into oneSourceLineper line; for awrite, the body is the whole uncapped file. A heap dump showed 416KSourceLines plus 520K small strings, about 70 MB of a 102 MB live heap, held byToolCard.presentation. One fatal stack ends inToolResultInspector.nonEmptyLines← … ←SessionChatTimeline.publishDisplayMessages.settledDetailalso copied each output into the card'sdetailText.Android change.
SessionChatTimelineBlock.ToolCardno longer haspresentation. A tool card leavesdetailTextnull (only the compaction summary still sets it) and carriesopensToolDetailanddetailRevision(lengths of output, error and written content, so the live activity-sheet detail is still rebuilt as a running tool's output grows).opensToolDetailcomes fromToolResultInspector.hasResult(tool), which reads the output only up to its first non-blank character, plus a check on the chrome detail that copies nothing.SessionChatTimelineBlocks.toolDetail(tool)from the tool part looked up at that moment (SessionChatToolDetails, reached throughLocalSessionChatToolDetailResolver). The Session Chat screen model provides it from the loaded transcript, and the tool group route from the store. The activity sheet builds it only for the open step.writecard's+Nnow counts newlines instead of splitting the content.2. Tool-group navigation key carried tool contents (fatal)
Cause.
SessionToolGroupheldSessionToolGroupMembers, each withdetailText(a full output copy) andpresentation(all its lines). Navigation3 callstoString()on the key (NavEntryKt.defaultContentKey), and the key is@Serializablesaved state. Tapping a 78-tool group needed one 76 MB allocation, which crashed the main thread inSessionToolGroup.toString.Android change.
SessionToolGroupnow carries ids only:sessionId,worktree,transcriptWorktree,parentId,blockID,messageId,owningTurnMessageId,memberBlockIDs, and the existing flags. It also keeps the boundedtitleandsubtitlethe top bar shows (count labels, or a single path or pattern).SessionToolGroupMemberand theSessionToolGroupImagesholder are gone.SessionToolGroupViewModelobservesMessageRepository.observeMessages(sessionId, transcriptWorktree). That is the same shared store flow Session Chat observes, so it adds no load. It projects the members with the sametoToolCardthe timeline uses.isInterrupted,noteTextand images for group members. Members resolved from the store now show an interrupted or declined member, its note and its images the way the timeline does, including after process death.3. Session cache encode
Cause.
DefaultSessionCache.flushLockedencoded the whole loaded transcript into one JSON string 3 s after the last update. On device it asked for one contiguous 70 MBchar[]; a JVM probe measured 5–8× the payload. TherunCatchingthere caught theOutOfMemoryErrorand logged it, leaving the heap at its limit.Android change.
SessionCacheCodec.encodeMessagesencodes one message at a time, newest first. It keeps the newest messages whose JSON fitsMESSAGE_TIMELINE_BUDGET_CHARS(2M chars, about 4 MB as UTF-16; it always keeps the newest message), then splices them into the unchanged envelope. Decode is unchanged.flushLocked,seedanddecodeMessagesnow catchException, notThrowable; anErrorand cancellation propagate.SessionCacheMessageEncoderis the test seam.MessageWindowMerge.applyTailkeeps seeded messages older than the REST tail, so a trimmed cached part would never be replaced.iOS: what I found and what changed
SessionChatToolCardBlockreplaces the storedpresentationwithresultRequest: ToolResultRequest?. These are the classifier's inputs, which share the tool part's string storage.presentationis now a computed property, read only when the detail opens.opensDetailgates the tap at render, andSessionChatStepTapActionsand the tool group view build the detail inside the tap closure. Before, they built it at render.classifyortrimmingCharacterson whole outputs.ToolResultInspector.hasResultandisBlankTextstop at the first non-blank scalar.components(separatedBy:), andsettledDetailreturns a single part as is, so it shares storage.detailTextand the carried strings: Swift strings share storage, so no copy is made.SessionChatToolGroupTargetis@State, hashed onblockIDonly, notCodableand never printed. With the presentation gone from the cards, its members hold only shared strings. No change.SessionCacheCodec.encodeMessagesbuilt the whole transcript as oneDataand then oneString. It now uses the same per-message newest-first budget (messageTimelineBudgetBytes, 2 MB of UTF-8). Swift cannot catch an out-of-memory condition, so there was no swallowedErrorto fix.Fixes #1033
Checks
./gradlew :app:assembleDebug :app:assembleDebugAndroidTestpassed. The full./gradlew :app:testDebugUnitTestran 3384 tests with 0 failures.ToolCardDeferredDetailTest: multi-MB write and shell cards print under 2,000 chars and hold no presentation; the detail built on open equals the old eagerfromToolresult;hasResultmatchesfromTool != nullover the fixtures;detailRevisionfollows a growing output.SessionToolGroupRouteTest:toString()and serialized size are identical for 1 KB and 5 MB outputs; the destination resolves the same members; the route goes back when the group leaves.SessionCacheMessageBudgetTest: an 8M-char transcript is encoded one message at a time into a payload within budget, keeping the newest messages whole; anOutOfMemoryErrorfrom the encode propagates out offlush(); an encode exception is still logged and skipped.SessionChatTimelineBlocksTest,SessionChatActivityCardTestandV2LiveTurnTimelineTestnow read the tool detail through the on-open path instead ofcard.detailText.xcodebuild buildandxcodebuild build-for-testingforgeneric/platform=iOS Simulatorboth succeed. On a simulator, 590 tests in 13 classes pass, including the newToolCardDeferredDetailTestsandSessionCacheMessageBudgetTests.Android emulator with a 192 MB Java heap, same seeded sessions as the reproduction on
main:mainSourceLineobjects after it settlesOutOfMemoryErroriOS simulator, heavy session open: 138 MB on
main, 108–109 MB here.Tool details (read, shell, grep, unknown, failed), the tool group screen, restore after process death, the route going back after a revert, and the cached first paint for a small and a heavy session pass on Android; details, the tool group screen and the cached paint pass on iOS.
Two defects found on device and fixed: Android cannot read a cache row over 2 MB, so a session cached by an earlier build stayed stuck (
0b5de7d92: oversized rows are skipped and replaced, and the budget counts bytes, 1.8 MB); and the tool group screen listed one member of a 78-tool group because members were looked up in one message only (38ef67fb2).The full Android unit suite on the final head: 3,389 tests, 0 failures.
Risks / Follow-ups
main; a v1 server. The running-subagent check on Android used small child outputs only.Follow-up, not in this pull request: release a session's transcript from
MessageSync/InMemoryMessageStoreafter its screen closes (about 5 MB per visited child session). Also left out: the 32 MB full-image cache and page sizes.🤖 Generated with Claude Code
Open in [code]smith · Need help on this PR? Tag
@codesmith-botwith what you need.Note
Medium Risk
Large behavioral change across session message caching, navigation/saved state, and tool UI loading paths; regression risk in cold-cache first paint, tool groups, and offline sessions despite broad tests.
Overview
Addresses #1033
OutOfMemoryErrorcrashes in Session Chat by keeping large tool output out of timeline projection, navigation state, and cache writes.Timeline and tool details (Android + iOS). Tool cards no longer carry eager
presentation/ per-line inspector bodies or fulldetailTextcopies during projection. They exposeopensToolDetail(or iOSresultRequest) and build detail on tap viaSessionChatToolDetails/LocalSessionChatToolDetailResolver. Projection uses cheap checks likeToolResultInspector.hasResultand newline counting instead of splitting megabyte tool bodies.Tool group route (Android).
SessionToolGroupnavigation keys now store onlymemberBlockIDs(plus metadata), not fullSessionToolGroupMemberpayloads.SessionToolGroupViewModelresolves members fromMessageRepositoryand navigates back when the group disappears;SessionToolGroupImagesis removed.Session cache (Android + iOS). Message timeline encoding is budgeted (
encodeMessageskeeps newest whole messages under ~1.8–2 MB UTF-8). Cache seed / flush failures (includingOutOfMemoryError) are treated as misses without aborting live loads. Room addsmeta/setRetainedAtto skip or replace rows exceeding the SQLite cursor window.Extensive unit tests cover budget encoding, oversized cache rows, deferred tool detail, and the slim tool group route.
Reviewed by Cursor Bugbot for commit 3fd64a7. Bugbot is set up for automated code reviews on this repo. Configure here.