Repository navigation
#1057 Release closed sessions' transcripts on both platforms - #1060
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]>
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]>
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]>
A session's in-memory transcript (messages, parts, raw info, last published frame, history window, shared-flow replay and its share coroutine) is now reference-counted on the store observation. Once nothing observes it, the three most recently closed sessions stay warm for two minutes and the rest are released (TranscriptRetentionPolicy, same names and values on Android and iOS). Memory pressure (Android onTrimMemory/onLowMemory, iOS memory warning) releases every closed session at once, and clearCache() now stops the share coroutines so nothing stays reachable through a replay buffer. A released session re-opens like a first open: session cache paint, then the server. A loop that was stopped or released can no longer commit a late REST page. On iOS a release also drops the session's prepared history. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ed-sessions # Conflicts: # android/app/src/main/java/dev/opencode/mobile/domain/message/store/MessageSync.kt # android/app/src/main/java/dev/opencode/mobile/domain/sessioncache/SessionCacheCodec.kt # android/app/src/main/java/dev/opencode/mobile/ui/sessionchat/SessionToolGroupViewModel.kt # android/app/src/test/java/dev/opencode/mobile/domain/sessioncache/SessionCacheMessageBudgetTest.kt # android/app/src/test/java/dev/opencode/mobile/ui/sessionchat/SessionToolGroupRouteTest.kt # ios/OpenCode Mobile/OpenCode Mobile/Domain/SessionCache/SessionCacheCodec.swift # ios/OpenCode Mobile/OpenCode MobileTests/Domain/SessionCache/SessionCacheMessageBudgetTests.swift
There was a problem hiding this comment.
Automated review: no finding that 2+ of 2 passes agreed on.
5 finding(s) from a single pass, not posted
android/app/src/main/java/dev/opencode/mobile/domain/message/store/MessageSync.kt:254high: Late loadOlder commits after dropSession and resurrects released transcript (muse-spark-1.3-contributor)ios/OpenCode Mobile/OpenCode Mobile/Domain/Message/Store/MessageSync.swift:253high: Late loadOlder commits after releaseTranscript and resurrects released transcript (muse-spark-1.3-contributor)ios/OpenCode Mobile/OpenCode Mobile/Domain/Message/Store/MessageSync.swift:151medium: Reopen during release runs two message loops that both apply the same live delta (muse-spark-1.3-contributor)android/app/src/main/java/dev/opencode/mobile/domain/message/store/MessageSync.kt:992medium: Split-turn backfill checks stillCurrent before the fetch, then commits into a released session (deepseek-v4.1-flash)ios/OpenCode Mobile/OpenCode Mobile/Domain/Message/Store/MessageSync.swift:283medium: Release drops MessageSync state under lock but clears the store after unlocking, racing a reopen (deepseek-v4.1-flash)
opencode pr-review · passes: muse-spark-1.3-contributor, glm-5.3-flash, deepseek-v4.1-flash · $0.115 · 1 pass(es) failed
|
bugbot run |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 3 potential issues.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 0b3924b. Configure here.
Device check (#1057, combined with #1061)Real apps against the scenario harness on a v2 server only (opencode 2.2.5; no v1 binary on the machine, so only Sessions: Android heap
Release timing, from the log line: from the 4th closed child on, each close released the oldest warm child at once (cap of 3). The last 3 were released exactly 120 s after each one closed. The parent stayed open throughout (more than 12 minutes, with children opened on top of it) and was never released. A closed session was released when the app went to the launcher ( Behaviour
Note for the running turn (v2): the server returns an empty text part for a step that is still streaming. So on re-entry after release, the reply shows only the cached paint plus what streams after re-entry (screenshot 3 shows "Progress 2 of 8." while the server was at 6). When the step finished, the text was complete and in order, with nothing duplicated (screenshot 4). This matches "re-enter = first open", but on Not checked: Android re-entry, Android running-turn re-entry and Android Home status. The device tool kept refusing touch injection on the emulator after a reinstall. Also not checked: offline re-entry, the tool-group and activity-card keep-alive, and the iOS memory warning, which were dropped from scope (they are unit-tested).
TestsCI |





Part of #1057: the three items about releasing closed sessions' transcripts. The diff view, Changes and File Viewer items are handled separately.
Builds on #1051 (merged); this branch is merged with
main.Problem
Device check of #1051 on an Android emulator with a 192 MB Java heap: after opening and closing 10 heavy child sessions, 94 MB stays live. About 75 MB of that is tool input strings that the message store holds for the parent and the 10 children. With the heap in that state, opening two more heavy screens ran the app out of memory.
On Android, closing a session's screen never released its transcript. Each
observeMessagesshareIn(replay 1) kept its share coroutine and replay buffer alive in the app-lived scope. That is also whyclearCache()freed nothing. iOS also kept each closed session's store, last frame and history window, plus up to 8 sessions of prepared history (capped by text length only, not tool output).Policy (same on both platforms)
TranscriptRetentionPolicy(Androiddomain/message/store/TranscriptRetentionPolicy.kt, iOSDomain/Message/Store/TranscriptRetentionPolicy.swift):CLOSED_SESSION_GRACE_MS/closedSessionGraceMs= 120 000 (2 minutes)MAX_WARM_CLOSED_SESSIONS/maxWarmClosedSessions= 3A session stays loaded while anything observes it. That covers its Session Chat anywhere on the back stack, a tool-group screen, and a parent's activity card watching a running child. All of these read the same
observeMessagesstream. When the last observer stops, the session stays warm for the grace period, and only the 3 most recently closed sessions stay warm; older closed sessions are released at once. On memory pressure (AndroidonTrimMemoryat the levels the highlighter already trims on, andonLowMemory; iOS memory warning) every closed session is released at once and open sessions are left alone.Mechanism
MessageSyncreference-counts collectors per session. Each session'sshareInnow runs in its own child scope, so a release cancels the share coroutine (which frees the replay buffer) and then drops the last frame, identity, history window, health and the cache handle. The store side isInMemoryMessageStore.release(slot), which drops base messages, parts, raw infos, orders, revisions, delta chunks and running context.clearCache()also cancels every share scope.TranscriptMemoryPressureObserveris registered fromOpenCodeMobileApplication, the same way as the TextMate trim observer.MessageSynccounts observers when the stream is created and inonTermination. A release callsfinish()on the session'sSharedLiveObservation, which cancels the upstream and clears its last value, drops the same per-slot state, and callsInMemoryMessageStore.release(sessionID:).DisplayMessagePipelinedrops the session's prepared history when its transcript is released. Its existing memory-warning observer now also callsreleaseClosedSessions().isActiveguard on the coordinator loader and the split-turn backfill. On iOS each loop gets a run token, checked before a commit or publish.Live events for a released session
Both platforms apply transcript events only inside an active observation's message loop. That holds for v1
/global/eventand instance/eventand for v2/api/event, which all feed the same foreground stream. Once a session is released, its events are dropped, the same as for a session that was never opened. They do not rebuild a partial transcript. Home status, permissions and questions live in their own stores, which keep their own subscriptions and keep updating (there is a test for this on each platform).Re-entry
A released session opens exactly like a first open: it paints from the session cache, then confirms or replaces that paint from REST. Within the grace period it still paints the held transcript at once, as before.
Checks
./gradlew :app:testDebugUnitTest(3405 tests, 0 failures),:app:assembleDebug,:app:assembleDebugAndroidTest.ktlintCheckreports nothing in the changed files.xcodebuild buildandbuild-for-testingforgeneric/platform=iOS Simulator(OpenCode Mobile), plusbuildfor Hex Code. The new iOS tests were compiled but not run: no simulator was available.MessageSyncTranscriptReleaseTest, iOSMessageSyncTranscriptReleaseTests, plus one status-store test each). The grace period runs on virtual time on Android and on a manual sleeper on iOS. The cases:clearCache()with open and closed sessionsobserveMessages(...).first()and then loaded older pages on a session nothing observed any more. They now keep the screen open while loading, as the app does.Risks / Follow-ups
Device checks still needed:
Other notes:
TRIM_MEMORY_UI_HIDDEN, when the app goes to the background, because that level already counts as Moderate pressure for the highlighter.🤖 Generated with Claude Code
Open in [code]smith · Need help on this PR? Tag
@codesmith-botwith what you need.Note
Medium Risk
Touches core message sync, caching, and memory lifecycle; wrong retention could drop live data or cause extra reloads, but open sessions and explicit guards limit exposure.
Overview
Adds transcript retention and release on Android and iOS so closed sessions stop holding large in-memory message state (tool inputs, share/replay buffers, prepared history).
Shared policy (
TranscriptRetentionPolicy): transcripts stay while any UI still observesobserveMessages; after the last observer leaves, the 3 most recently closed sessions stay warm for 2 minutes, older closed sessions drop immediately; memory pressure releases all closed sessions at once.MessageSyncnow reference-counts observers per session, cancels per-session share/observation scopes on release, and clears sync maps plusInMemoryMessageStore.release/ engine state. Late REST commits are blocked once an observation is released (mayCommit/ run tokens). Re-opening a released session behaves like a first open (cache paint then server); reopen within grace still paints the held transcript.Android:
TranscriptMemoryPressureObserverregistered from the application class (trim levels aligned with TextMate). iOS:DisplayMessagePipelineevicts prepared history on transcript release and callsreleaseClosedSessions()on memory warning.Wide mirror tests on both platforms; some older Android tests now keep an active observer while loading older pages.
Reviewed by Cursor Bugbot for commit 0b3924b. Bugbot is set up for automated code reviews on this repo. Configure here.