Diff
A file change as hunks with old and new line numbers, in the reply or beside it — and comments on a line or a range, sent to the agent as a review.
-
<aparte-diff> -
@aparte/plugin-diff
<!-- In your app: import '@aparte/plugin-diff'. Click a line number to comment; Shift+click for a range. -->
<aparte-diff commentable></aparte-diff>
<script>
const view = document.querySelector('aparte-diff');
view.diff = {
path: 'src/parse.ts',
before: [
'export function parse(input: string): number {',
' let total = 0;',
' for (const [, amount, unit] of input.matchAll(TOKEN)) {',
' total += parseInt(amount, 10) * UNITS[unit];',
' }',
' return total;',
'}',
'',
].join('\n'),
after: [
'export function parse(input: string): number {',
' let total = 0;',
' for (const [, amount, unit] of input.matchAll(TOKEN)) {',
' total += Number(amount) * UNITS[unit];',
' }',
" if (total === 0) throw new RangeError('Nothing to parse');",
' return total;',
'}',
'',
].join('\n'),
};
// The element keeps no comment: your app does, and hands them back to be shown.
const comments = [
{ path: 'src/parse.ts', side: 'new', startLine: 4, endLine: 4, text: 'Number keeps the fraction: 1.5h is ninety minutes now.', state: 'sent' },
];
view.comments = comments;
view.addEventListener('aparte-diff-comment', (event) => {
comments.push({ ...event.detail, state: 'pending' });
view.comments = comments;
});
</script>An agent that edits files should show what it changed. <aparte-diff> shows a change the way a
reviewer reads one: each file under a header with its path and its counts (+3 −1), each line
with its old and new numbers and a + or −, and the unchanged lines between the changes folded.
With commentable, the reader picks a line or a range and writes a comment on it, and your app
sends the comments to the agent as one review.
It works beside the chat — in the other pane of a split, a tab, a dialog — and in the reply, under an edit tool’s line.
npm install @aparte/plugin-diff @aparte/core<aparte-diff></aparte-diff>import '@aparte/plugin-diff';
const view = document.querySelector('aparte-diff')!;
view.diff = {
path: 'src/parse.ts',
before: 'let total = 0;\ntotal += parseInt(amount, 10);\n',
after: 'let total = 0;\ntotal += Number(amount);\n',
};Importing the package defines the element (AparteDiff). diff takes three shapes
(AparteDiffInput):
- A file’s two texts,
{ path, before, after }(AparteDiffSource; addoldPathfor a rename). The element computes the diff, and every unchanged line can be shown: each folded run gets a “Show 24 unchanged lines” button. A side that does not exist isnull:before: nullfor a file created,after: nullfor one deleted.''is a file that exists and is empty. - A unified diff’s text, as
git diffprints it or a model returns it: several files, new, deleted, renamed and binary ones included. The folded runs then say how many lines they leave out, since the text does not hold them. - A list of files, each one either of the above as data (
AparteDiffFile) or two texts. They are shown one after the other.
Each file’s header folds it. The lines wrap rather than scroll sideways, and the code reads left to right in a right-to-left page.
Comments on a line
Section titled “Comments on a line”<aparte-diff commentable></aparte-diff>With commentable, a click on a line number opens a field under the line, and Shift+click
stretches the selection to another line. From the keyboard, the numbers of a file are one tab
stop: the arrows move between them, Shift+arrows stretch the selection, Enter or Space opens the
field, Ctrl+Enter (⌘+Enter) sends it and Escape lets go. Without commentable, nothing in the
view is clickable.
Sending fires aparte-diff-comment. Its detail (AparteDiffCommentEventDetail) says where the
comment is — path, side (AparteDiffSide: 'old' on a removed line, 'new' on the rest),
startLine, endLine — and holds its text and the code it is about. The element keeps
nothing: you keep the comments, and hand them back through comments (AparteDiffComment) to
show them under their lines, each with its state, pending or sent.
import type { AparteDiffComment } from '@aparte/plugin-diff';
const view = document.querySelector('aparte-diff')!;
const review: AparteDiffComment[] = [];
view.addEventListener('aparte-diff-comment', (event) => {
review.push({ ...event.detail, id: crypto.randomUUID(), state: 'pending' });
view.comments = review;
});
// A "Send review" button of yours: every comment, as one message to the agent.
function sendReview(send: (text: string) => void): void {
const lines = review
.filter((comment) => comment.state === 'pending')
.map((comment) => `- ${comment.path}, line ${comment.startLine}: ${comment.text}`);
if (!lines.length) return;
send(`Review of your changes:\n${lines.join('\n')}`);
for (const comment of review) comment.state = 'sent';
view.comments = review;
}<AparteUi> mounts the tag with no declaration, and useAparteEvent listens on its element:
import { useRef, useState } from 'react';
import { AparteUi, useAparteEvent, type AparteUiHandle } from '@aparte/react';
import type { AparteDiffComment } from '@aparte/plugin-diff';
export function Review({ send }: { send: (text: string) => void }) {
const view = useRef<AparteUiHandle>(null);
const [review, setReview] = useState<AparteDiffComment[]>([]);
useAparteEvent(view, 'aparte-diff-comment', (event) => {
setReview((all) => [...all, { ...event.detail, id: crypto.randomUUID(), state: 'pending' }]);
});
// A "Send review" button of yours: every comment, as one message to the agent.
function sendReview() {
const lines = review
.filter((comment) => comment.state === 'pending')
.map((comment) => `- ${comment.path}, line ${comment.startLine}: ${comment.text}`);
if (!lines.length) return;
send(`Review of your changes:\n${lines.join('\n')}`);
setReview(review.map((comment) => ({ ...comment, state: 'sent' })));
}
return (
<>
<AparteUi ref={view} name="aparte-diff" props={{ commentable: '', comments: review }} />
<button onClick={sendReview}>Send review</button>
</>
);
}<script setup lang="ts">
import { ref } from 'vue';
import '@aparte/plugin-diff';
import type { AparteDiffComment } from '@aparte/plugin-diff';
const props = defineProps<{ send: (text: string) => void }>();
const review = ref<AparteDiffComment[]>([]);
// A "Send review" button of yours: every comment, as one message to the agent.
function sendReview() {
const lines = review.value
.filter((comment) => comment.state === 'pending')
.map((comment) => `- ${comment.path}, line ${comment.startLine}: ${comment.text}`);
if (!lines.length) return;
props.send(`Review of your changes:\n${lines.join('\n')}`);
for (const comment of review.value) comment.state = 'sent';
}
</script>
<template>
<aparte-diff
commentable
:comments.prop="review"
@aparte-diff-comment="(event) => review.push({ ...event.detail, id: crypto.randomUUID(), state: 'pending' })"
/>
<button @click="sendReview">Send review</button>
</template><script lang="ts">
import '@aparte/plugin-diff';
import type { AparteDiffComment } from '@aparte/plugin-diff';
let { send }: { send: (text: string) => void } = $props();
let review = $state<AparteDiffComment[]>([]);
// A "Send review" button of yours: every comment, as one message to the agent.
function sendReview() {
const lines = review
.filter((comment) => comment.state === 'pending')
.map((comment) => `- ${comment.path}, line ${comment.startLine}: ${comment.text}`);
if (!lines.length) return;
send(`Review of your changes:\n${lines.join('\n')}`);
for (const comment of review) comment.state = 'sent';
}
</script>
<aparte-diff
commentable
comments={review}
onaparte-diff-comment={(event) => review.push({ ...event.detail, id: crypto.randomUUID(), state: 'pending' })}
></aparte-diff>
<button onclick={sendReview}>Send review</button>On Svelte 4, write the event as on:aparte-diff-comment={(event) => …}.
import { Component, CUSTOM_ELEMENTS_SCHEMA, input } from '@angular/core';
import '@aparte/plugin-diff';
import type { AparteDiffComment, AparteDiffCommentEventDetail } from '@aparte/plugin-diff';
@Component({
selector: 'app-review',
standalone: true,
schemas: [CUSTOM_ELEMENTS_SCHEMA],
template: `
<aparte-diff commentable [comments]="review" (aparte-diff-comment)="add($any($event).detail)"></aparte-diff>
<button (click)="sendReview()">Send review</button>
`,
})
export class ReviewComponent {
readonly send = input.required<(text: string) => void>();
review: AparteDiffComment[] = [];
add(detail: AparteDiffCommentEventDetail) {
this.review = [...this.review, { ...detail, id: crypto.randomUUID(), state: 'pending' }];
}
// A "Send review" button of yours: every comment, as one message to the agent.
sendReview() {
const lines = this.review
.filter((comment) => comment.state === 'pending')
.map((comment) => `- ${comment.path}, line ${comment.startLine}: ${comment.text}`);
if (!lines.length) return;
this.send()(`Review of your changes:\n${lines.join('\n')}`);
this.review = this.review.map((comment) => ({ ...comment, state: 'sent' }));
}
}Cancel the event (event.preventDefault()) to keep the field open with its text, when the comment
could not be kept.
In the reply
Section titled “In the reply”setupDiff shows an edit tool’s result as a diff under the tool’s line, opened. The row keeps its
label, its summary and its states; the change takes the place of the raw input and output.
<!-- In your app: import { setupDiff } from '@aparte/plugin-diff'. -->
<aparte-chat-bubble message-id="a1" data-role="assistant"></aparte-chat-bubble>
<script>
const { aparteGlobalConfig } = window.aparte;
const { setupDiff } = window.apartePlugins.diff;
aparteGlobalConfig.registerToolDisplay('edit_file', { summary: (call) => call.toolCall.input.path });
setupDiff({
tool: 'edit_file',
map: (result, input) => ({ path: input.path, before: result.before, after: result.after }),
});
const before = ['## Install', '', 'npm install spanwise', '', 'Durations are whole hours.', ''].join('\n');
const after = ['## Install', '', 'npm install spanwise', '', 'Durations can be decimal: 1.5h is ninety minutes.', ''].join('\n');
document.querySelector('aparte-chat-bubble').setSegments([
{ id: 's1', type: 'text', content: 'The README promised whole hours only. I changed that line.' },
{
id: 's2', type: 'tool_call', status: 'resolved',
toolCall: { id: 't1', name: 'edit_file', input: { path: 'README.md' } },
result: JSON.stringify({ before, after }),
},
]);
</script>import { setupDiff } from '@aparte/plugin-diff';
const stop = setupDiff({
tool: 'edit_file',
map: (result: { before: string; after: string }, input) => ({
path: String(input['path']),
before: result.before,
after: result.after,
}),
});DiffSetupOptions holds tool (a name, a pattern, or a list), map (the change, from the tool’s
result and the call’s input; without it, the result must already be a diff), commentable and
open (false keeps the change closed under its line) and preview (the change a call would make, for its approval question). The config comes second, the page’s by
default. Tool display has more on what sits
behind a tool’s line.
In the approval question
Section titled “In the approval question”When the edit tool needs approval, the question can show the change
before the call runs. setupDiff registers that too: it reads the call’s input, before and
after or old_string and new_string (with the file in path or file_path), and draws the
diff between the question and its buttons. Give preview for an input of another shape, or false
for none.
import { setupDiff } from '@aparte/plugin-diff';
setupDiff({
tool: 'write_file',
// The input holds the new content only: the preview is a file created.
preview: (input) => ({ path: String(input['path']), before: null, after: String(input['content']) }),
});preview returns null for a call with nothing to show, and one that throws leaves the plain
arguments.
On the server
Section titled “On the server”Three functions do the work without a page, so a server can prepare a diff and send it as data or as text:
import { diffTexts, formatUnifiedDiff, parseUnifiedDiff } from '@aparte/plugin-diff';
const file = diffTexts('a\nb\n', 'a\nc\n', { path: 'notes.txt', context: 3 });
file.added; // 1
const patch = formatUnifiedDiff(file); // the text `git apply` takes
const files = parseUnifiedDiff(patch); // back to datadiffTexts (DiffTextsOptions: context, path, oldPath) finds the fewest added and removed
lines, with three unchanged lines around each change by default, as git diff does. A file saved
with Windows line endings reads the same as one without; a last line that gains or loses its
newline shows as changed. A side given as null is a file that does not exist:
import { diffTexts } from '@aparte/plugin-diff';
diffTexts(null, 'hello\n', { path: 'notes.md' }).status; // 'added'
diffTexts('bye\n', null, { path: 'old.md' }).status; // 'deleted'
diffTexts('', 'hello\n', { path: 'empty.md' }).status; // 'modified': an empty file filled inA large file is first cut at the lines it holds once on each side, in the same order (patience
anchoring, as git diff --patience does), and each gap between them is diffed on its own: a
200,000-line file changed in a thousand places still gives a thousand small hunks, in well under a
second. A gap with thousands of changes and little in common shows as removed then added: a true
account of the change, without searching for the shortest one.
formatUnifiedDiff writes what git apply takes, with git’s new file mode and
deleted file mode headers for a file created or deleted. parseUnifiedDiff reads a rename only
where git says one (rename from and rename to, or a similarity index): a plain
diff -u x.c.orig x.c is a change to x.c.
An AparteDiffFile is { path, oldPath, status, added, removed, hunks, binary }, its status an
AparteDiffFileStatus (modified, added, deleted, renamed). Each AparteDiffHunk has its
oldStart, oldCount, newStart and newCount, the section it is in when the tool said, and
its lines: each an AparteDiffLine with its kind (AparteDiffLineKind: context, add,
del), text, oldLine, newLine, and noNewline on the last line of a file that ends without
one.
Highlighting
Section titled “Highlighting”With a highlighter installed — @aparte/plugin-shiki, or your own
setHighlightProvider — the lines are coloured in the language the file’s extension names, each
side of the change at once so a line reads in its context. Without one, they are plain text. A
highlighter installed or replaced after the view was drawn colours it then, and one that failed
(still loading its grammars) is tried again at the next change of the config.
In a framework
Section titled “In a framework”The plugin exports diffElement, the element’s spec, and every framework binds it as it binds
any plugin’s element: createAparteElement(diffElement) in React, whose props then
include diff and comments, which are properties, and onDiffComment; the tag typed from the
spec in Vue and Svelte; CUSTOM_ELEMENTS_SCHEMA in Angular.
A framework hands diff and comments again on every render, often as a new object or a new
array: review.filter((c) => c.path === file), an inline { path, before, after }. A list of the
same comments, or a change with the same texts, draws nothing, so the rows, the folds the reader
opened and the field they are writing in stay as they are. A comment changed in place and handed
back is drawn.
Customize
Section titled “Customize”The view is light DOM, like the chat: its classes are aparte-diff-*, and its buttons and field
are the kit’s. Five tokens set its tints, each falling back to one of core’s, so a theme that moves
the success and error colours moves the diff:
aparte-diff {
--aparte-diff-added-bg: var(--aparte-success-surface);
--aparte-diff-removed-bg: var(--aparte-error-surface);
--aparte-diff-added-ink: var(--aparte-success-ink);
--aparte-diff-removed-ink: var(--aparte-error-ink);
--aparte-diff-selected-bg: var(--aparte-surface-hover);
}The two line numbers sit in .aparte-diff-line__gutter, each in an .aparte-diff-line__num with
data-side="old" or data-side="new". The view is light DOM, so a rule reaches them as it reaches
the rest, a rule between the two columns for one:
aparte-diff .aparte-diff-line__num[data-side='old'] {
border-inline-end: var(--aparte-border-width) solid var(--aparte-border);
}Its words are in the ten languages the locales ship, in the chat’s
language. Change one with extendLocale, under its key (diffCommentSubmit, diffShowUnchanged…).
Accessibility
Section titled “Accessibility”A screen reader hears each + and − as “added” and “removed”, and each file’s counts as
“3 lines added, 1 line removed”. Each header is a button that says whether its file is open. With
commentable, each line number is a button named for its line (“Added line 13”), described by the
line’s code and pressed while it is picked for a comment; the field is labelled with the lines it
is about.
<aparte-diff> · class AparteDiff
Attributes
| Attribute | Description |
|---|---|
commentable | Let the reader pick a line or a range and write a comment on it. Off by default: without it nothing is clickable. |
Properties
| Property | Type | Description |
|---|---|---|
diff | AparteDiffInput | null | The change to show: a unified diff’s text, { path, before, after }, or a list of files (AparteDiffFile or texts). |
comments | AparteDiffComment[] | The comments to show under their lines, with their state. The element only shows them. |
commentable | boolean | Whether a reader can comment on a line. Reflects the commentable attribute. |
Events
| Event | Type | Description |
|---|---|---|
aparte-diff-comment | CustomEvent<AparteDiffCommentEventDetail> | A comment was written and sent: { path, side, startLine, endLine, text, code }. Bubbles out of the chat; cancel it to keep the field open with its text. |
CSS variables
| Variable | Default | Description |
|---|---|---|
--aparte-diff-added-bg | var(--aparte-success-surface) | The background of an added line. |
--aparte-diff-removed-bg | var(--aparte-error-surface) | The background of a removed line. |
--aparte-diff-added-ink | var(--aparte-success-ink) | The + of an added line, and the count of added lines. |
--aparte-diff-removed-ink | var(--aparte-error-ink) | The − of a removed line, and the count of removed lines. |
--aparte-diff-selected-bg | var(--aparte-surface-hover) | The background of the lines picked for a comment. |
Related
Section titled “Related”- Tool display — what sits behind a tool’s line in the reply.
- Split — the two panes a review view usually sits in.
- Code block — code with no change to show.