Skip to content

Lay out diffs lazily and bound Changes and File Viewer memory - #1061

Merged
ivanfenenko merged 2 commits into
mainfrom
fix/1057-lazy-diff-changes-file-viewer
Nov 16, 2026
Merged

ivanfenenko merged 2 commits into
mainfrom
fix/1057-lazy-diff-changes-file-viewer

Conversation

@ivanfenenko

@ivanfenenko ivanfenenko commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Part of #1057: the unified diff view, the Changes screen and the File Viewer. Releasing closed sessions' transcripts is separate work.

Problem

On an Android emulator with a 192 MB Java heap and about 94 MB already live, opening a turn's Changes (60 files, about 620,000 added lines) and then a 1 MB file in the File Viewer took the heap to 191 MB, and the process died. Reading the code showed the same problems on both platforms:

  • Collapsed diff rows compared every context row against every changed row (quadratic), several times per render.
  • Every diff row was laid out at once in a non-lazy column or stack.
  • The edit detail parsed its patch again on every render. On iOS, the Changes file viewer also parsed it again, because its @State initial value is rebuilt each time the parent renders.
  • before/after contents were split and joined into a patch several times over.
  • The empty-source hint fetched the whole turn diff just to count its files.

What changed

Unified diff (Changes file viewer and edit details), Android and iOS

  • Collapsed rows come from two linear passes, a forward one and a backward one, and are computed once per document. canExpandContext reads the cached result.
  • Each patch is parsed once. Android takes each row's text straight from the patch. iOS works on Substrings and only splits a line when it could be a hunk header.
  • Every row has the same height, measured from one probe row. Only the rows near what the enclosing vertical scroll view shows are composed (Android) or drawn (iOS), plus about one screen above and below, in blocks of 32 rows. The layout still takes the full height of all rows, so the parent scrolls exactly as before. The horizontal scroll width comes from laying out the 8 rows with the most display columns (wide characters count twice, a tab as 8).
  • Collapsed and expanded context, hunk headers and selection, line numbers, additions and deletions, and horizontal scrolling should all look the same as before. Hunk navigation computes the hunk's offset from its row index. On iOS, scroll targets now exist only for hunk rows, which are the only rows anything scrolls to.

How the diff stays lazy inside a parent that scrolls
The parents keep their current scroll containers: the Changes viewer's scroll column and the bottom sheet's scroll body on both platforms. Nesting a LazyColumn or LazyVStack there would either crash (Compose) or stop being lazy (SwiftUI). Instead the diff reads what the parent shows:

  • Android: a SubcomposeLayout reads boundsInWindow() in onGloballyPositioned, so its visible rows are already clipped by every ancestor.
  • iOS: the drawn rows read bounds(of: .scrollView(axis: .vertical)) through onGeometryChange. With no vertical scroll view around it (the Appearance sample), every row is drawn.

The design-system component's public API is unchanged.

Changes

  • FileDiff gains isPatchTruncated (default false). A server patch longer than 1 MB is cut at its last line end when it is mapped, so the full string is not kept. The parser accepts a cut last hunk that holds fewer rows than its header says.
  • A patch built from before/after is written once, straight into a buffer of its final size (UnifiedPatch). Each input is read a bounded number of times, and building stops at the same 1 MB. The output matches the old builder byte for byte, including iOS keeping \r\n inside a line.
  • The "other source has N files" hint reads the last turn's file count from the published Review Changes summary. When no summary exists yet, it fetches once and publishes the summary. It never keeps the files.
  • The changed-file list derives its filtered files, groups and file positions once per state, not once per row.
  • Parsed rows still exist only for the file open in the viewer. That viewer's state no longer parses when it is rebuilt and dropped (iOS), or when it is copied (both platforms).

File Viewer
What a 1 MB file held, by reading the code. The text cap was already 1 MB:

  • the text itself
  • a copy of each line
  • syntax spans for every line once background colouring finished: tens of objects per line, so several MB for about 30,000 lines (an estimate, not a heap measurement)
  • on Android v1, a transient 1 MB byte array used only to measure the text

Now:

  • A file over 10,000 lines keeps colours only for the 10,000 lines centred on the visible ones. Lines further away go back to their plain form and colour again when scrolled back to. Files up to 10,000 lines colour exactly as before.
  • Android v1 counts UTF-8 bytes instead of encoding the text.

Cap and what the user sees

Only in the Changes file viewer, and only for a file whose patch is over 1 MB (UTF-8 bytes on iOS, UTF-16 characters on Android, the same for ASCII):

  • A banner above the diff, like the File Viewer's: "Showing the first 1 MB of this file's changes."
  • The diff shows whole lines up to that point. The last hunk ends where the cut falls.
  • Hunk navigation covers the hunks shown.
  • The file row's +/− counts are the server's and stay complete.

Edit details in the tool result sheet are not capped.

