Skip to content

feat(native-chat): render agent file edits as inline diff cards - #18765

Merged
brennanb2025 merged 8 commits into
mainfrom
brennanb2025/native-chat-code-diff
Sep 5, 2026
Merged

brennanb2025 merged 8 commits into
mainfrom
brennanb2025/native-chat-code-diff

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​803 $\color{#cf222e}{\Huge{\mathbf{−}}}$​12 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​791
Prod 15 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1401 $\color{#cf222e}{\Huge{\mathbf{−}}}$​11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1390

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 exec tool, which matched none of the shapes the old parser looked for.

Measured against real payloads from live sessions rather than fixtures:

Path Before After
Codex, transcript lane Nothing rendered Diff card, gutter blank
Codex, structured lane Rows, ranges parsed then discarded Diff card with real line numbers
Claude Edit / Write / MultiEdit Path, then all deletions, then all additions Interleaved card with real line numbers

How

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 Patch envelope 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/delete arrive 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

  • The verb comes from the observed change kind (Added / Deleted / Renamed / Edited), not the tool name.
  • An edit's call and result are paired into a single card; every other tool renders exactly as before.
  • Row and gutter grounds come from new --diff-* tokens derived from the existing git status palette via color-mix, replacing the hardcoded bg-emerald-500/10 / bg-rose-500/10 the 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.ts is 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 tc clean.
  • 15 new tests in native-chat-edit-normalize.test.ts, covering each payload shape, both Codex traps, and the numbering rule.
  • Two existing NativeChatToolRun tests updated: they asserted the old renderer's exact DOM (+after as one string) and the hardcoded palette classes this PR replaces. Intent preserved — still "renders a diff, not JSON".
  • pnpm run check:code-quality:changed passes.
  • Note for reviewers: 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:

  • Collapsed card: chevron, Edited file header, filename, +N -M counts, copy button.
  • Expanded card: interleaved unified rows with a one-column gutter. A replaced line repeats its number (Claude 43/43, Codex 19/19).
  • Claude: Edit call plus the resolved hunks from the tool result (structuredPatch) — that is how this PR gets real line numbers for Claude.
  • Codex: apply_patch with @@ ranges (the structured-lane payload shape, fed through the transcript decoder).
  • Dark and light.

Claude — collapsed, dark

claude-collapsed-dark.png

Claude — expanded, dark (gutter 42 / 43 / 43 / 44)

claude-expanded-dark.png

Claude — expanded, light

claude-expanded-light.png

Codex — collapsed, dark

codex-collapsed-dark.png

Codex — expanded, dark (gutter 18 / 19 / 19 / 20)

codex-expanded-dark.png

Codex — expanded, light

codex-expanded-light.png

What looked off in the UI

  • The card copy control reuses the message copy button, so its accessible name is Copy message rather than something file-specific.
  • The assistant-message copy / scroll-to-top controls still render under the card (two extra icons below the filename row).
  • The card is only as wide as its content inside the chat column; lots of unused width to the right. Not a functional issue.

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.
@coderabbitai

coderabbitai Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The 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 15db7

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning 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… Add a valid issue reference after "Fixes #". Complete the required checklist items, add the AI disclosure if applicable, and confirm the agent-skill upstream boundary.
Docstring Coverage ⚠️ Warning Docstring coverage is 51.85% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 54 functions across 17 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary change: rendering native-chat agent file edits as inline diff cards.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

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 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 structured changes, whole-file add/delete) into one interleaved row model with per-side line numbers.
  • Claude resolved hunks — transcript-line-decoders-claude.ts now extracts toolUseResult.structuredPatch and attaches it to the tool-result block, so the renderer can number rows against the real file when available.
  • Inline diff card — a new NativeChatDiffCard and NativeChatToolRun pairing collapse an edit call + result into a single card, with --diff-* tokens derived from the git status palette replacing the hardcoded emerald/rose classes.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (1)
src/shared/native-chat-begin-patch.ts (1)

60-60: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Drop the unused movePath binding.

movePath is written at Line 75 and never read. The rename path reads moves.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

📥 Commits

Reviewing files that changed from the base of the PR and between 38bde20 and 000fcb0.

📒 Files selected for processing (15)
  • src/main/native-chat/transcript-line-decoders-claude.ts
  • src/renderer/src/assets/main.css
  • src/renderer/src/components/native-chat/NativeChatCopyButton.tsx
  • src/renderer/src/components/native-chat/NativeChatDiffCard.tsx
  • src/renderer/src/components/native-chat/NativeChatToolRun.test.tsx
  • src/renderer/src/components/native-chat/NativeChatToolRun.tsx
  • src/renderer/src/i18n/locales/en.json
  • src/shared/native-chat-begin-patch.ts
  • src/shared/native-chat-diff.ts
  • src/shared/native-chat-edit-lcs.ts
  • src/shared/native-chat-edit-model.ts
  • src/shared/native-chat-edit-normalize.test.ts
  • src/shared/native-chat-edit-normalize.ts
  • src/shared/native-chat-types.ts
  • src/shared/native-chat-unified-patch.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.

Comment on lines +43 to +51
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] : []))
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

