297 lines
15 KiB
JavaScript
297 lines
15 KiB
JavaScript
// Step by step: Claude's file changes shown as a diff in the editor, one step at a time (mode "Step by step" of the Claude window).
|
||
//
|
||
// Claude Code asks the IDE before every Edit / MultiEdit / Write (claude --permission-prompt-tool, AgentTools.tool_permission).
|
||
// Nothing is written until the user answers: the file opens at the change, what Claude removes in red (in place), what it
|
||
// adds in green (a block under it), each block with its own tick; the card in the conversation has Accept / Decline and a
|
||
// message for Claude ("not that way: ..."). An accepted step is kept (the conversation shows it with the request that led to it)
|
||
// and can be rolled back on its own, whatever came after it.
|
||
import { monaco } from './editor.js';
|
||
import { backend } from './backend.js';
|
||
import { el, icon, notify, confirm } from './ui.js';
|
||
|
||
/** Edit / MultiEdit / Write: the tools this mode holds back. */
|
||
export const STEP_TOOLS = ['Edit', 'MultiEdit', 'Write'];
|
||
|
||
/** The text with the first (or every) `old` replaced by `next` (no `$` patterns). */
|
||
function replaceText(text, old, next, all) {
|
||
return all ? text.split(old).join(next) : text.replace(old, () => next);
|
||
}
|
||
|
||
function count(text, needle) {
|
||
if (!needle) return 0;
|
||
let n = 0;
|
||
for (let i = text.indexOf(needle); i !== -1; i = text.indexOf(needle, i + needle.length)) n++;
|
||
return n;
|
||
}
|
||
|
||
/**
|
||
* What a tool call would do to a file whose text is `before` (null = it does not exist).
|
||
* @return {{before: ?string, after: string, hunks: object[]} | {error: string}}
|
||
*/
|
||
export function planStep(name, input, before) {
|
||
if (name === 'Write') {
|
||
const after = String(input.content ?? '');
|
||
return { before, after, hunks: [{ kind: 'write', old: before ?? '', new: after, index: 0 }] };
|
||
}
|
||
const edits = name === 'MultiEdit' ? (Array.isArray(input.edits) ? input.edits : []) : [input];
|
||
if (!edits.length) return { error: 'no edit' };
|
||
let text = before ?? '';
|
||
const hunks = [];
|
||
for (const [index, e] of edits.entries()) {
|
||
const old = String(e.old_string ?? '');
|
||
const next = String(e.new_string ?? '');
|
||
if (old === '') {
|
||
if (text !== '' && before !== null) return { error: 'empty old_string on a file that has text' };
|
||
text = next;
|
||
hunks.push({ kind: 'edit', old: '', new: next, all: false, index });
|
||
continue;
|
||
}
|
||
if (!text.includes(old)) return { error: 'old_string not found' };
|
||
text = replaceText(text, old, next, !!e.replace_all);
|
||
hunks.push({ kind: 'edit', old, new: next, all: !!e.replace_all, index });
|
||
}
|
||
return { before, after: text, hunks };
|
||
}
|
||
|
||
/** The text after only the accepted blocks of a plan (`keep`: their indexes). */
|
||
export function applyHunks(before, hunks, keep) {
|
||
let text = before ?? '';
|
||
for (const h of hunks) {
|
||
if (!keep.has(h.index)) continue;
|
||
if (h.kind === 'write') return h.new;
|
||
text = h.old === '' ? h.new : replaceText(text, h.old, h.new, h.all);
|
||
}
|
||
return text;
|
||
}
|
||
|
||
/**
|
||
* Takes a step back: what the file is now without it. By its text when the file is still as the step left it,
|
||
* else by undoing each change where it still is. {text: string|null} (null = the file did not exist before), or {error}.
|
||
*/
|
||
export function reverseStep(step, current) {
|
||
if (step.after != null && current === step.after) return { text: step.before ?? null };
|
||
if (step.kind === 'write') {
|
||
return step.after == null ? { error: 'this step is not kept any more (the IDE was closed): restore the file from the Local History' } : { error: 'the file changed since this step' };
|
||
}
|
||
let text = current;
|
||
for (const h of [...step.hunks].reverse()) {
|
||
if (h.new === '') return { error: 'a deletion cannot be found again in the file as it is now' };
|
||
const n = count(text, h.new);
|
||
if (h.all ? n < 1 : n !== 1) return { error: 'the file changed since this step' };
|
||
text = replaceText(text, h.new, h.old, h.all);
|
||
}
|
||
return { text };
|
||
}
|
||
|
||
/** Lines: {start (1-based, in `text`), end} of the first `needle`. */
|
||
function lineSpan(text, needle) {
|
||
const at = text.indexOf(needle);
|
||
if (at < 0) return null;
|
||
const start = text.slice(0, at).split('\n').length;
|
||
const body = needle.endsWith('\n') ? needle.slice(0, -1) : needle;
|
||
return { start, end: start + body.split('\n').length - 1 };
|
||
}
|
||
|
||
/** A Write over an existing file: only the lines that differ (the common top and bottom are trimmed). */
|
||
function trimDiff(before, after) {
|
||
const a = before.split('\n');
|
||
const b = after.split('\n');
|
||
let top = 0;
|
||
while (top < a.length && top < b.length && a[top] === b[top]) top++;
|
||
let bottom = 0;
|
||
while (bottom < a.length - top && bottom < b.length - top && a[a.length - 1 - bottom] === b[b.length - 1 - bottom]) bottom++;
|
||
return { start: top + 1, removed: a.slice(top, a.length - bottom), added: b.slice(top, b.length - bottom) };
|
||
}
|
||
|
||
/** What each block shows in the editor: the red lines (range in the file as it is now) and the green text under them. */
|
||
function layout(plan) {
|
||
const out = [];
|
||
for (const h of plan.hunks) {
|
||
if (h.kind === 'write') {
|
||
if (plan.before === null) { out.push({ hunk: h, range: null, added: h.new.split('\n') }); continue; }
|
||
const d = trimDiff(plan.before, plan.after);
|
||
out.push({ hunk: h, range: d.removed.length ? { start: d.start, end: d.start + d.removed.length - 1 } : null, after: d.start - 1, added: d.added });
|
||
continue;
|
||
}
|
||
const span = h.old ? lineSpan(plan.before ?? '', h.old) : null;
|
||
out.push({ hunk: h, range: span, after: span ? span.end : 0, added: h.new === '' ? [] : h.new.replace(/\n$/, '').split('\n') });
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/** The steps' data kept while the IDE is open (the conversation keeps only what is needed to roll back). */
|
||
const memory = new Map(); // step id -> {before, after}
|
||
const draws = new WeakMap(); // step item -> redraw()
|
||
const pending = new Map(); // step id -> controller {toggle(i), answer(accept, message), keep:Set}
|
||
|
||
let seq = 0;
|
||
export const newStepId = () => `s${Date.now().toString(36)}${(seq++).toString(36)}`;
|
||
|
||
/** The step card's redraw after its item changed. */
|
||
function redraw(item) { draws.get(item)?.(); }
|
||
export const redrawStep = redraw;
|
||
|
||
export class EditReview {
|
||
constructor(app) {
|
||
this.app = app;
|
||
this.open = new Map(); // step id -> {cleanup}
|
||
}
|
||
|
||
/** The editor widget showing a model, if one does. */
|
||
editorOf(model) {
|
||
return this.app.editors.groups.find((g) => g.editor?.getModel() === model)?.editor || null;
|
||
}
|
||
|
||
/**
|
||
* Shows the change and waits for the answer.
|
||
* @return {Promise<{keep: Set<number>, message: string}>}
|
||
*/
|
||
async ask(item, plan, conv) {
|
||
const path = item.path;
|
||
const editors = this.app.editors;
|
||
const blocks = layout(plan);
|
||
const keep = new Set(plan.hunks.map((h) => h.index));
|
||
let marks = null;
|
||
try {
|
||
if (plan.before === null) {
|
||
await editors.openDiff(path, { original: '', modified: plan.after, readOnly: true, title: `${path} (new file)` });
|
||
} else {
|
||
const first = blocks.find((b) => b.range);
|
||
await editors.open(path, { preview: true, focus: false, ...(first ? { line: first.range.start, endLine: first.range.end, select: false } : {}) });
|
||
this.app.tree?.reveal(path);
|
||
const model = editors.files.get(path)?.model;
|
||
const editor = model ? this.editorOf(model) : null;
|
||
if (editor && !model.isDisposed()) marks = this.mark(editor, model, blocks, keep, item);
|
||
}
|
||
} catch (e) {
|
||
console.warn('[step review]', e);
|
||
}
|
||
return new Promise((resolve) => {
|
||
const done = (accept, message) => {
|
||
pending.delete(item.id);
|
||
marks?.();
|
||
resolve({ keep: accept ? keep : new Set(), message: String(message || '').trim() });
|
||
};
|
||
pending.set(item.id, {
|
||
keep, blocks, plan,
|
||
toggle: (i) => { keep.has(i) ? keep.delete(i) : keep.add(i); item.keep = [...keep]; marks?.refresh?.(); redraw(item); },
|
||
answer: done,
|
||
});
|
||
item.keep = [...keep];
|
||
conv.addStep(item);
|
||
this.app.showTool('claude', true);
|
||
notify(`${path}: ${item.added} added, ${item.removed} removed`, 'info', { title: 'Claude proposes a change' });
|
||
});
|
||
}
|
||
|
||
/** Red lines + green blocks (with a tick each) in the editor; returns the function that removes them. */
|
||
mark(editor, model, blocks, keep, item) {
|
||
const lineHeight = editor.getOption(monaco.editor.EditorOption.lineHeight);
|
||
const zones = [];
|
||
const decorations = [];
|
||
const paint = () => {
|
||
zones.forEach((z) => z.refresh());
|
||
const ids = model.deltaDecorations(decorations.splice(0), blocks.filter((b) => b.range).map((b) => ({
|
||
range: new monaco.Range(Math.min(b.range.start, model.getLineCount()), 1, Math.min(b.range.end, model.getLineCount()), 1),
|
||
options: { isWholeLine: true, className: `claude-del${keep.has(b.hunk.index) ? '' : ' off'}`, linesDecorationsClassName: 'claude-del-gutter',
|
||
overviewRuler: { color: '#e5534b', position: monaco.editor.OverviewRulerLane.Right } },
|
||
})));
|
||
decorations.push(...ids);
|
||
};
|
||
editor.changeViewZones((accessor) => {
|
||
for (const b of blocks) {
|
||
const after = Math.min(b.after ?? 0, model.getLineCount());
|
||
const dom = el('div.claude-add');
|
||
const head = el('div.claude-add-head');
|
||
const tick = el('input', { type: 'checkbox', checked: true, title: 'Apply this block', onchange: () => pending.get(item.id)?.toggle(b.hunk.index) });
|
||
head.append(tick, el('span', {}, b.added.length ? `Claude adds ${b.added.length} line${b.added.length > 1 ? 's' : ''}` : 'Claude removes the lines above'));
|
||
dom.append(head, ...b.added.map((l) => el('div.claude-add-line', { style: { height: lineHeight + 'px', lineHeight: lineHeight + 'px' } }, l || ' ')));
|
||
const id = accessor.addZone({ afterLineNumber: after, heightInLines: b.added.length + 1, domNode: dom, suppressMouseDown: false });
|
||
zones.push({ id, dom, refresh: () => { const on = keep.has(b.hunk.index); tick.checked = on; dom.classList.toggle('off', !on); } });
|
||
}
|
||
});
|
||
paint();
|
||
const cleanup = () => {
|
||
if (!model.isDisposed()) model.deltaDecorations(decorations.splice(0), []);
|
||
editor.changeViewZones((accessor) => zones.forEach((z) => accessor.removeZone(z.id)));
|
||
};
|
||
cleanup.refresh = paint;
|
||
return cleanup;
|
||
}
|
||
|
||
/** The turn ended (stopped, new settings): a question left open is declined. */
|
||
cancelAll() {
|
||
for (const [id, ctl] of [...pending]) {
|
||
ctl.answer(false, 'The turn ended before the answer.');
|
||
pending.delete(id);
|
||
}
|
||
}
|
||
}
|
||
|
||
/** What a step keeps for a later rollback. */
|
||
export function remember(id, plan) { memory.set(id, { before: plan.before, after: plan.after }); }
|
||
export const hasPending = (id) => pending.has(id);
|
||
|
||
/** Roll one step back, whatever came after it. */
|
||
export async function rollback(app, item) {
|
||
const file = await backend.invoke('file.read', { path: item.path }).catch(() => null);
|
||
const current = file?.content ?? null;
|
||
const kept = memory.get(item.id);
|
||
const step = { kind: item.name === 'Write' ? 'write' : 'edit', hunks: item.hunks || [], before: kept ? kept.before : item.writeBefore, after: kept?.after };
|
||
if (current === null && step.after != null) return notify(`${item.path} does not exist any more`, 'error');
|
||
const r = reverseStep(step, current ?? '');
|
||
if (r.error) { notify(`Cannot roll back: ${r.error}`, 'error', { title: item.path }); return false; }
|
||
if (!await confirm('Roll back this step?', `${item.path}: ${r.text === null ? 'the file Claude created is deleted' : 'what this step changed goes back to how it was'}. The other steps stay.`, { ok: 'Roll back', danger: true })) return false;
|
||
if (r.text === null) await backend.invoke('file.delete', { path: item.path });
|
||
else await backend.invoke('file.write', { path: item.path, content: r.text });
|
||
await app.editors.reloadFromDisk([item.path]);
|
||
app.tree?.refresh();
|
||
item.status = 'rolled';
|
||
redraw(item);
|
||
return true;
|
||
}
|
||
|
||
/** The card of a step in the conversation: what it changes, the request that led to it, and what can be done with it. */
|
||
export function stepCard(app, item, conv) {
|
||
const box = el('div.claude-step');
|
||
const draw = () => {
|
||
box.replaceChildren();
|
||
box.className = `claude-step ${item.status}`;
|
||
const ctl = pending.get(item.id);
|
||
const status = { pending: 'waiting for you', accepted: 'applied', partial: 'applied in part', declined: 'declined', rolled: 'rolled back', ended: 'not answered' }[item.status] || item.status;
|
||
box.append(el('div.claude-step-head', {},
|
||
el('b', {}, `Step ${item.n}`), el('a.claude-step-file', { title: 'Open the file', onclick: () => app.editors.open(item.path, { preview: true }) }, item.path),
|
||
el('span.claude-step-count', {}, el('span.add', {}, `+${item.added}`), ' ', el('span.del', {}, `−${item.removed}`)),
|
||
el('span.claude-step-status', {}, status)));
|
||
if (item.ask) box.append(el('div.claude-step-ask', { title: item.ask }, `↳ ${item.ask.slice(0, 140)}`));
|
||
if (ctl) {
|
||
if (item.hunks.length > 1) {
|
||
box.append(el('div.claude-step-hunks', {}, ...item.hunks.map((h, i) => el('label', {},
|
||
el('input', { type: 'checkbox', checked: (item.keep || []).includes(h.index), onchange: () => ctl.toggle(h.index) }),
|
||
` ${i + 1}. ${(h.old || h.new).split('\n')[0].trim().slice(0, 70) || '…'}`))));
|
||
}
|
||
const message = el('input.input.small', { placeholder: 'Tell Claude why / what to do instead (optional)', onkeydown: (e) => { if (e.key === 'Enter') decline.click(); } });
|
||
const accept = el('button.btn.small.primary', { onclick: () => ctl.answer(true, message.value) }, icon('check'), item.hunks.length > 1 ? ' Apply the ticked blocks' : ' Accept');
|
||
const decline = el('button.btn.small', { onclick: () => ctl.answer(false, message.value) }, 'Decline');
|
||
box.append(el('div.claude-step-actions', {}, message, accept, decline));
|
||
} else if (item.status === 'accepted' || item.status === 'partial') {
|
||
box.append(el('div.claude-step-actions', {},
|
||
el('button.btn.small', { onclick: () => showDiff(app, item) }, 'See the diff'),
|
||
el('button.btn.small', { onclick: () => rollback(app, item) }, 'Roll back')));
|
||
} else if (item.status === 'declined' || item.status === 'ended') {
|
||
box.append(el('div.claude-step-actions', {}, el('button.btn.small', { onclick: () => showDiff(app, item) }, 'See what was proposed')));
|
||
}
|
||
};
|
||
draws.set(item, draw);
|
||
draw();
|
||
return box;
|
||
}
|
||
|
||
/** A step's diff in an editor tab (the text of the file before and after), else the blocks as they were proposed. */
|
||
function showDiff(app, item) {
|
||
const kept = memory.get(item.id);
|
||
if (kept) return app.editors.openDiff(item.path, { original: kept.before ?? '', modified: kept.after, readOnly: true, title: `${item.path} (step ${item.n})` });
|
||
const before = item.hunks.map((h) => h.old).join('\n…\n');
|
||
const after = item.hunks.map((h) => h.new).join('\n…\n');
|
||
return app.editors.openDiff(item.path, { original: before, modified: after, readOnly: true, title: `${item.path} (step ${item.n})` });
|
||
}
|