Checks

  • Android ./gradlew :app:testDebugUnitTest (full suite), :app:assembleDebug, :app:assembleDebugAndroidTest, :hexcode:assembleDebug: pass.
  • iOS xcodebuild build and build-for-testing for generic/platform=iOS Simulator (OpenCode Mobile), and build for Hex Code: pass. iOS tests were compiled but not run.
  • New structural tests on both platforms, with no wall-time assertions:
    • Collapsed rows match the old quadratic definition on the existing fixtures and new ones (changes at the start and end, adjacent hunks, no context, context only, metadata, a sparse 400-row hunk), at context 0, 1, 3 and 5.
    • Collapsed rows take exactly 2 × rows steps at 10,000 and 40,000 rows.
    • The memo parses a patch once across repeated reads. On iOS, FileViewerState does not parse until it is read.
    • A truncated patch keeps its cut last hunk.
    • The builder matches the old split/join output and reads each input character at most 4 times (Android) or each byte at most twice (iOS).
    • The hint takes the count from the summary with no diff request.
    • The Changes content state holds no parsed rows.
    • File Viewer colours stay within the limit and move with the visible rows.
  • Lint: ktlint is clean on the lines this PR adds. The files still carry their existing violations.
  • UI change: there is a new banner for patches over 1 MB. Everything else should look the same. Screenshots on both platforms will be attached after device checks.

Risks / Follow-ups

Device checks needed on both platforms (none were run here):

  • A small diff and a 10,000-line diff, in Changes and in an edit detail. Compare the look against main, then expand and collapse context, use hunk previous/next, scroll vertically and horizontally, and check the selected hunk highlight.
  • A turn with 60 files and about 620,000 added lines: Changes list, opening files, and a file over 1 MB showing the banner.
  • A 1 MB file in the File Viewer: colours near the top, after jumping to the end, and after scrolling back.
  • Heap on the low-heap (192 MB) emulator before and after the Changes and 1 MB file steps. Measure iOS memory for the same steps.
  • Scrolling smoothness. Rows are composed or drawn in blocks of 32 as the parent scrolls. A very fast fling could show a frame before a new block lands.

Other risks:

  • The scroll width is set by the 8 rows with the most estimated columns. A narrower-counted row that renders wider (an unusual font fallback) could be clipped at the right edge.
  • Rows have one fixed height. A glyph taller than the code line height would be clipped.
  • The turn diff response is still decoded in full before the 1 MB cap applies. Streaming the decode is a possible follow-up in the network layer.
  • Android caps a patch in characters and iOS in UTF-8 bytes. For non-ASCII patches, the cut falls in slightly different places.

🤖 Generated with Claude Code


Autofix with [code]smith
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

Unified diff (Changes and edit details), both platforms:
- Collapsed rows come from two linear passes and are computed once
  per document instead of comparing every context row with every
  change on each render.
- Rows sit at one measured height and only the rows near what the
  enclosing scroll view shows are composed or drawn, so the diff stays
  lazy inside the Changes viewer and the tool result sheet. The scroll
  width comes from the few widest rows.
- The edit detail parses its patch once per patch value.

Changes:
- A server patch over 1 MB is cut at its last line end and the viewer
  says it shows the first 1 MB of the file's changes.
- A patch built from before/after is written once into a buffer of its
  final size instead of splitting and joining both files.
- The empty-source hint reads the last turn's file count from its
  published summary instead of fetching the whole turn diff.

File Viewer: a file over 10,000 lines keeps syntax colors only for the
10,000 lines around the visible ones; v1 text is no longer encoded to
bytes just to measure it.

Refs #1057

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ivanfenenko
ivanfenenko marked this pull request as ready for review November 16, 2026 07:56

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review: no finding that 2+ of 3 passes agreed on.

5 finding(s) from a single pass, not posted
  • ios/OpenCode Mobile/OpenCode Mobile/Domain/Session/UnifiedPatch.swift:66 high: CRLF is not counted as a line break when building a patch (muse-spark-1.3-contributor)
  • ios/OpenCode Mobile/OpenCode Mobile/Domain/Session/UnifiedPatch.swift:23 medium: Truncation strips \r from a CRLF line end (muse-spark-1.3-contributor)
  • android/app/src/main/java/dev/opencode/mobile/domain/session/UnifiedPatch.kt:22 medium: Patch preview limit uses chars instead of UTF-8 bytes (muse-spark-1.3-contributor)
  • ios/OpenCode Mobile/OpenCode Mobile/Components/Chat/OpenCodeUnifiedDiff.swift:293 medium: iOS hunk-header detection now treats context lines that start with "@@ " as new hunks (deepseek-v4.1-flash)
  • android/app/src/main/java/dev/opencode/mobile/ui/components/chat/OpenCodeUnifiedDiff.kt:446 medium: Row count is clamped to MAX_DIFF_LAYOUT_HEIGHT, silently dropping the tail of very long diffs (deepseek-v4.1-flash)