Suggested change
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
})

Comment thread src/shared/native-chat-begin-patch.ts Resolved
]
}
// A move is appended to the diff body as prose rather than a header field.
const body = diff.replace(/\n*Moved to: .*$/, '')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

Suggested change
const body = diff.replace(/\n*Moved to: .*$/, '')
const body = diff.replace(/\n*Moved to: [^\n]*\s*$/, '')

Comment on lines +71 to +74
export type NativeChatEditPatch = {
filePath?: string
hunks: NativeChatEditPatchHunk[]
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes — delta since the prior pullfrog review (237b7e5).

  • Blank-gutter fix — the gutter is now gated on gutterWidth > 0 and finalizeEditFile drops snippet-relative numbers when lineNumbersKnown is false, so a snippet-pair edit no longer renders a plausible-but-wrong line number.
  • Copy label wired — NativeChatCopyButton gained a label prop, the card now reads "Copy diff", and the dead editedFiles key was dropped.
  • Patch-tool split — the patch-tool set was split into envelope vs. text tools and the result.output fallback scoped to Diff, so a git diff command's output is no longer reclassified as an edit card.
  • Unlanded edits suppressed — editFilesFromToolPair returns 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 splitEditContent carrying a truncated flag, 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 MultiEdit snippet-pair support and Write create-vs-overwrite detection keyed on positive evidence only.

Pullfrog  | View workflow run | Using 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes — delta since the prior pullfrog review (000fcb0).

  • Codex argument decoding — codexCallInput in the transcript decoder now parses a JSON-object arguments string 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 gap line kind (editGapLine/pushEditGap), and NativeChatDiffCard renders a DiffGapRow separator between hunks and snippets so a gutter jump reads as a deliberate break.
  • Headerless hunks — editLinesFromUnifiedPatch gained an implicitFirstHunk option so a Codex update whose first chunk carries no @@ header is kept rather than dropped from a multi-file envelope.
  • Envelope recovery — unwrapBeginPatch now 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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Merge Sim added 2 commits September 4, 2026 21:06
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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes — delta since the prior pullfrog review (615524e).

  • Codex JSON decode reverted — codexCallInput again passes the arguments payload through untouched, so the ask surface no longer reads a questions shape out of an unrelated tool's input; the one consumer that needs structure (native-chat-begin-patch) decodes it for itself.
  • Envelope recovery scoped — unwrapBeginPatch searches only the input/command/patch/arguments/script keys and is gated on patch-running tools, so a Write whose content quotes an envelope no longer renders a card for the quoted file instead of the file actually written.
  • Landing evidence required — editFilesFromToolPair reports an edit only when the provider marked the call complete or a non-error result exists; the renderer's activeTurnIsWorking heuristic is dropped in favor of the model deciding which calls have landed.
  • Multi-file patch splitting — unifiedPatchSections splits Diff/patch text into one card per file, with per-section change kinds and old/new paths.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: e29b3a9f-0a5c-4457-8031-fbad42ed2300

📥 Commits

Reviewing files that changed from the base of the PR and between 615524e and 6432dd8.

📒 Files selected for processing (8)
  • src/main/native-chat/transcript-line-decoders-codex.ts
  • src/main/native-chat/transcript-reader-codex-history-mode.test.ts
  • src/renderer/src/components/native-chat/NativeChatToolRun.test.tsx
  • src/renderer/src/components/native-chat/NativeChatToolRun.tsx
  • src/shared/native-chat-begin-patch.ts
  • src/shared/native-chat-edit-normalize.test.ts
  • src/shared/native-chat-edit-normalize.ts
  • src/shared/native-chat-unified-patch.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.

Comment on lines 210 to 211
if (payload.arguments !== undefined) {
return payload.arguments

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ 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]\//, '')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 9cb3edee-1562-47fa-ac8c-db0fc4a5d64c

📥 Commits

Reviewing files that changed from the base of the PR and between 6432dd8 and 279a7e4.

📒 Files selected for processing (5)
  • src/shared/native-chat-begin-patch.ts
  • src/shared/native-chat-edit-normalize.test.ts
  • src/shared/native-chat-edit-normalize.ts
  • src/shared/native-chat-unified-patch.ts
  • src/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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ 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 files count standing in for a path is refused, bare --- /+++ pairs no longer read as renames, and a Moved to: prose trailer is split out of the body.
  • Command-tool envelope gating — unwrapBeginPatch gained requireApplyCommand, so exec/shell/local_shell yield a patch only when the command actually runs apply_patch; a command that merely quotes an envelope (cat > notes.md <<EOF) no longer renders an edit card.
  • Truncation-marker recovery — a new stripBoundedTextMarker in structured-agent-session-projection.ts strips the journal's … (N bytes) / Orca: output truncated trailers so a clipped patch reports truncated instead of rendering the marker as a numbered line.
  • Headerless multi-file splitting — unifiedPatchSections now splits patches written without diff --git headers on a header pair immediately followed by @@, backed by eight new exact-assertion tests.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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('@@'))) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: db7fa5b3-9215-4dc1-8470-f3a7499fc75b

📥 Commits

Reviewing files that changed from the base of the PR and between 279a7e4 and 15db74c.

📒 Files selected for processing (5)
  • src/renderer/src/components/native-chat/NativeChatDiffCard.tsx
  • src/renderer/src/components/native-chat/NativeChatToolRun.test.tsx
  • src/shared/native-chat-begin-patch.ts
  • src/shared/native-chat-edit-normalize.test.ts
  • src/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/

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

ℹ️ 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_MARKER now requires Moved 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.
  • applypatch spelling accepted — APPLY_COMMAND is now a regex matching both apply_patch and applypatch, 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 -M counts 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.

Pullfrog  | Fix it ➔ | View workflow run | Using 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.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status: ready to merge

Five review loops plus a readiness checklist at each end. 31a756ee3a8, 8 commits, 18 files, ~2204 insertions. PR Checks green on the final SHA (26 jobs, 0 failed).

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 wrong

Silent data loss in the patch parser

  • A deleted line whose content starts -- is emitted as --- , which terminated the hunk — the rest of the diff vanished and the card reported 0 added / 0 removed. native-chat-diff.ts already documents and guards this exact trap; the new parser re-derived the grammar and lost the guard. It now reuses that guard.
  • \ No newline at end of file appears mid-hunk; it also terminated the hunk, discarding every row after it.
  • A multi-file patch collapsed into one card whose header named the first file and whose gutter carried the second file's line numbers.
  • Content past the 96k cap was dropped with truncated: false, so a changed file rendered as complete and unchanged with no truncation notice.

Cards claiming edits that did not happen

  • A failed edit rendered as a successful diff card built from the intended strings, and the provider's error was suppressed entirely — strictly worse than the pre-PR view, which showed it in red.
  • git diff run through exec was reclassified as a file edit, invented the path file, and swallowed the command line.
  • A Write or Edit whose content quoted a patch envelope rendered a card for the file named inside the quote, and the real edit disappeared.
  • A row merely mentioning Moved to: claimed a rename and truncated its own text.
  • The journal clips patches at 16k — well below this module's own cap — and appends a byte-count marker. That marker rendered as numbered file content, and the last real row was a mid-line fragment shown as complete.
  • On the structured lane a multi-file edit arrives titled 2 files, which is not a path. The card now refuses that shape and falls back to the generic view rather than naming a file that does not exist.

Correctness and platform

  • CRLF: three splitters disagreed, leaving \r on every row, a phantom blank row, and a dirty clipboard. One splitter now.
  • MultiEdit never produced a card, so one turn showed two different diff presentations side by side. NotebookEdit is now deliberately excluded, with the reason in the code.
  • Non-contiguous hunks were concatenated with no separator, so the gutter jumped 42 → 310 as if continuous.
  • Several valid patch shapes made a file vanish from a multi-file envelope: an update chunk with no @@ header, and a section with no body.

Performance

  • The whole diff model, including the LCS, recomputed in the render body on every streaming token — for every historical edit, even in a collapsed group that rendered nothing. Now memoized, and a collapsed run does no diffing at all.
  • The copy text rebuilt up to 2000 rows on every render, including while collapsed. Also memoized.

CI

  • Two i18n keys were added but never used, failing verify:localization-runtime-catalog. One is now wired to the copy button (which read "Copy message" on a diff card); the other is deleted. The generated catalog is deliberately not regenerated — sync rewrites it with ~1073 deletions of pre-existing drift unrelated to this PR, and the gate passes without it.

