Repository navigation
feat(native-chat): render agent file edits as inline diff cards - #18765
Conversation
An agent's file edit rendered as a flat list of every removed line followed by every added line, with no interleaving, no file header, and no line numbers. A Codex edit on the transcript lane rendered no diff at all: the patch arrives wrapped in the source string of its `exec` tool, which matched none of the shapes the old parser looked for. Adds one diff model shared by every edit shape the supported agents produce: - `native-chat-edit-lcs` interleaves a snippet pair, falling back to a linear prefix/suffix diff above the quadratic guard. - `native-chat-unified-patch` keeps the `@@` ranges as per-row line numbers instead of parsing them into display text and discarding them. - `native-chat-begin-patch` recovers the `*** Begin Patch` envelope from the JavaScript string literal Codex sends it in, so that lane renders a diff. - `native-chat-edit-normalize` folds all of it into one model, including the two Codex shapes that do not look like diffs: add and delete arrive as raw file content, and a rename is appended to the body as prose. Claude reports an edit as a snippet pair, which cannot locate the change in the file, so its result's resolved hunks are now carried on the tool-result block and preferred when present. The field is optional, so an older client reading a newer journal simply drops it. Where no resolved ranges exist the gutter stays blank rather than showing a snippet-relative number, which would read as a file position. The card renders the verb from the observed change kind rather than the tool name, pairs an edit's call and result into a single row, and takes its row and gutter grounds from new tokens derived from the git status palette, replacing the hardcoded Tailwind tints the old view used. Desktop only; mobile chat keeps its existing renderer and parser untouched.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe change adds structured edit patches to decoded Claude tool results and preserves Codex argument payloads. It introduces shared edit models, LCS and unified-patch parsing, begin-patch extraction, and tool-pair normalization. Native chat now renders normalized edits as collapsible diff cards with gutters, gap rows, copy actions, truncation indicators, localized labels, and theme-specific colors. Tests cover provider formats, edit states, patch gaps, file operations, and rendering behavior. Merge Risk: 🟡 Moderate · up to Desktop native chat can still show incomplete, missing, or mislabeled file-edit cards, and a command that merely quotes an applypatch envelope can be presented as a file edit. These display-accuracy issues should be resolved before merging. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description explains the problem, implementation, scope, testing, and visual behavior in detail. However, it omits the required linked issue and does not provide the required checklist or explicit AI disclosure and agent-skill boundary responses. ✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Important
The blank-gutter path for snippet-pair edits still renders snippet-relative line numbers — the exact "wrong number reads as authoritative" failure this PR set out to avoid. See the inline comments.
Reviewed changes
- Shared diff model — five new
native-chat-edit-*modules (model,lcs,unified-patch,begin-patch,normalize) fold every edit shape the supported agents emit (Claude snippet pairs, Codex*** Begin Patch, Codex structuredchanges, whole-file add/delete) into one interleaved row model with per-side line numbers. - Claude resolved hunks —
transcript-line-decoders-claude.tsnow extractstoolUseResult.structuredPatchand attaches it to the tool-result block, so the renderer can number rows against the real file when available. - Inline diff card — a new
NativeChatDiffCardandNativeChatToolRunpairing collapse an edit call + result into a single card, with--diff-*tokens derived from the git status palette replacing the hardcoded emerald/rose classes.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
… prove Every defect here shares one failure mode: the card stated something the input did not support, and stated it confidently. Parsing: - A hunk no longer ends on `--- `, `+++ ` or `\ No newline`. The first two are what a removed `-- comment` (SQL/Lua/Haskell) looks like once the marker is prepended, so they truncated the whole diff; the no-newline marker is emitted mid-hunk, between the removed old last line and the added new one. Real headers are recognised through `isFileHeaderPair`, lifted out of `native-chat-diff` so the rule has one home. - A `*** Begin Patch` envelope with no `*** End Patch` is declined. With no closing marker `indexOf` returned -1 and the slice swallowed the rest of the command line, so `… +y" && echo ok` rendered as file content the agent never wrote. - One splitter serves every shape, so a CRLF patch no longer keeps a `\r` on each row, in the phantom-row guard, or in the clipboard. It also tests for the trailing newline on the clipped body: on the un-clipped string that test deleted a real line whenever the slice fired. - Truncation is carried from each slice site to the card, so content past the character cap can no longer render as a complete unchanged file with no "Diff truncated" footer. Attribution: - A failed or still-running edit renders no card. It kept the generic tool view, whose result block carries the provider's own error — the card had been drawing "Edited file +1 −1" from the input while hiding the red error body, which is worse than what preceded this feature. - The result-as-patch fallback is scoped to `Diff`, the one tool whose call carries only a path. Any command tool's output could previously be read as a patch, so `git diff` through `exec` was reclassified as an edit of a file named "file" and its command line disappeared with the result. - A whole-content write claims a creation only on evidence — the editor tool's own `create` command, or the provider reporting one. Overwriting a large existing file had always read as "Added file". - `MultiEdit` reads its `edits[]`, and `NotebookEdit` leaves the set: it carries only the new cell source. Both previously fell through to the old renderer, so one turn could show two diff presentations at once. - Snippet-relative numbers are dropped at the model layer rather than hidden by a zero-width gutter, which the flex min-width floor re-exposed on top of the marker and the first characters of the row. The run memoizes its edit model, so a collapsed group no longer re-diffs on every streaming token, and the card's copy button says what it copies.
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (1)
src/shared/native-chat-begin-patch.ts (1)
60-60: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDrop the unused
movePathbinding.
movePathis written at Line 75 and never read. The rename path readsmoves.get(index)at Line 87.♻️ Proposed refactor
- let movePath: string | null = null const moves = new Map<number, string>()if (move && sections.length > 0) { - movePath = move[1]!.trim() - moves.set(sections.length - 1, movePath) + moves.set(sections.length - 1, move[1]!.trim()) continue }Also applies to: 75-76
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 77e27515-bc9c-496d-90c4-a1a8a121a4a0
📒 Files selected for processing (15)
src/main/native-chat/transcript-line-decoders-claude.tssrc/renderer/src/assets/main.csssrc/renderer/src/components/native-chat/NativeChatCopyButton.tsxsrc/renderer/src/components/native-chat/NativeChatDiffCard.tsxsrc/renderer/src/components/native-chat/NativeChatToolRun.test.tsxsrc/renderer/src/components/native-chat/NativeChatToolRun.tsxsrc/renderer/src/i18n/locales/en.jsonsrc/shared/native-chat-begin-patch.tssrc/shared/native-chat-diff.tssrc/shared/native-chat-edit-lcs.tssrc/shared/native-chat-edit-model.tssrc/shared/native-chat-edit-normalize.test.tssrc/shared/native-chat-edit-normalize.tssrc/shared/native-chat-types.tssrc/shared/native-chat-unified-patch.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.
| hunks.push({ | ||
| oldStart: hunk.oldStart, | ||
| oldLines: typeof hunk.oldLines === 'number' ? hunk.oldLines : 0, | ||
| newStart: hunk.newStart, | ||
| newLines: typeof hunk.newLines === 'number' ? hunk.newLines : 0, | ||
| lines: lines | ||
| .slice(0, MAX_EDIT_PATCH_HUNK_LINES) | ||
| .flatMap((line) => (typeof line === 'string' ? [line] : [])) | ||
| }) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Skip hunks whose rows all get filtered out.
lines passes the Array.isArray guard even when it is empty or holds only non-string entries. The flatMap then yields [], and the hunk is still pushed. claudeEditPatch returns a non-null patch, so editFilesFromToolPair in src/shared/native-chat-edit-normalize.ts (Line 214) takes the resolved-hunk branch and skips the snippet-pair fallback. The card then renders with no rows and +0 -0.
Require at least one row per hunk.
🐛 Proposed fix
- hunks.push({
- oldStart: hunk.oldStart,
- oldLines: typeof hunk.oldLines === 'number' ? hunk.oldLines : 0,
- newStart: hunk.newStart,
- newLines: typeof hunk.newLines === 'number' ? hunk.newLines : 0,
- lines: lines
- .slice(0, MAX_EDIT_PATCH_HUNK_LINES)
- .flatMap((line) => (typeof line === 'string' ? [line] : []))
- })
+ const rows = lines
+ .slice(0, MAX_EDIT_PATCH_HUNK_LINES)
+ .flatMap((line) => (typeof line === 'string' ? [line] : []))
+ if (rows.length === 0) {
+ continue
+ }
+ hunks.push({
+ oldStart: hunk.oldStart,
+ oldLines: typeof hunk.oldLines === 'number' ? hunk.oldLines : 0,
+ newStart: hunk.newStart,
+ newLines: typeof hunk.newLines === 'number' ? hunk.newLines : 0,
+ lines: rows
+ })📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| hunks.push({ | |
| oldStart: hunk.oldStart, | |
| oldLines: typeof hunk.oldLines === 'number' ? hunk.oldLines : 0, | |
| newStart: hunk.newStart, | |
| newLines: typeof hunk.newLines === 'number' ? hunk.newLines : 0, | |
| lines: lines | |
| .slice(0, MAX_EDIT_PATCH_HUNK_LINES) | |
| .flatMap((line) => (typeof line === 'string' ? [line] : [])) | |
| }) | |
| const rows = lines | |
| .slice(0, MAX_EDIT_PATCH_HUNK_LINES) | |
| .flatMap((line) => (typeof line === 'string' ? [line] : [])) | |
| if (rows.length === 0) { | |
| continue | |
| } | |
| hunks.push({ | |
| oldStart: hunk.oldStart, | |
| oldLines: typeof hunk.oldLines === 'number' ? hunk.oldLines : 0, | |
| newStart: hunk.newStart, | |
| newLines: typeof hunk.newLines === 'number' ? hunk.newLines : 0, | |
| lines: rows | |
| }) |
| ] | ||
| } | ||
| // A move is appended to the diff body as prose rather than a header field. | ||
| const body = diff.replace(/\n*Moved to: .*$/, '') |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Anchor the move-marker strip past trailing whitespace.
In JavaScript $ without the m flag matches only the end of the input. It does not match before a final newline. If the Codex diff body ends with a newline after Moved to: <path>, the replace does not fire. The marker then reaches editLinesFromUnifiedPatch and renders as a context row.
🐛 Proposed fix
- const body = diff.replace(/\n*Moved to: .*$/, '')
+ const body = diff.replace(/\n*Moved to: [^\n]*\s*$/, '')📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const body = diff.replace(/\n*Moved to: .*$/, '') | |
| const body = diff.replace(/\n*Moved to: [^\n]*\s*$/, '') |
| export type NativeChatEditPatch = { | ||
| filePath?: string | ||
| hunks: NativeChatEditPatchHunk[] | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Preserve structured-patch truncation state.
claudeEditPatch clips oversized hunk arrays and line arrays with slice(...), but NativeChatEditPatch cannot record that clipping occurred. editFilesFromToolPair then creates an edit card with truncated unset. A large Claude edit silently shows only part of the patch and omits the truncation indicator.
Add a truncated field to NativeChatEditPatch. Set it when the decoder drops hunks or rows. Pass it to finalizeEditFile.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — delta since the prior pullfrog review (237b7e5).
- Blank-gutter fix — the gutter is now gated on
gutterWidth > 0andfinalizeEditFiledrops snippet-relative numbers whenlineNumbersKnownis false, so a snippet-pair edit no longer renders a plausible-but-wrong line number. - Copy label wired —
NativeChatCopyButtongained alabelprop, the card now reads "Copy diff", and the deadeditedFileskey was dropped. - Patch-tool split — the patch-tool set was split into envelope vs. text tools and the
result.outputfallback scoped toDiff, so agit diffcommand's output is no longer reclassified as an edit card. - Unlanded edits suppressed —
editFilesFromToolPairreturns null for failed/running calls and error results, keeping the provider's own error visible instead of a card that claims the edit was made. - Parser hardening — CRLF-safe
splitEditContentcarrying atruncatedflag, mid-hunk\ No newline at end of file,---prefixed removed lines vs. file-header pairs, and truncation threaded through every edit shape. - MultiEdit / Write semantics — added
MultiEditsnippet-pair support and Write create-vs-overwrite detection keyed on positive evidence only.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
A run of hunks was concatenated into one flat row list, so the gutter jumped from one region of the file to a distant one with nothing between them and the reader saw two unrelated spans as one continuous block. Rows now carry an explicit break: it holds no text and no position, counts toward neither side of the change, is trimmed from the end where it would mark nothing, and is left out of the copied text. The patch envelope lost files, and lost them silently: - An update chunk may carry no hunk header at all. The parser required one, returned nothing, and the caller dropped that file from a multi-file envelope with nothing to say it had gone. A header-less body now opens as a hunk of unknown position, and whether the rows are locatable is read off the rows themselves rather than off the header. - The envelope's own control lines rendered as content rows in the card. - A delete names its file and carries no body, which rendered as a card with an empty expandable row list. The header states the change and offers no disclosure behind it. - The header patterns are anchored and `.` excludes a carriage return, so a CRLF envelope matched no header at all and produced no card whatsoever. The envelope is split on both newline forms once, up front, rather than each pattern having to tolerate the extra character. A tool call's argument payload arrives as a string holding JSON. It was passed along undecoded, which is the only reason this code carried a hand-rolled string-literal unescaper. It is decoded once at the transcript decoder now — defensively, since the transcript is untrusted, so anything that is not a JSON object is left exactly as it arrived — and the unescaper is gone. Recovering the envelope no longer guesses at argument names either: it looks at the values, including the words of an argument vector, which is where the envelope actually sits once the payload is decoded.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — delta since the prior pullfrog review (000fcb0).
- Codex argument decoding —
codexCallInputin the transcript decoder now parses a JSON-objectargumentsstring once, so consumers see the object shape instead of unescaping it themselves; non-object payloads pass through unchanged. - Region gaps — the edit model gained a
gapline kind (editGapLine/pushEditGap), andNativeChatDiffCardrenders aDiffGapRowseparator between hunks and snippets so a gutter jump reads as a deliberate break. - Headerless hunks —
editLinesFromUnifiedPatchgained animplicitFirstHunkoption so a Codex update whose first chunk carries no@@header is kept rather than dropped from a multi-file envelope. - Envelope recovery —
unwrapBeginPatchnow reads the envelope from any argument value (including one word of an argument vector) and strips*** End of File/*** Environment ID:control lines instead of rendering them as content. - Bodiless deletes — a delete that names the file and nothing else keeps its header and offers no empty disclosure.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Recovering the patch envelope from any value of a tool's payload meant a write's own content was searched for one. A file documenting the patch format rendered a card for the file its example names, while the file actually written never appeared at all — the call and its result were consumed by that card, so nothing was left to correct it. Two changes: the envelope is recovered only for the tools that run one, never for a file edit whose payload is content; and only patch- or command-bearing arguments are searched, still including the words of an argument vector, which is where the envelope sits when a command tool applies it. The call payload is decoded back where it is needed rather than at the transcript decoder. Decoding it there changed the shape every reader of a tool's input sees, including the surface that recognises a question payload from any tool by shape alone: a tool whose arguments happened to carry that shape raised a question card pinned over the composer. That decode now happens inside the envelope recovery, the one consumer that needs the structure. A card also states an edit as made, so it now takes evidence that it landed — the provider reporting the call complete, or a result that is not an error. A turn that stopped before its call was answered reported an edit that may never have applied. This replaces the working-turn heuristic in the view, so the rule lives in one place. Two files still went missing. A multi-file patch has no per-file split, so it rendered as one card under the first file's name, with the later files' rows and their gutter numbers beneath it — a card asserting a false file position. Patch text is now split on its file boundaries, one card per file, each named by its own header, with a rename and a `/dev/null` side read from the same headers. And an envelope section that names a file but carries no body was dropped rather than reported, which is the same silent loss the delete case was fixed for.
The section under construction was only ever assigned inside the helper that opens one, which control-flow analysis does not see, so the variable stayed narrowed to its initial null and reading a field off it did not compile. The helper now only builds and records a section; the loop owns the assignment, which also fixes a real leak in the fall-through row: it opened a section it never made current, so the next row opened another one. The multi-file case also passed a possibly-undefined slice to a helper that takes an array or null.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — delta since the prior pullfrog review (615524e).
- Codex JSON decode reverted —
codexCallInputagain passes theargumentspayload through untouched, so the ask surface no longer reads aquestionsshape out of an unrelated tool's input; the one consumer that needs structure (native-chat-begin-patch) decodes it for itself. - Envelope recovery scoped —
unwrapBeginPatchsearches only theinput/command/patch/arguments/scriptkeys and is gated on patch-running tools, so aWritewhose content quotes an envelope no longer renders a card for the quoted file instead of the file actually written. - Landing evidence required —
editFilesFromToolPairreports an edit only when the provider marked the call complete or a non-error result exists; the renderer'sactiveTurnIsWorkingheuristic is dropped in favor of the model deciding which calls have landed. - Multi-file patch splitting —
unifiedPatchSectionssplitsDiff/patch text into one card per file, with per-section change kinds and old/new paths.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 3
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: e29b3a9f-0a5c-4457-8031-fbad42ed2300
📒 Files selected for processing (8)
src/main/native-chat/transcript-line-decoders-codex.tssrc/main/native-chat/transcript-reader-codex-history-mode.test.tssrc/renderer/src/components/native-chat/NativeChatToolRun.test.tsxsrc/renderer/src/components/native-chat/NativeChatToolRun.tsxsrc/shared/native-chat-begin-patch.tssrc/shared/native-chat-edit-normalize.test.tssrc/shared/native-chat-edit-normalize.tssrc/shared/native-chat-unified-patch.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.
| if (payload.arguments !== undefined) { | ||
| return payload.arguments |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Decode raw Codex edit arguments in the edit normalizer.
A Codex function_call with arguments: '{"changes":[...]}' now reaches editFilesFromToolPair as a string. Its record(pair.input) call returns null, so the codexChangeFiles(input.changes) branch cannot run. The native chat therefore shows the generic tool row instead of edit cards for direct Codex change payloads.
Keep transcript input raw for other consumers. Parse an object-shaped JSON string at the edit-normalization boundary before evaluating changes. Add an end-to-end decoder-to-normalizer test for raw changes arguments.
| * trailing tab introduces the timestamp some producers append. */ | ||
| function sourceHeaderPath(line: string): string | null { | ||
| const value = (line.slice(4).split('\t')[0] ?? '').trim() | ||
| return value === '' || value === '/dev/null' ? null : value.replace(/^[ab]\//, '') |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Parse quoted Git paths before assigning file metadata.
Git quotes paths such as diff --git "a/old file.ts" "b/new file.ts". Line 225 cannot find b/ in that header. A rename-only patch then has no path, and editFilesFromToolPair drops its card because it has no hunk rows. Line 218 also leaves quotes and Git escapes in regular patch card names.
Use one Git path parser for both header forms. Add cases for a content edit and a rename-only patch with spaces or escaped characters in the path.
Also applies to: 225-231
Splitting a patch into its files only ever looked for a boundary outside a hunk, and nothing reopened that state once the first hunk began, so every file after the first was swallowed as the first one's body. A `--- `/`+++ ` pair inside a hunk is now a boundary too, but only when a hunk header follows it immediately: a removed `-- x` over an added `++ y` is never followed by a column-0 header, which is what keeps the guard against reading content as structure intact. One producer cannot be recovered by any parser: it joins several files' patches and keeps a count where the path goes, so nothing in what reaches here names a file. That shape is refused rather than rendered under a name no file has. Recovering the per-file paths belongs to the producer and is filed separately. A clipped body carries its own marker in its text, and the bound that clips it is six times smaller than this module's, so it fires first. Read as content, the marker became a numbered line of the file and the rows before it were reported complete. It is recognised at the end of the text, removed, and reported as the truncation it is — the footer says so and the copied text no longer carries it. Also: a move appended to the body as prose is now read as a rename on every lane that carries the body as text, not just the one that also carries the destination as a field, where it had been rendering as a numbered line of the file it moved. The call's own path no longer wins over a rename's destination, which is only ever in the header, and only sections that name a file count toward deciding whether the call names the one file at hand. A command that merely quotes an envelope — writing documentation about the format — must now also invoke the tool that applies one. And two compared directories are no longer called a rename: only a header that states both sides as such is evidence of a move.
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 9cb3edee-1562-47fa-ac8c-db0fc4a5d64c
📒 Files selected for processing (5)
src/shared/native-chat-begin-patch.tssrc/shared/native-chat-edit-normalize.test.tssrc/shared/native-chat-edit-normalize.tssrc/shared/native-chat-unified-patch.tssrc/shared/structured-agent-session-projection.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/shared/native-chat-begin-patch.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
| }) | ||
| ] | ||
| } | ||
| const parsed = editLinesFromUnifiedPatch(splitMoveMarker(diff).body) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Apply the Codex prose rename destination.
When a Codex changes entry provides its rename only as Moved to: …, this call removes the marker but discards movedTo. movePath remains null, so the card reports an edit at the old path instead of a rename. Retain the result and use its destination as the fallback to movePath.
There was a problem hiding this comment.
ℹ️ No critical issues — one rare edge case in the header-pair splitting is noted inline.
Reviewed changes — delta since the prior pullfrog review (4282699).
- Patch-lane naming guards — a patch that cannot name its file no longer invents one: a
N filescount standing in for a path is refused, bare---/+++pairs no longer read as renames, and aMoved to:prose trailer is split out of the body. - Command-tool envelope gating —
unwrapBeginPatchgainedrequireApplyCommand, soexec/shell/local_shellyield a patch only when the command actually runsapply_patch; a command that merely quotes an envelope (cat > notes.md <<EOF) no longer renders an edit card. - Truncation-marker recovery — a new
stripBoundedTextMarkerinstructured-agent-session-projection.tsstrips the journal's… (N bytes)/Orca: output truncatedtrailers so a clipped patch reportstruncatedinstead of rendering the marker as a numbered line. - Headerless multi-file splitting —
unifiedPatchSectionsnow splits patches written withoutdiff --githeaders on a header pair immediately followed by@@, backed by eight new exact-assertion tests.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| // `-- x` over an added `++ y` is never followed by a column-0 `@@`, and | ||
| // that is what separates the files of a patch written without `diff --git` | ||
| // headers, where nothing else would end the previous file's hunk. | ||
| if (isFileHeaderPair(rows, index) && (!inHunk || (rows[index + 2] ?? '').startsWith('@@'))) { |
There was a problem hiding this comment.
The startsWith('@@') guard doesn't fully rule out a content pair: a removed -- comment sitting directly over an added ++ foo as the last change of a hunk emits as --- comment / +++ foo / @@ -…, which still trips this boundary test. The result is a split section and a fabricated foo card with the -- comment→++ foo change silently dropped, so the docstring's "never followed by a column-0 @@" overstates the invariant.
Technical details
# Header-pair false positive when a `-- x`→`++ y` pair abuts the next hunk
## Affected sites
- src/shared/native-chat-unified-patch.ts:173 — the `!inHunk || (rows[index + 2] ?? '').startsWith('@@')` clause treats a removed `-- comment` immediately over an added `++ foo` as a file boundary whenever a second hunk follows.
## Repro
unifiedPatchSections('@@ -1,2 +1,2 @@\n ctx\n--- comment\n+++ foo\n@@ -10,1 +10,1 @@\n-later\n+later2')
- index 2/3: `isFileHeaderPair` sees `--- comment` / `+++ foo`; `inHunk` is true and `rows[4]` starts with `@@`, so it opens a named section (`oldPath: 'comment'`, `newPath: 'foo'`, `fromGitHeader: false`).
- The ` ctx`, `-later`, `+later2` rows collapse into one section named `foo`; the `-- comment`→`++ foo` change itself is consumed as a header and never rendered.
## Required outcome
- Decide whether this residual mis-split is acceptable (in which case soften the docstring's absolute "never"), or add a discriminator that excludes this shape.
## Open questions for the human
- How common are adjacent `-- `-prefixed deletions over `++ `-prefixed additions at a hunk boundary in the payloads these lanes actually receive? If effectively nil, documenting the residual risk is sufficient.The marker a producer appends to say where a file moved was matched anywhere on the body's last line, so a row whose own content mentions a move was cut in half at that point and the file it named claimed as the destination of a rename that never happened. It is now anchored to the start of the final line, on both lanes that carry the body as text. The command that applies a patch envelope has a second spelling the runner accepts and runs; requiring the first one refused a patch that really landed. Both are accepted, still matched against whole argument words rather than the payload at large. A clipped diff also said so only under its own rows, where a collapsed card — or one clipped down to no rows at all — showed nothing. It sits beside the change counts now, which are visible either way.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: db7fa5b3-9215-4dc1-8470-f3a7499fc75b
📒 Files selected for processing (5)
src/renderer/src/components/native-chat/NativeChatDiffCard.tsxsrc/renderer/src/components/native-chat/NativeChatToolRun.test.tsxsrc/shared/native-chat-begin-patch.tssrc/shared/native-chat-edit-normalize.test.tssrc/shared/native-chat-edit-normalize.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/shared/native-chat-edit-normalize.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
| const ENVELOPE_ARGUMENTS = ['input', 'command', 'patch', 'arguments', 'script'] as const | ||
| /** What a command tool runs to apply an envelope, as opposed to quoting one. | ||
| * Both spellings the runner accepts, since either one really applies it. */ | ||
| const APPLY_COMMAND = /apply_?patch/ |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Do not treat quoted applypatch text as an applied patch.
APPLY_COMMAND.test() accepts a substring anywhere in the command. A completed command that only prints an applypatch envelope passes this check, and src/shared/native-chat-edit-normalize.ts then replaces the command row with an Edited file card. Parse and validate the actual command invocation, or keep the generic tool row when that proof is unavailable. Add a quoted-applypatch regression case.
There was a problem hiding this comment.
ℹ️ No new issues in this delta. Approval is withheld because one prior thread remains open and unchanged.
Reviewed changes — delta since the prior pullfrog review (279a7e4).
- Move marker anchored to its own line —
MOVE_MARKERnow requiresMoved to:to sit at the start of a line, so a diff row whose own content mentions a move (e.g.+See Moved to: docs/archive/index.md) is no longer cut in half and claimed as a rename that never happened. applypatchspelling accepted —APPLY_COMMANDis now a regex matching bothapply_patchandapplypatch, so a Codex command that runs the underscore-less variant still counts as applying an envelope.- Truncation label hoisted to the header — the "Diff truncated" hint now sits beside the
+N -Mcounts rather than under the rows, so a collapsed card (or one clipped to no rows at all) still signals a clipped diff.
The prior review's open thread on src/shared/native-chat-unified-patch.ts (a removed -- comment over an added ++ foo at a hunk boundary followed by @@ can still split a file and drop that change) is untouched by this commit. It is not re-raised here; it is the sole item blocking approval.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
The copy text is joined from every row of the diff, which a collapsed card renders none of, and it was rebuilt on every render to seed a prop. It is memoized on the rows, matching how the run memoizes its edit model. The two scanners that read patch text kept the same file-section alternation verbatim, so they could drift apart while both looking correct; there is one definition now, beside the header-pair rule that already lives there. Also: the row that marks a break between regions is built in one place, so it is no longer exported; the move destination in the envelope reader was a function-wide binding written and read within one iteration, which read as if a move carried between sections; and a test comment named the wrong mechanism for keeping a card collapsed. Adds the missing pin on what the copy affordance actually copies.
Review status: ready to mergeFive review loops plus a readiness checklist at each end. The original commit was red on CI and carried defects across every payload lane. 28 were found and fixed. Almost all were one failure mode: the card asserting something it could not prove. What was wrongSilent data loss in the patch parser
Cards claiming edits that did not happen
Correctness and platform
Performance
CI
Deliberately not changed
Verification
Scope held throughout: |
Visual proof, re-captured after reviewThe screenshots in the PR body were taken against the original commit Driven through the production path — real JSONL on disk → real main-process decoder → real Renderer ownership was proved at attach and again before shutdown: The first two are the feature working. The next four are the review's fixes — each of these rendered wrongly at some point during the campaign. Claude
|
…d of refusing it The shell parsed the host's transcript reply against a .strict() page contract. The host already publishes three things that contract has never carried, all on the transcript lane the hosted page uses: - Claude's resolved edit hunks (editPatch), on every Edit tool result since #18765; - a structured providerFrame on a text block; - text up to MOBILE_TEXT_BLOCK_CHAR_CAP (64 KiB), where the wire allows 4200. Each was an unrecognized key or an over-long string, so the parse threw. On read the page got 'Transcript read failed' and rendered nothing; on subscribe sanitizeEvent returned null and the ledger cancelled with invalid_message, which is not retryable, so the live transcript died mid-turn. The native app reads the same host method directly and showed all three fine, so this was a hosted-only blank screen rather than a missing feature. The shell now projects each message onto the contract: text and tool output are clipped with the truncation marker the host itself uses, the tool-call lifecycle state is carried, a block whose shape the page cannot render is dropped without its siblings, and a message whose id would break dedup is dropped rather than clipped. A projected corpus is asserted to always satisfy the schema, and the .parse stays behind it as a fence. editPatch and providerFrame are dropped, not widened: mobile renders edits through diffFromToolCall and has no provider-frame row, so carrying them would be wire weight no component reads. Both are additive shell->page fields if a mobile renderer for them ever lands. Supersedes sanitizeMobileWebNativeChatMessages, which only reached tool inputs. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
…lyai#18765) * feat(native-chat): render agent file edits as inline diff cards An agent's file edit rendered as a flat list of every removed line followed by every added line, with no interleaving, no file header, and no line numbers. A Codex edit on the transcript lane rendered no diff at all: the patch arrives wrapped in the source string of its `exec` tool, which matched none of the shapes the old parser looked for. Adds one diff model shared by every edit shape the supported agents produce: - `native-chat-edit-lcs` interleaves a snippet pair, falling back to a linear prefix/suffix diff above the quadratic guard. - `native-chat-unified-patch` keeps the `@@` ranges as per-row line numbers instead of parsing them into display text and discarding them. - `native-chat-begin-patch` recovers the `*** Begin Patch` envelope from the JavaScript string literal Codex sends it in, so that lane renders a diff. - `native-chat-edit-normalize` folds all of it into one model, including the two Codex shapes that do not look like diffs: add and delete arrive as raw file content, and a rename is appended to the body as prose. Claude reports an edit as a snippet pair, which cannot locate the change in the file, so its result's resolved hunks are now carried on the tool-result block and preferred when present. The field is optional, so an older client reading a newer journal simply drops it. Where no resolved ranges exist the gutter stays blank rather than showing a snippet-relative number, which would read as a file position. The card renders the verb from the observed change kind rather than the tool name, pairs an edit's call and result into a single row, and takes its row and gutter grounds from new tokens derived from the git status palette, replacing the hardcoded Tailwind tints the old view used. Desktop only; mobile chat keeps its existing renderer and parser untouched. * fix(native-chat): stop the diff card from asserting an edit it cannot prove Every defect here shares one failure mode: the card stated something the input did not support, and stated it confidently. Parsing: - A hunk no longer ends on `--- `, `+++ ` or `\ No newline`. The first two are what a removed `-- comment` (SQL/Lua/Haskell) looks like once the marker is prepended, so they truncated the whole diff; the no-newline marker is emitted mid-hunk, between the removed old last line and the added new one. Real headers are recognised through `isFileHeaderPair`, lifted out of `native-chat-diff` so the rule has one home. - A `*** Begin Patch` envelope with no `*** End Patch` is declined. With no closing marker `indexOf` returned -1 and the slice swallowed the rest of the command line, so `… +y" && echo ok` rendered as file content the agent never wrote. - One splitter serves every shape, so a CRLF patch no longer keeps a `\r` on each row, in the phantom-row guard, or in the clipboard. It also tests for the trailing newline on the clipped body: on the un-clipped string that test deleted a real line whenever the slice fired. - Truncation is carried from each slice site to the card, so content past the character cap can no longer render as a complete unchanged file with no "Diff truncated" footer. Attribution: - A failed or still-running edit renders no card. It kept the generic tool view, whose result block carries the provider's own error — the card had been drawing "Edited file +1 −1" from the input while hiding the red error body, which is worse than what preceded this feature. - The result-as-patch fallback is scoped to `Diff`, the one tool whose call carries only a path. Any command tool's output could previously be read as a patch, so `git diff` through `exec` was reclassified as an edit of a file named "file" and its command line disappeared with the result. - A whole-content write claims a creation only on evidence — the editor tool's own `create` command, or the provider reporting one. Overwriting a large existing file had always read as "Added file". - `MultiEdit` reads its `edits[]`, and `NotebookEdit` leaves the set: it carries only the new cell source. Both previously fell through to the old renderer, so one turn could show two diff presentations at once. - Snippet-relative numbers are dropped at the model layer rather than hidden by a zero-width gutter, which the flex min-width floor re-exposed on top of the marker and the first characters of the row. The run memoizes its edit model, so a collapsed group no longer re-diffs on every streaming token, and the card's copy button says what it copies. * fix(native-chat): keep every edited file, and mark where the diff breaks A run of hunks was concatenated into one flat row list, so the gutter jumped from one region of the file to a distant one with nothing between them and the reader saw two unrelated spans as one continuous block. Rows now carry an explicit break: it holds no text and no position, counts toward neither side of the change, is trimmed from the end where it would mark nothing, and is left out of the copied text. The patch envelope lost files, and lost them silently: - An update chunk may carry no hunk header at all. The parser required one, returned nothing, and the caller dropped that file from a multi-file envelope with nothing to say it had gone. A header-less body now opens as a hunk of unknown position, and whether the rows are locatable is read off the rows themselves rather than off the header. - The envelope's own control lines rendered as content rows in the card. - A delete names its file and carries no body, which rendered as a card with an empty expandable row list. The header states the change and offers no disclosure behind it. - The header patterns are anchored and `.` excludes a carriage return, so a CRLF envelope matched no header at all and produced no card whatsoever. The envelope is split on both newline forms once, up front, rather than each pattern having to tolerate the extra character. A tool call's argument payload arrives as a string holding JSON. It was passed along undecoded, which is the only reason this code carried a hand-rolled string-literal unescaper. It is decoded once at the transcript decoder now — defensively, since the transcript is untrusted, so anything that is not a JSON object is left exactly as it arrived — and the unescaper is gone. Recovering the envelope no longer guesses at argument names either: it looks at the values, including the words of an argument vector, which is where the envelope actually sits once the payload is decoded. * fix(native-chat): only read a patch where a patch was actually run Recovering the patch envelope from any value of a tool's payload meant a write's own content was searched for one. A file documenting the patch format rendered a card for the file its example names, while the file actually written never appeared at all — the call and its result were consumed by that card, so nothing was left to correct it. Two changes: the envelope is recovered only for the tools that run one, never for a file edit whose payload is content; and only patch- or command-bearing arguments are searched, still including the words of an argument vector, which is where the envelope sits when a command tool applies it. The call payload is decoded back where it is needed rather than at the transcript decoder. Decoding it there changed the shape every reader of a tool's input sees, including the surface that recognises a question payload from any tool by shape alone: a tool whose arguments happened to carry that shape raised a question card pinned over the composer. That decode now happens inside the envelope recovery, the one consumer that needs the structure. A card also states an edit as made, so it now takes evidence that it landed — the provider reporting the call complete, or a result that is not an error. A turn that stopped before its call was answered reported an edit that may never have applied. This replaces the working-turn heuristic in the view, so the rule lives in one place. Two files still went missing. A multi-file patch has no per-file split, so it rendered as one card under the first file's name, with the later files' rows and their gutter numbers beneath it — a card asserting a false file position. Patch text is now split on its file boundaries, one card per file, each named by its own header, with a rename and a `/dev/null` side read from the same headers. And an envelope section that names a file but carries no body was dropped rather than reported, which is the same silent loss the delete case was fixed for. * fix(native-chat): type the patch-section scan and its test helper call The section under construction was only ever assigned inside the helper that opens one, which control-flow analysis does not see, so the variable stayed narrowed to its initial null and reading a field off it did not compile. The helper now only builds and records a section; the loop owns the assignment, which also fixes a real leak in the fall-through row: it opened a section it never made current, so the next row opened another one. The multi-file case also passed a possibly-undefined slice to a helper that takes an array or null. * fix(native-chat): stop the patch lane naming files it cannot name Splitting a patch into its files only ever looked for a boundary outside a hunk, and nothing reopened that state once the first hunk began, so every file after the first was swallowed as the first one's body. A `--- `/`+++ ` pair inside a hunk is now a boundary too, but only when a hunk header follows it immediately: a removed `-- x` over an added `++ y` is never followed by a column-0 header, which is what keeps the guard against reading content as structure intact. One producer cannot be recovered by any parser: it joins several files' patches and keeps a count where the path goes, so nothing in what reaches here names a file. That shape is refused rather than rendered under a name no file has. Recovering the per-file paths belongs to the producer and is filed separately. A clipped body carries its own marker in its text, and the bound that clips it is six times smaller than this module's, so it fires first. Read as content, the marker became a numbered line of the file and the rows before it were reported complete. It is recognised at the end of the text, removed, and reported as the truncation it is — the footer says so and the copied text no longer carries it. Also: a move appended to the body as prose is now read as a rename on every lane that carries the body as text, not just the one that also carries the destination as a field, where it had been rendering as a numbered line of the file it moved. The call's own path no longer wins over a rename's destination, which is only ever in the header, and only sections that name a file count toward deciding whether the call names the one file at hand. A command that merely quotes an envelope — writing documentation about the format — must now also invoke the tool that applies one. And two compared directories are no longer called a rename: only a header that states both sides as such is evidence of a move. * fix(native-chat): anchor the move marker to its own line The marker a producer appends to say where a file moved was matched anywhere on the body's last line, so a row whose own content mentions a move was cut in half at that point and the file it named claimed as the destination of a rename that never happened. It is now anchored to the start of the final line, on both lanes that carry the body as text. The command that applies a patch envelope has a second spelling the runner accepts and runs; requiring the first one refused a patch that really landed. Both are accepted, still matched against whole argument words rather than the payload at large. A clipped diff also said so only under its own rows, where a collapsed card — or one clipped down to no rows at all — showed nothing. It sits beside the change counts now, which are visible either way. * refactor(native-chat): tidy what the diff-card work left behind The copy text is joined from every row of the diff, which a collapsed card renders none of, and it was rebuilt on every render to seed a prop. It is memoized on the rows, matching how the run memoizes its edit model. The two scanners that read patch text kept the same file-section alternation verbatim, so they could drift apart while both looking correct; there is one definition now, beside the header-pair rule that already lives there. Also: the row that marks a break between regions is built in one place, so it is no longer exported; the move destination in the envelope reader was a function-wide binding written and read within one iteration, which read as if a move carried between sections; and a test comment named the wrong mechanism for keeping a card collapsed. Adds the missing pin on what the copy affordance actually copies. --------- Co-authored-by: Merge Sim <sim@local>











What was wrong
An agent's file edit rendered as a flat list of every removed line followed by every added line — no interleaving, no file header, no counts, no line numbers. And a Codex edit on the transcript lane rendered no diff at all: the patch arrives wrapped in the source string of its
exectool, which matched none of the shapes the old parser looked for.Measured against real payloads from live sessions rather than fixtures:
Edit/Write/MultiEditHow
One diff model shared by every edit shape the supported agents produce:
native-chat-edit-lcs— interleaves a snippet pair, falling back to a linear prefix/suffix diff above the quadratic guard.native-chat-unified-patch— keeps@@ranges as per-row line numbers instead of parsing them into display text and throwing them away.native-chat-begin-patch— recovers the*** Begin Patchenvelope from the JavaScript string literal Codex sends it in. This is what takes that lane from nothing to a diff.native-chat-edit-normalize— folds it into one model, including the two Codex shapes that don't look like diffs:add/deletearrive as raw file content with no hunk header or signs, and a rename is appended to the body as prose.Line numbering follows the standard unified rule: a removed row is numbered on the old side, added and context rows on the new side. A replaced line therefore repeats its number, which is correct.
Line numbers, and where they come from
Claude reports an edit as a snippet pair, which cannot say where in the file the change sits. Its result carries hunks it already resolved against the real file, so those are now kept on the tool-result block and preferred when present. The field is optional and the journal schema is non-strict, so an older client reading a newer journal drops it rather than failing.
Where no resolved ranges exist, the gutter stays blank rather than showing a snippet-relative number — a plausible-looking wrong line number reads as authoritative and is worse than none.
Also
Added/Deleted/Renamed/Edited), not the tool name.--diff-*tokens derived from the existing git status palette viacolor-mix, replacing the hardcodedbg-emerald-500/10/bg-rose-500/10the old view used. The gutter gets its own slightly stronger ground so the number column stays legible on a tinted row.Scope
Desktop only.
src/shared/native-chat-diff.tsis untouched, so mobile chat keeps its existing parser and renderer and compiles unchanged. Mobile is a separate follow-up, which will also collapse the LCS that now exists both here and in mobile's diff-review screen.Syntax highlighting and word-level intra-line tints are deliberately out of scope — the card is correct without them.
Verification
pnpm tcclean.native-chat-edit-normalize.test.ts, covering each payload shape, both Codex traps, and the numbering rule.NativeChatToolRuntests updated: they asserted the old renderer's exact DOM (+afteras one string) and the hardcoded palette classes this PR replaces. Intent preserved — still "renders a diff, not JSON".pnpm run check:code-quality:changedpasses.src/main/native-chat/agent-session-wire/has load-sensitive tests that fail nondeterministically when the directory runs in parallel and pass when run alone. Verified the same files pass in isolation both with and without this change.Visual proof
These are seeded transcripts, not a live agent turn. An isolated Orca dev instance (this worktree, fresh profile, native chat on) loaded Claude and Codex JSONL through the real native-chat transcript decoder and renderer. No agent was driven.
What the shots show:
+N -Mcounts, copy button.43/43, Codex19/19).Editcall plus the resolved hunks from the tool result (structuredPatch) — that is how this PR gets real line numbers for Claude.apply_patchwith@@ranges (the structured-lane payload shape, fed through the transcript decoder).Claude — collapsed, dark
Claude — expanded, dark (gutter 42 / 43 / 43 / 44)
Claude — expanded, light
Codex — collapsed, dark
Codex — expanded, dark (gutter 18 / 19 / 19 / 20)
Codex — expanded, light
What looked off in the UI