Files
orca/src/shared/native-chat-edit-model.ts
T
Brennan BensonandMerge Sim 172aa1ac35 feat(native-chat): render agent file edits as inline diff cards (#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>
2026-09-04 23:42:43 -07:00

108 lines
4.2 KiB
TypeScript

/** One rendered diff row. Numbers are per side: a removed row has no new-side
* number and an added row has no old-side number. `gap` marks the break
* between two regions of the file, which are otherwise concatenated and read
* as one continuous block even as the gutter jumps hundreds of lines. */
export type NativeChatEditLineKind = 'context' | 'add' | 'del' | 'gap'
export type NativeChatEditLine = {
kind: NativeChatEditLineKind
text: string
oldLineNumber: number | null
newLineNumber: number | null
}
export type NativeChatEditChangeKind = 'added' | 'deleted' | 'edited' | 'renamed'
export type NativeChatEditFile = {
path: string
/** Set only when the change moved the file. */
oldPath: string | null
changeKind: NativeChatEditChangeKind
lines: NativeChatEditLine[]
added: number
removed: number
/** False when the numbers locate a row inside a snippet rather than the file,
* which is the case whenever the provider gave us no resolved hunk ranges. */
lineNumbersKnown: boolean
truncated: boolean
}
export const MAX_EDIT_LINES = 2_000
export const MAX_EDIT_CHARS = 96_000
/** The LCS table is quadratic; above this a linear prefix/suffix diff is used. */
export const MAX_EDIT_DIFF_CELLS = 200_000
/** Rows of a source string, plus whether it was clipped before splitting. */
export type EditContentLines = { lines: string[]; truncated: boolean }
/** The one row splitter for every edit shape. Splits on both newline forms so a
* CRLF file never carries a trailing `\r` into a row, where it would render as
* a stray character, defeat the phantom-row guard, and reach the clipboard. */
export function splitEditContent(content: string): EditContentLines {
if (content.length === 0) {
return { lines: [], truncated: false }
}
const truncated = content.length > MAX_EDIT_CHARS
const body = truncated ? content.slice(0, MAX_EDIT_CHARS) : content
const lines = body.split(/\r?\n/)
// Tested against the clipped body: on the un-clipped string this popped a
// real line whenever the slice fired.
if (body.endsWith('\n')) {
lines.pop()
}
return { lines, truncated }
}
/** The break between two regions of a file. Carries no text and no position. */
function editGapLine(): NativeChatEditLine {
return { kind: 'gap', text: '', oldLineNumber: null, newLineNumber: null }
}
/** Appends a gap when rows already exist, so the break never opens a diff or
* doubles up behind an empty region. */
export function pushEditGap(lines: NativeChatEditLine[]): void {
if (lines.length > 0 && lines.at(-1)?.kind !== 'gap') {
lines.push(editGapLine())
}
}
/** Unified line numbering: a removed row is located on the old side, everything
* else on the new side. One column, so a replaced line repeats its number. */
export function unifiedLineNumber(line: NativeChatEditLine): number | null {
return line.kind === 'del' ? line.oldLineNumber : (line.newLineNumber ?? line.oldLineNumber)
}
export function finalizeEditFile(
input: Omit<NativeChatEditFile, 'added' | 'removed' | 'truncated'> & {
/** Set when the source text was clipped before it became rows. */
truncated?: boolean
}
): NativeChatEditFile {
const overLineCap = input.lines.length > MAX_EDIT_LINES
const truncated = overLineCap || input.truncated === true
const capped = overLineCap ? input.lines.slice(0, MAX_EDIT_LINES) : input.lines
// A gap marks a break between regions, so one at the end marks nothing. The
// row cap can leave one behind even when the source did not.
let end = capped.length
while (end > 0 && capped[end - 1]?.kind === 'gap') {
end -= 1
}
const trimmed = end === capped.length ? capped : capped.slice(0, end)
// Without resolved ranges the numbers locate a row inside a snippet; dropping
// them keeps a plausible-looking wrong position out of the gutter, the copy
// text, and the row keys.
const lines = input.lineNumbersKnown
? trimmed
: trimmed.map((line) => ({ ...line, oldLineNumber: null, newLineNumber: null }))
let added = 0
let removed = 0
for (const line of lines) {
if (line.kind === 'add') {
added += 1
} else if (line.kind === 'del') {
removed += 1
}
}
return { ...input, lines, added, removed, truncated }
}