Deliberately not changed

  • Converging the repo's four hand-rolled diff parsers. native-chat-diff.ts, native-chat-unified-patch.ts, pr-review-comment-lines.ts and mobile's mobile-diff-lines.ts all hand-roll this. The diff package is already resolved and installed in the lockfile, has no runtime dependencies of its own, and would delete ~200 lines here. That is the right shape, but it is a larger change than this PR's one thing and adding it for one module would make a fourth pattern rather than fewer. Follow-up.
  • The producer that flattens changes[]. The structured journal item joins every change into one string with a N files pseudo-path, destroying file boundaries before any renderer sees them. No parser can recover them. Fixing it is a journal/wire change and belongs in its own PR; this PR refuses the shape instead.
  • The two rename lanes disagreeing on a prose Moved to: marker with no structured move field. That marker has no producer anywhere in this repo, so its reachability cannot be settled here — recorded as unknown rather than fixed speculatively.
  • Per-file truncation flagging (currently a whole-patch flag, which over-warns — the safe direction); a card replacing a compound command that chained apply_patch with other commands; and diff cards staying expanded when sibling tool lines collapse.

Verification

pnpm tc clean. All four localization gates pass. 1854 tests green on the native-chat suites; the normalize suite went 15 → 50. check:code-quality:changed and check:react-doctor:changed both clean across 16 files. Each fix round was ablated — sources reverted with the new tests kept — to confirm the tests actually bite rather than passing vacuously.

Scope held throughout: src/shared/native-chat-diff.ts gained one export and a comment, so mobile is unaffected and still compiles unchanged.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Visual proof, re-captured after review

The screenshots in the PR body were taken against the original commit 237b7e51085. These replace them: captured against 31a756ee3a8, after the review campaign.

Driven through the production path — real JSONL on disk → real main-process decoder → real nativeChat:readSession IPC → the real native chat pane in an isolated dev instance on this branch. Not a component harness. Seeded transcripts, not live agent turns.

Renderer ownership was proved at attach and again before shutdown: /@fs returns 200 for a file inside the QA worktree and 403 for the same path in another worktree, with a single CDP page target.

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 Edit with resolved hunks — gutter 41, 42, 43, 44, 44, 45, 46

A replaced line repeats its number, which is the correct unified rule.

s1-claude-resolved-hunks-expanded-dark.png

s1-claude-resolved-hunks-expanded-light.png

Claude Edit from a snippet pair — no gutter

A snippet pair cannot say where in the file it sits, so no number is shown. Earlier in review this leaked snippet-relative numbers into the gutter, overlapping the sign column.

s2-claude-snippet-no-gutter-expanded-dark.png

s2-claude-snippet-no-gutter-expanded-light.png

A failed edit — no card, error preserved

String to replace not found in file. The generic tool view is kept and the error renders in red. This previously rendered a confident +1 −1 diff card built from the intended strings, with the error suppressed entirely.

s3-failed-edit-no-card-dark.png

git diff through a command tool — stays a command row

The command line stays visible and no card is fabricated. This previously became an Edited file card with the invented path file, swallowing the command.

s4-git-diff-command-row-dark.png

MultiEdit, two regions — ⋯ separator between them

The gutter goes 22 → 93 across the break, so the two regions do not read as continuous. MultiEdit produced no card at all before review, and hunks were concatenated with no separator.

s5-multi-hunk-gap-expanded-dark.png

Truncation visible while collapsed

Diff truncated sits on the path row, so it is legible without expanding. It previously rendered only inside the expanded body.

s6-truncated-collapsed-dark.png

Deleted file — no chevron, no empty disclosure

A *** Delete File: section has no body, so the card drops the chevron and the disclosure region. Note it also shows no +N −M: at 0 added / 0 removed DiffLineCounts renders nothing, which is correct.

s7-deleted-file-no-chevron-dark.png

Codex apply_patch through exec

Both heredoc calls render as cards rather than command rows. Worth noting the contrast in this one shot: the hunk with @@ -27,6 +27,7 @@ gets a gutter, while the bare @@ export function … form — which Codex emits often — gets none, because a bare marker carries no ranges and inventing numbers would assert false file positions. Expect a good share of real Codex cards to render without a gutter.

s8-codex-exec-apply-patch-expanded-dark.png


Not covered: live agent turns, renamed-file cards, and light theme for the last six.

@brennanb2025
brennanb2025 merged commit 172aa1a into main Sep 5, 2026
28 checks passed
Jinwoo-H added a commit that referenced this pull request Sep 6, 2026
…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
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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>
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