opencode pr-review · passes: muse-spark-1.3-contributor, glm-5.3-flash, deepseek-v4.1-flash · $0.116 · 1 pass(es) stopped early

@ivanfenenko

Copy link
Copy Markdown
Collaborator Author

Automated review single-pass findings, triaged:

  • CRLF line counting / truncation stripping \r (iOS UnifiedPatch): intentional. It matches the old split(separator: "\n") output byte for byte, where \r\n is one grapheme.
  • iOS hunk-header detection with leading spaces: same as main. The old parser split on spaces with empty pieces dropped, so it matched those lines as well.
  • Android row clamp at the max layout height, and Android capping by chars instead of UTF-8 bytes: valid but low. Tracked in Diff view: flag rows past the layout limit and align the patch cap across platforms #1071.

@ivanfenenko
ivanfenenko added this pull request to the merge queue Nov 16, 2026
Merged via the queue into main with commit 55add13 Nov 16, 2026
@ivanfenenko
ivanfenenko deleted the fix/1057-lazy-diff-changes-file-viewer branch November 16, 2026 09:04
@ivanfenenko

Copy link
Copy Markdown
Collaborator Author

Device check (#1057, after merge)

This was checked as a local merge with #1060 and main, using this PR's head e021cdedb. The PR merged while the check was running. Real apps against the scenario harness, v2 server only. Android: emulator, API 37, Java heap limit 192 MB. iOS: simulator, iOS 27.2. All content is generated filler.

Defect found: line numbers past 2 digits are cut (both platforms, regression)

Every row now gets one measured height, and the line-number columns are still 24 dp/pt wide. On main, a wider number wrapped and the row grew. Now the shared height cuts it:

  • Android: a 4-digit line number shows only its first 2 digits. Lines 7818–7855 all read "78".
  • iOS: every line number from 100 up shows as "1…".

So any diff past line 99 (iOS) or 999 (Android) shows wrong or unreadable line numbers. A fix is ready as a local commit on top of main (096ed17c9, not pushed, because this PR has merged). It sizes both columns from the largest line number in the document, one digit width per digit past two, and stops them wrapping. Diffs under 100 lines look exactly as before. It adds one test per platform (lineNumberColumnsAreSizedForTheLargestLineNumber). Checked on both devices: Android shows 6014–6052 in full while fling-scrolling a 17,000-line diff; iOS shows 98–125 and 1590–1621 in full. It needs a follow-up pull request.

Heap and timing (Android, combined build, after 10 child sessions were opened and released: 38 MB live)

Step #1051 build (earlier evidence) With #1060 + this PR
Changes, Git changes: 67 files, +650,761 lines heap reached 191 MB and the process died ready about 2 s after the tap (load 2–4); peak 94 MB, then 46 MB live after GC; no crash
One 1.01 MB file diff (10,327 lines) peak 55 MB
Over-1 MB diff (huge.ts, 1.49 MB patch) and fast fling through it 59 MB on open, 66 MB peak while flinging
1 MB file in the File Viewer Android not measured (see below). iOS: opened in under 4.5 s, coloured at the top and at line ~6,140

The server fills patches only up to a budget. In the 67-file diff, 60 files came back with an empty patch and show "Preview unavailable", the same as before this PR. The banner was checked with that file as one of 4 changed files.

Behaviour

Check Android iOS
Small diff looks as on main pass (main screenshot below; PR build matches) pass (no main build on iOS; matches the description)
~7,000-row diff: look, fast fling, no gaps or overlap pass, except the line numbers above pass, except the line numbers above
Over-1 MB patch: banner "Showing the first 1 MB of this file's changes.", list counts unchanged (+17000) pass pass
File Viewer, file over 10,000 lines: colours near the visible lines not checked pass

Not checked: expanding context, hunk navigation, wide-glyph rows (tabs, CJK, emoji), the edit-detail sheet, scrolling to the very end of the cut patch, and the Android File Viewer. The device tool kept refusing touch injection on the emulator after a reinstall, and the scope was cut to an hour.

Android iOS
Small diff main: PR:
1 MB banner —
Line numbers cut (before the fix)
File Viewer, 10,327-line file at line ~6,140 —

Tests

CI android-checks and ios-checks passed on e021cdedb. Locally on the combined merge, all pass: Android UnifiedDiffDocumentTest, UnifiedPatchTest, ChangesViewModelTest and FilesViewModelTest (full suite: 3,465 tests, 0 failures); iOS UnifiedDiffVisibilityTests, UnifiedPatchTests, UnifiedDiffParserTests and ChangesViewModelTests. iOS FilesViewModelTests had one failure under load, in an existing test, aFinishedPassReleasesItsHighlightCoreSession; it passed 3 of 3 alone.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant