Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1df3d2c154 | |||
| 656089432f | |||
| f4594daa6f | |||
| 38053239fa | |||
| 65293326c8 | |||
| e5992840d2 | |||
| 8c6e7822b4 | |||
| ddbbb7aec3 | |||
| 930b4ab056 | |||
| 6d54963f15 | |||
| 92ff4dd4ac | |||
| bea9fd5148 |
@@ -8,6 +8,3 @@ test/e2e/fixtures/workspace/.threads/
|
||||
|
||||
# Sandbox playground churn (the EDH workspace - play freely, commit nothing)
|
||||
sandbox/.threads/
|
||||
|
||||
# brainstorming visual-companion scratch
|
||||
.superpowers/
|
||||
|
||||
@@ -1,827 +0,0 @@
|
||||
# Author-colored track changes Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Render every change as a track-changes diff where **style = operation** (underline = inserted, strikethrough = removed) and **color = author** (human green/red, Claude blue/purple), in both the rendered preview pane and the main editor pane.
|
||||
|
||||
**Architecture:** Fuse the two color systems that exist today — the *semantic* diff (green=add/red=remove) and the *authorship* tint (cw-by-claude/cw-by-human) — into one author-colored diff. Insertions are colored by their attribution span (data already exists). Deletions are colored by an **adjacency heuristic**: a struck run inherits the author of the insertion it is paired with in the same changed hunk; a standalone removed block falls back to neutral. Phase 1 does this in the pure render engine (preview). Phase 2 reverses INV-32 to bring the same author-colored track changes inline into the editor.
|
||||
|
||||
**Tech Stack:** TypeScript, VS Code extension API, `markdown-it`, `diff` (jsdiff), vitest (unit), Playwright/electron host harness (E2E). Render engine (`src/trackChangesModel.ts`) is pure and vscode-free.
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- **Render engine stays pure / vscode-free / deterministic** — `src/trackChangesModel.ts` must not import `vscode`; same inputs → identical HTML (INV-22).
|
||||
- **Author color mapping (verbatim):** human added `#3fb950` / human removed `#f85149` / Claude added `#58a6ff` / Claude removed `#bc8cff`. Insert = 2px underline in the author color + faint author-hued background; remove = line-through in the author color + faint background.
|
||||
- **Convention:** underline = inserted, strikethrough = removed, color = author.
|
||||
- **"Color means changed since the pinned baseline."** Unchanged-since-baseline text renders plain (no author coloring). The pin→clean behavior (#48) is preserved: a pinned, zero-diff doc renders with no annotation.
|
||||
- **Deletion authorship = adjacency heuristic** (locked decision): paired deletions inherit the paired insertion's author; standalone deletions render neutral.
|
||||
- **Two roles only:** `human` and `claude` (`AuthorKind`). No arbitrary palettes, no user-configurable colors (YAGNI).
|
||||
- **Test command:** `npm test` (vitest, unit). E2E: `npm run test:e2e`. Typecheck: `npm run typecheck`.
|
||||
- Commit after each task. Branch off `main` (do not commit to `main` directly).
|
||||
|
||||
---
|
||||
|
||||
# Phase 1 — Preview pane (independently shippable)
|
||||
|
||||
Delivers the full author-colored track-changes language in the rendered preview, where the attribution data already exists.
|
||||
|
||||
## File Structure (Phase 1)
|
||||
|
||||
- `src/trackChangesModel.ts` — add `authorAt()` + `wordDiffByAuthor()` pure helpers; route the review path through them; color proposal blocks by author; stop coloring unchanged blocks. Add `author?` to `ProposalView`.
|
||||
- `src/trackChangesPreview.ts` — pass each proposal's author into its `ProposalView`.
|
||||
- `media/preview.css` — author×operation classes; retire the semantic green/red and flat authorship tints.
|
||||
- `test/trackChangesModel.test.ts` — new unit tests; update tests asserting old semantic classes.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: `authorAt()` + `wordDiffByAuthor()` pure helpers
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/trackChangesModel.ts` (add after `wordMergedMarkdown`, ~line 475)
|
||||
- Test: `test/trackChangesModel.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: existing `AuthorKind`, `AuthorSpan` (trackChangesModel.ts:557-562), `diffWordsWithSpace` (already imported, line 12).
|
||||
- Produces:
|
||||
- `authorAt(offset: number, spans: AuthorSpan[]): AuthorKind | null` — the author whose span covers `offset` (half-open), else null.
|
||||
- `wordDiffByAuthor(beforeRaw: string, afterRaw: string, afterStart: number, spans: AuthorSpan[]): string` — inline HTML where each inserted run is `<ins class="cw-ins-{author}">` (author looked up at the run's `afterStart`-relative landed offset) and each removed run is `<del class="cw-del-{author}">` (author = the insertion it's paired with in the same change cluster; `cw-del-none` if standalone). Unchanged parts are emitted verbatim.
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
Add to `test/trackChangesModel.test.ts` (import `authorAt`, `wordDiffByAuthor` from `../src/trackChangesModel`):
|
||||
|
||||
```ts
|
||||
describe("authorAt", () => {
|
||||
const spans: AuthorSpan[] = [
|
||||
{ start: 0, end: 5, author: "human" },
|
||||
{ start: 5, end: 10, author: "claude" },
|
||||
];
|
||||
test("returns the covering span's author (half-open)", () => {
|
||||
expect(authorAt(0, spans)).toBe("human");
|
||||
expect(authorAt(4, spans)).toBe("human");
|
||||
expect(authorAt(5, spans)).toBe("claude");
|
||||
expect(authorAt(9, spans)).toBe("claude");
|
||||
});
|
||||
test("returns null outside any span", () => {
|
||||
expect(authorAt(10, spans)).toBeNull();
|
||||
expect(authorAt(-1, spans)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("wordDiffByAuthor", () => {
|
||||
test("an inserted run is colored by the author covering its landed offset", () => {
|
||||
// before "hello " ; after "hello brave " ; "brave " inserted at landed offset 6..12
|
||||
const spans: AuthorSpan[] = [{ start: 6, end: 12, author: "claude" }];
|
||||
const html = wordDiffByAuthor("hello ", "hello brave ", 0, spans);
|
||||
expect(html).toContain('<ins class="cw-ins-claude">brave </ins>');
|
||||
expect(html).toContain("hello ");
|
||||
});
|
||||
test("a paired deletion inherits the paired insertion's author (adjacency)", () => {
|
||||
// "light" -> "dark", both in one cluster; "dark" is claude-inserted
|
||||
const spans: AuthorSpan[] = [{ start: 0, end: 4, author: "claude" }];
|
||||
const html = wordDiffByAuthor("light", "dark", 0, spans);
|
||||
expect(html).toContain('<del class="cw-del-claude">light</del>');
|
||||
expect(html).toContain('<ins class="cw-ins-claude">dark</ins>');
|
||||
});
|
||||
test("a standalone deletion (no paired insertion) is neutral", () => {
|
||||
const html = wordDiffByAuthor("keep this word", "keep word", 0, []);
|
||||
expect(html).toContain('<del class="cw-del-none">this </del>');
|
||||
expect(html).not.toContain("cw-del-human");
|
||||
expect(html).not.toContain("cw-del-claude");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `npm test -- trackChangesModel`
|
||||
Expected: FAIL — `authorAt`/`wordDiffByAuthor` not exported.
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
Add to `src/trackChangesModel.ts` after `wordMergedMarkdown` (line 475):
|
||||
|
||||
```ts
|
||||
/** The author whose span covers `offset` (half-open [start,end)), or null. */
|
||||
export function authorAt(offset: number, spans: AuthorSpan[]): AuthorKind | null {
|
||||
for (const s of spans) if (offset >= s.start && offset < s.end) return s.author;
|
||||
return null;
|
||||
}
|
||||
|
||||
const insClass = (a: AuthorKind | null): string => `cw-ins-${a ?? "none"}`;
|
||||
const delClass = (a: AuthorKind | null): string => `cw-del-${a ?? "none"}`;
|
||||
|
||||
/**
|
||||
* Author-colored word diff for a changed PROSE block in the review.
|
||||
* `afterStart` is the landed-text offset of `afterRaw[0]` so an inserted run's
|
||||
* offset maps into `spans`. Insertions are colored by the author covering their
|
||||
* offset; deletions inherit the author of the insertion they are paired with in
|
||||
* the same contiguous change cluster (adjacency heuristic) — `cw-del-none` when a
|
||||
* cluster has no insertion. Pure, deterministic.
|
||||
*/
|
||||
export function wordDiffByAuthor(
|
||||
beforeRaw: string,
|
||||
afterRaw: string,
|
||||
afterStart: number,
|
||||
spans: AuthorSpan[],
|
||||
): string {
|
||||
const parts = diffWordsWithSpace(beforeRaw, afterRaw);
|
||||
// First pass: find each change cluster's insertion author (first added run).
|
||||
// A cluster is a maximal run of added/removed parts bounded by unchanged parts.
|
||||
let afterOff = afterStart;
|
||||
const clusterAuthor: (AuthorKind | null)[] = []; // per part index, the cluster's del author
|
||||
{
|
||||
let off = afterStart;
|
||||
let i = 0;
|
||||
while (i < parts.length) {
|
||||
const p = parts[i];
|
||||
if (!p.added && !p.removed) {
|
||||
clusterAuthor[i] = null;
|
||||
off += p.value.length;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
// a cluster: scan to its end, capturing the first added run's author
|
||||
let j = i;
|
||||
let author: AuthorKind | null = null;
|
||||
let scanOff = off;
|
||||
while (j < parts.length && (parts[j].added || parts[j].removed)) {
|
||||
if (parts[j].added && author === null) author = authorAt(scanOff, spans);
|
||||
if (parts[j].added) scanOff += parts[j].value.length;
|
||||
j++;
|
||||
}
|
||||
for (let k = i; k < j; k++) clusterAuthor[k] = author;
|
||||
off = scanOff;
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
// Second pass: emit.
|
||||
const out: string[] = [];
|
||||
parts.forEach((p, i) => {
|
||||
if (p.added) {
|
||||
const a = authorAt(afterOff, spans);
|
||||
out.push(`<ins class="${insClass(a)}">${p.value}</ins>`);
|
||||
afterOff += p.value.length;
|
||||
} else if (p.removed) {
|
||||
out.push(`<del class="${delClass(clusterAuthor[i] ?? null)}">${p.value}</del>`);
|
||||
} else {
|
||||
out.push(p.value);
|
||||
afterOff += p.value.length;
|
||||
}
|
||||
});
|
||||
return out.join("");
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
Run: `npm test -- trackChangesModel`
|
||||
Expected: PASS (new describes green).
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/trackChangesModel.ts test/trackChangesModel.test.ts
|
||||
git commit -m "feat: authorAt + wordDiffByAuthor pure helpers (author-colored word diff w/ adjacency del)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Route the review path through `wordDiffByAuthor`; stop coloring unchanged blocks
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/trackChangesModel.ts` — `renderReviewOp` (769-780), the `colored` closure + changed-op handling in `renderReview` (889-897)
|
||||
- Test: `test/trackChangesModel.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `wordDiffByAuthor` (Task 1), `landedSpans` + `ranges` already computed in `renderReview`.
|
||||
- Produces: review HTML where changed prose blocks emit `cw-ins-{author}`/`cw-del-{author}`, added blocks are author-colored as insertions, and **unchanged blocks render plain**.
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
Add to the `renderReview` describe in `test/trackChangesModel.test.ts`:
|
||||
|
||||
```ts
|
||||
test("renderReview: a changed prose block colors ins/del by author (claude replace)", () => {
|
||||
// baseline "light" -> current "dark"; "dark" attributed to claude at 0..4
|
||||
const html = renderReview("light", "dark", [{ start: 0, end: 4, author: "claude" }], []);
|
||||
expect(html).toContain('cw-ins-claude');
|
||||
expect(html).toContain('cw-del-claude'); // adjacency: struck "light" inherits claude
|
||||
});
|
||||
|
||||
test("renderReview: an unchanged block renders plain (no author coloring)", () => {
|
||||
const doc = "Alpha stays.";
|
||||
const html = renderReview(doc, doc, [{ start: 0, end: 12, author: "human" }], []);
|
||||
expect(html).not.toContain("cw-by-");
|
||||
expect(html).not.toContain("cw-ins-");
|
||||
});
|
||||
|
||||
test("renderReview: an added block is author-colored as an insertion", () => {
|
||||
// baseline empty-ish -> add a new paragraph authored by human
|
||||
const html = renderReview("Keep.", "Keep.\n\nFresh line.", [{ start: 6, end: 17, author: "human" }], []);
|
||||
expect(html).toContain("cw-ins-human");
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `npm test -- trackChangesModel`
|
||||
Expected: FAIL — changed blocks still emit plain `<ins>/<del>` via `wordMergedMarkdown`; unchanged blocks still carry `cw-by-*`.
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
In `src/trackChangesModel.ts`:
|
||||
|
||||
**(a)** Change `renderReviewOp` (769-780) so a changed PROSE block uses author coloring. Give it the colored-insertion path for `added` and the author word-diff for non-atomic `changed`. Replace the function body:
|
||||
|
||||
```ts
|
||||
function renderReviewOp(
|
||||
op: BlockOp,
|
||||
render: (src: string) => string,
|
||||
colored: (raw: string) => string,
|
||||
src: string,
|
||||
changedHtml?: string,
|
||||
): string {
|
||||
// A non-atomic changed prose block is pre-rendered with author-colored ins/del
|
||||
// (changedHtml). Removed blocks and atomic changed fences stay neutral via renderOp
|
||||
// (standalone deletion → neutral, per the adjacency heuristic). `src` is "" for a
|
||||
// removed block (no live source — INV-36).
|
||||
if (op.kind === "changed" && !op.atomic && changedHtml !== undefined) {
|
||||
return `<div class="cw-blk cw-changed"${src}>${changedHtml}</div>`;
|
||||
}
|
||||
if (op.kind === "removed" || op.kind === "changed") return renderOp(op, render, src);
|
||||
return `<div class="cw-blk ${op.kind === "added" ? "cw-added" : "cw-unchanged"}"${src}>${colored(op.block.raw)}</div>`;
|
||||
}
|
||||
```
|
||||
|
||||
**(b)** In `renderReview` (the loop at 889-897), compute the author-colored changed HTML and stop coloring unchanged blocks. Replace the loop body:
|
||||
|
||||
```ts
|
||||
let ci = 0; // pointer into ranges; advances for every op with a current-side block
|
||||
const bodyParts: string[] = [];
|
||||
for (const op of ops) {
|
||||
const blockIndex = op.kind === "removed" ? -1 : ci;
|
||||
const blk = op.kind === "removed" ? undefined : ranges[ci++];
|
||||
// Only ADDED blocks are author-colored (they are insertions since baseline);
|
||||
// UNCHANGED blocks render plain (color means "changed since baseline").
|
||||
const colored = (raw: string): string =>
|
||||
blk && !clean && op.kind === "added" ? colorByAuthor(raw, blk.start, landedSpans, render) : render(raw);
|
||||
// A non-atomic changed prose block: author-colored word diff (ins by author,
|
||||
// del by adjacency). `blk.start` is the landed offset of the after-side text.
|
||||
const changedHtml =
|
||||
op.kind === "changed" && !op.atomic && blk && !clean
|
||||
? render(wordDiffByAuthor(op.before.raw, op.block.raw, blk.start, landedSpans))
|
||||
: undefined;
|
||||
bodyParts.push(renderReviewOp(op, render, colored, srcAttr(blk), changedHtml));
|
||||
const here = blockIndex >= 0 ? byBlock.get(blockIndex) : undefined;
|
||||
if (here) for (const p of here) bodyParts.push(proposalBlockHtml(p, render));
|
||||
}
|
||||
for (const p of trailing) bodyParts.push(proposalBlockHtml(p, render));
|
||||
return bodyParts.join("\n");
|
||||
```
|
||||
|
||||
> Note: `render(wordDiffByAuthor(...))` passes the HTML-bearing string through markdown-it (same as `wordMergedMarkdown` was rendered). `colorByAuthor` on added blocks emits `cw-by-{author}` spans — Task 4 restyles those to insert styling in CSS.
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
Run: `npm test -- trackChangesModel`
|
||||
Expected: PASS for the new tests.
|
||||
|
||||
- [ ] **Step 5: Update tests that assert the OLD review markup**
|
||||
|
||||
Two existing tests assert the old semantic output (test/trackChangesModel.test.ts:226-232). Update them:
|
||||
|
||||
```ts
|
||||
test("renderReview: human addition since baseline renders author-colored ins", () => {
|
||||
const html = renderReview("hello", "hello world", [{ start: 6, end: 11, author: "human" }], []);
|
||||
expect(html).toContain("cw-ins-human");
|
||||
});
|
||||
test("renderReview: a standalone deletion since baseline renders neutral struck del", () => {
|
||||
const html = renderReview("hello world", "hello", [], []);
|
||||
expect(html).toMatch(/cw-del-none|cw-removed/);
|
||||
});
|
||||
```
|
||||
|
||||
Run: `npm test -- trackChangesModel`
|
||||
Expected: PASS (whole file green).
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/trackChangesModel.ts test/trackChangesModel.test.ts
|
||||
git commit -m "feat: author-colored changed/added blocks in review; unchanged blocks render plain"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Color pending proposal blocks by author
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/trackChangesModel.ts` — `ProposalView` (731-742) + `proposalBlockHtml` (744-767)
|
||||
- Modify: `src/trackChangesPreview.ts` — populate `author` on each `ProposalView`
|
||||
- Test: `test/trackChangesModel.test.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `AuthorKind` (557).
|
||||
- Produces: `ProposalView.author?: AuthorKind` (defaults to `"claude"`); `proposalBlockHtml` emits `cw-del-{author}` / `cw-ins-{author}`.
|
||||
|
||||
- [ ] **Step 1: Write the failing test**
|
||||
|
||||
```ts
|
||||
test("renderReview: a proposal block colors its del/ins by author (claude default)", () => {
|
||||
const proposals: ProposalView[] = [{ id: "p1", anchorStart: 0, anchorEnd: 5, replaced: "hello", replacement: "goodbye" }];
|
||||
const html = renderReview("hello", "hello", [], proposals);
|
||||
expect(html).toContain('cw-del-claude');
|
||||
expect(html).toContain('cw-ins-claude');
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run test to verify it fails**
|
||||
|
||||
Run: `npm test -- trackChangesModel`
|
||||
Expected: FAIL — `proposalBlockHtml` still emits `cw-del` / `cw-add`.
|
||||
|
||||
- [ ] **Step 3: Write minimal implementation**
|
||||
|
||||
In `src/trackChangesModel.ts`, add `author?` to `ProposalView` (after line 741):
|
||||
|
||||
```ts
|
||||
/** F12/#64 (INV-48): the pre-apply original, set after optimistic apply. */
|
||||
original?: string;
|
||||
/** Who made the proposal — colors the del/ins. Defaults to "claude". */
|
||||
author?: AuthorKind;
|
||||
}
|
||||
```
|
||||
|
||||
Update `proposalBlockHtml` (753-754):
|
||||
|
||||
```ts
|
||||
const who = p.author ?? "claude";
|
||||
const before = p.replaced ? `<del class="cw-del-${who}">${safe(p.replaced)}</del>` : "";
|
||||
const after = `<ins class="cw-ins-${who}">${safe(p.replacement)}</ins>`;
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run test to verify it passes**
|
||||
|
||||
Run: `npm test -- trackChangesModel`
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Populate `author` from the live proposal**
|
||||
|
||||
In `src/trackChangesPreview.ts` find where `ProposalView`s are built for `renderReview` (the `listProposals` mapping near line 373). Add `author` from the proposal's provenance. Locate the mapping and add:
|
||||
|
||||
```ts
|
||||
author: p.author?.kind === "agent" ? "claude" : "human",
|
||||
```
|
||||
|
||||
(where `p` is the live `Proposal` with `author: Provenance`). If the preview builds `ProposalView` via a helper, add the field there. Run `npm run typecheck` to confirm the field name matches the live `Proposal.author` shape (`model.ts:79-108`).
|
||||
|
||||
- [ ] **Step 6: Run typecheck + tests**
|
||||
|
||||
Run: `npm run typecheck && npm test -- trackChangesModel`
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 7: Commit**
|
||||
|
||||
```bash
|
||||
git add src/trackChangesModel.ts src/trackChangesPreview.ts test/trackChangesModel.test.ts
|
||||
git commit -m "feat: color pending proposal blocks by author (Claude blue/purple)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: CSS — author×operation color system (preview)
|
||||
|
||||
**Files:**
|
||||
- Modify: `media/preview.css`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: classes emitted by Tasks 1-3: `cw-ins-human|claude|none`, `cw-del-human|claude|none`, `cw-by-human|claude` (added blocks), `cw-added`, `cw-removed`, `cw-changed`, `.cw-proposal`.
|
||||
- Produces: the locked color mapping; unchanged text plain.
|
||||
|
||||
- [ ] **Step 1: Replace the semantic diff + authorship-tint rules**
|
||||
|
||||
In `media/preview.css`, replace lines 21-33 and 55-58 with author-colored rules. New block:
|
||||
|
||||
```css
|
||||
/* Author-colored track changes — style = operation, color = author.
|
||||
underline = inserted, strikethrough = removed; human green/red, Claude blue/purple. */
|
||||
#cw-summary .cw-add { color: #3fb950; }
|
||||
#cw-summary .cw-del { color: #f85149; }
|
||||
.cw-blk { position: relative; }
|
||||
|
||||
/* base ins/del carry the operation; author classes carry the color */
|
||||
ins { text-decoration: none; }
|
||||
del { text-decoration: line-through; opacity: 0.7; }
|
||||
|
||||
.cw-ins-human { background: rgba(63,185,80,0.14); border-bottom: 2px solid #3fb950; text-decoration: none; }
|
||||
.cw-ins-claude { background: rgba(88,166,255,0.15); border-bottom: 2px solid #58a6ff; text-decoration: none; }
|
||||
.cw-ins-none { background: var(--vscode-diffEditor-insertedTextBackground, rgba(63,185,80,0.14)); text-decoration: none; }
|
||||
.cw-del-human { background: rgba(248,81,73,0.11); text-decoration: line-through; text-decoration-color: #f85149; }
|
||||
.cw-del-claude { background: rgba(188,140,255,0.13); text-decoration: line-through; text-decoration-color: #bc8cff; }
|
||||
.cw-del-none { background: var(--vscode-diffEditor-removedTextBackground, rgba(248,81,73,0.11)); text-decoration: line-through; opacity: 0.7; }
|
||||
|
||||
/* whole-block ops: an added block is an insertion (author-colored inside via cw-by-*);
|
||||
a standalone removed block is neutral struck (adjacency heuristic fallback) */
|
||||
.cw-added { background: transparent; }
|
||||
.cw-removed { background: var(--vscode-diffEditor-removedTextBackground, rgba(248,81,73,0.10)); text-decoration: line-through; opacity: 0.65; }
|
||||
.cw-changed { outline: none; }
|
||||
|
||||
/* added-block author runs (colorByAuthor sentinels) read as insertions */
|
||||
.cw-by-human { background: rgba(63,185,80,0.14); border-bottom: 2px solid #3fb950; text-decoration: none; }
|
||||
.cw-by-claude { background: rgba(88,166,255,0.15); border-bottom: 2px solid #58a6ff; text-decoration: none; }
|
||||
.cw-blk.cw-by-claude, .cw-blk.cw-by-human, .cw-blk.cw-mixed { outline: 2px solid currentColor; outline-offset: 2px; background: transparent; }
|
||||
#cw-legend .cw-swatch { padding: 0 0.4em; border-radius: 3px; }
|
||||
#cw-summary .cw-prop { opacity: 0.85; }
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Recolor the proposal block accent to neutral (author lives inside it now)**
|
||||
|
||||
The proposal block's left border is currently blue (`--vscode-charts-blue`). Keep it as a neutral "pending" frame — the del/ins inside now carry the author color. Change `media/preview.css:79-80`:
|
||||
|
||||
```css
|
||||
border-left: 3px solid var(--vscode-panel-border, #555);
|
||||
background: color-mix(in srgb, var(--vscode-foreground) 5%, transparent);
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Manual visual verification**
|
||||
|
||||
Run the extension host (or load the smoke doc) and confirm in the preview: human insertions green-underlined, Claude insertions blue-underlined, Claude deletions purple-struck, standalone deletions neutral, unchanged text plain.
|
||||
|
||||
Run: `npm run build`
|
||||
Expected: builds clean (CSS is bundled into the webview assets per the build).
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add media/preview.css
|
||||
git commit -m "feat: author-colored track-changes CSS for the preview (human green/red, Claude blue/purple)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Phase-1 host E2E — author colors render in the preview
|
||||
|
||||
**Files:**
|
||||
- Test: the existing F10/F7 preview E2E suite (find under `test/e2e/` — the preview/review specs)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: the rendered preview webview HTML.
|
||||
|
||||
- [ ] **Step 1: Write the failing E2E assertions**
|
||||
|
||||
In the preview E2E spec, after producing a Claude change + a human change on a doc, assert the webview body contains `cw-ins-claude` and `cw-ins-human`, and that an unchanged paragraph has no `cw-ins-`/`cw-by-` class. (Follow the existing pattern in that spec for opening the preview and reading `panel.webview` HTML or the DOM via the harness.)
|
||||
|
||||
- [ ] **Step 2: Run to verify it fails (or update an assertion that checked old classes)**
|
||||
|
||||
Run: `npm run test:e2e`
|
||||
Expected: FAIL if any existing assertion checked `cw-add`/`cw-by-*`-as-authorship; update those to the new classes.
|
||||
|
||||
- [ ] **Step 3: Make it pass**
|
||||
|
||||
Adjust any E2E assertion referencing retired classes (`cw-add`, semantic `ins`/`del` colors, `cw-by-*` on unchanged blocks) to the new author classes.
|
||||
|
||||
Run: `npm run test:e2e`
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add test/e2e
|
||||
git commit -m "test(e2e): assert author-colored track changes render in the preview"
|
||||
```
|
||||
|
||||
**>>> Phase 1 is independently shippable here. Open a PR for the preview pane before starting Phase 2, or continue.**
|
||||
|
||||
---
|
||||
|
||||
# Phase 2 — Editor pane (reverses INV-32)
|
||||
|
||||
Brings the same author-colored track changes inline into the main editor: all changes-since-baseline (committed + pending), not just pending proposals.
|
||||
|
||||
## File Structure (Phase 2)
|
||||
|
||||
- `src/editorProposalController.ts` — per-author decoration types; recolor proposals; subscribe to baseline + attribution; decorate all committed insertions (author-colored) + committed deletion hints (adjacency); overlap stacks naturally.
|
||||
- `src/extension.ts` — inject `DiffViewController` + `AttributionController` into `EditorProposalController`.
|
||||
- Test: editor E2E suite.
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Per-author decoration types; recolor proposals to Claude
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/editorProposalController.ts` (20-27 decoration types; 80-106 renderEditor)
|
||||
- Test: editor E2E
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `decorationPlan` (already imported), proposal list.
|
||||
- Produces: four insertion decoration types (`human`/`claude`) keyed by author, deletion-hint types colored by author; proposals decorate with Claude colors.
|
||||
|
||||
- [ ] **Step 1: Replace the two decoration types with per-author maps**
|
||||
|
||||
In `src/editorProposalController.ts`, replace lines 20-27:
|
||||
|
||||
```ts
|
||||
private readonly insDeco: Record<"human" | "claude", vscode.TextEditorDecorationType> = {
|
||||
human: vscode.window.createTextEditorDecorationType({
|
||||
backgroundColor: "rgba(63,185,80,0.14)", borderColor: "#3fb950",
|
||||
border: "0 0 2px 0", borderStyle: "solid",
|
||||
}),
|
||||
claude: vscode.window.createTextEditorDecorationType({
|
||||
backgroundColor: "rgba(88,166,255,0.15)", borderColor: "#58a6ff",
|
||||
border: "0 0 2px 0", borderStyle: "solid",
|
||||
}),
|
||||
};
|
||||
private readonly delDeco: Record<"human" | "claude", vscode.TextEditorDecorationType> = {
|
||||
human: vscode.window.createTextEditorDecorationType({ after: { color: "#f85149" } }),
|
||||
claude: vscode.window.createTextEditorDecorationType({ after: { color: "#bc8cff" } }),
|
||||
};
|
||||
```
|
||||
|
||||
Update the constructor's disposables push (39-40) to dispose all four:
|
||||
|
||||
```ts
|
||||
this.insDeco.human, this.insDeco.claude, this.delDeco.human, this.delDeco.claude, this.lensEmitter,
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Recolor proposal decorations to Claude in `renderEditor`**
|
||||
|
||||
Replace the body of `renderEditor` (81-106) so it groups ranges per author and applies the right decoration type. Proposals are Claude:
|
||||
|
||||
```ts
|
||||
private renderEditor(editor: vscode.TextEditor): void {
|
||||
const doc = editor.document;
|
||||
const clearAll = () => {
|
||||
for (const a of ["human", "claude"] as const) {
|
||||
editor.setDecorations(this.insDeco[a], []);
|
||||
editor.setDecorations(this.delDeco[a], []);
|
||||
}
|
||||
};
|
||||
if (doc.languageId !== "markdown") return clearAll();
|
||||
const key = this.proposals.keyFor(doc);
|
||||
const ins: Record<"human" | "claude", vscode.Range[]> = { human: [], claude: [] };
|
||||
const del: Record<"human" | "claude", vscode.DecorationOptions[]> = { human: [], claude: [] };
|
||||
// Pending proposals — always Claude (INV: proposals are agent-authored).
|
||||
for (const v of this.proposals.listProposals(doc)) {
|
||||
if (v.anchorStart === null || v.original === undefined || !this.proposals.isApplied(key, v.id)) continue;
|
||||
const plan = decorationPlan(v.anchorStart, v.original, v.replacement);
|
||||
for (const i of plan.insertions) ins.claude.push(new vscode.Range(doc.positionAt(i.start), doc.positionAt(i.end)));
|
||||
for (const d of plan.deletions) {
|
||||
del.claude.push({
|
||||
range: new vscode.Range(doc.positionAt(d.at), doc.positionAt(d.at)),
|
||||
renderOptions: { after: { contentText: ` ${d.text} `, textDecoration: "line-through" } },
|
||||
});
|
||||
}
|
||||
}
|
||||
// Committed changes-since-baseline are added in Task 7 (pushes into ins/del[author]).
|
||||
this.decorateCommitted(editor, ins, del); // no-op stub until Task 7
|
||||
for (const a of ["human", "claude"] as const) {
|
||||
editor.setDecorations(this.insDeco[a], ins[a]);
|
||||
editor.setDecorations(this.delDeco[a], del[a]);
|
||||
}
|
||||
}
|
||||
|
||||
/** Overridden in Task 7 to add committed (non-proposal) author-colored changes. */
|
||||
private decorateCommitted(
|
||||
_editor: vscode.TextEditor,
|
||||
_ins: Record<"human" | "claude", vscode.Range[]>,
|
||||
_del: Record<"human" | "claude", vscode.DecorationOptions[]>,
|
||||
): void {}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Typecheck + build**
|
||||
|
||||
Run: `npm run typecheck && npm run build`
|
||||
Expected: clean.
|
||||
|
||||
- [ ] **Step 4: E2E — proposal shows Claude colors**
|
||||
|
||||
Update/extend the editor E2E to assert a pending proposal decorates (smoke: the decoration types exist and apply; the harness asserts via the proposal-applied path used today). Run: `npm run test:e2e` → PASS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/editorProposalController.ts test/e2e
|
||||
git commit -m "feat: per-author editor decoration types; proposals decorate in Claude blue/purple"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Decorate committed changes-since-baseline by author (reverse INV-32)
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/editorProposalController.ts` — inject baseline + attribution; implement `decorateCommitted`; subscribe to baseline/attribution change events
|
||||
- Modify: `src/extension.ts` (line 122) — pass the two new deps
|
||||
- Test: editor E2E
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `DiffViewController.getBaseline(uri)` (diffViewController.ts:133) + `onDidChangeBaseline` (32); `AttributionController.spansFor(document)` (attributionController.ts:405); pure `wordEditHunks` + `authorAt` (trackChangesModel.ts).
|
||||
- Produces: committed insertions colored by `authorAt(currentOffset)`; committed deletion hints colored by adjacency (the paired insertion's author).
|
||||
|
||||
- [ ] **Step 1: Inject the new dependencies**
|
||||
|
||||
Change the constructor signature (38):
|
||||
|
||||
```ts
|
||||
constructor(
|
||||
private readonly proposals: ProposalController,
|
||||
private readonly diffView: import("./diffViewController").DiffViewController,
|
||||
private readonly attribution: import("./attributionController").AttributionController,
|
||||
) {
|
||||
```
|
||||
|
||||
Add subscriptions in the constructor disposables list:
|
||||
|
||||
```ts
|
||||
this.diffView.onDidChangeBaseline(({ uri }) => {
|
||||
const ed = vscode.window.visibleTextEditors.find((e) => e.document.uri.toString() === uri);
|
||||
if (ed) this.renderEditor(ed);
|
||||
}),
|
||||
```
|
||||
|
||||
In `src/extension.ts` (122) pass the deps (both already constructed above — `diffViewController` and `attributionController`):
|
||||
|
||||
```ts
|
||||
const editorProposalController = new EditorProposalController(
|
||||
proposalController,
|
||||
diffViewController,
|
||||
attributionController,
|
||||
);
|
||||
```
|
||||
|
||||
(Confirm the local variable names in `extension.ts` for the diff-view + attribution controllers via `npm run typecheck`.)
|
||||
|
||||
- [ ] **Step 2: Implement `decorateCommitted`**
|
||||
|
||||
Replace the stub with the real implementation. It diffs baseline → current, attributes insertions, and colors deletion hints by adjacency:
|
||||
|
||||
```ts
|
||||
private decorateCommitted(
|
||||
editor: vscode.TextEditor,
|
||||
ins: Record<"human" | "claude", vscode.Range[]>,
|
||||
del: Record<"human" | "claude", vscode.DecorationOptions[]>,
|
||||
): void {
|
||||
const doc = editor.document;
|
||||
const baseline = this.diffView.getBaseline(doc.uri.toString());
|
||||
if (!baseline || baseline.reason === "pinned") return; // pin→clean: no committed marks
|
||||
const current = doc.getText();
|
||||
const spans = this.attribution.spansFor(doc); // AuthorSpan[] in current coords
|
||||
const hunks = wordEditHunks(baseline.text, current); // start/end index INTO current
|
||||
for (const h of hunks) {
|
||||
// The replacement text occupies [h.start, h.start+replacement.length) in current.
|
||||
// Re-derive the intra-hunk word diff to split ins vs del and find the author.
|
||||
const original = baseline.text.slice(/* mapped */ 0, 0); // see note
|
||||
const plan = decorationPlan(h.start, hunkOriginal(baseline.text, current, h), current.slice(h.start, h.end));
|
||||
const author = authorAt(h.start, spans) ?? "human";
|
||||
for (const i of plan.insertions) ins[author].push(new vscode.Range(doc.positionAt(i.start), doc.positionAt(i.end)));
|
||||
for (const d of plan.deletions) {
|
||||
del[author].push({
|
||||
range: new vscode.Range(doc.positionAt(d.at), doc.positionAt(d.at)),
|
||||
renderOptions: { after: { contentText: ` ${d.text} `, textDecoration: "line-through" } },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> **Implementation note for the engineer:** `wordEditHunks(baseline, current)` returns hunks whose `start`/`end` index into **current** with a `replacement` that is the *baseline* text for that span (see trackChangesModel.ts:241-264 — `replacement` accumulates `removed` parts = baseline text, `end` advances over them). So for a committed change, the *original* (baseline) text of a hunk is `h.replacement` and the *applied* (current) text is `current.slice(h.start, h.end)`. Call `decorationPlan(h.start, h.replacement, current.slice(h.start, h.end))` directly — drop the `hunkOriginal`/`original` placeholder lines above. Verify this against a unit test before wiring (Step 3).
|
||||
|
||||
- [ ] **Step 3: Unit-test the hunk→plan derivation (pure)**
|
||||
|
||||
Because the offset semantics are subtle, add a pure unit test in `test/trackChangesModel.test.ts` proving `wordEditHunks` + `decorationPlan` reconstruct a committed change. Add an exported helper if needed:
|
||||
|
||||
```ts
|
||||
test("committed change: wordEditHunks replacement is baseline text; current slice is applied", () => {
|
||||
const baseline = "the light mode";
|
||||
const current = "the dark mode";
|
||||
const [h] = wordEditHunks(baseline, current);
|
||||
expect(h.replacement).toContain("light"); // baseline side
|
||||
expect(current.slice(h.start, h.end)).toContain("dark"); // applied side
|
||||
const plan = decorationPlan(h.start, h.replacement, current.slice(h.start, h.end));
|
||||
expect(plan.insertions.length).toBeGreaterThan(0);
|
||||
expect(plan.deletions.some((d) => d.text.includes("light"))).toBe(true);
|
||||
});
|
||||
```
|
||||
|
||||
Run: `npm test -- trackChangesModel` → PASS. Then finalize `decorateCommitted` to use `h.replacement` + `current.slice(h.start, h.end)` (removing the placeholder lines).
|
||||
|
||||
- [ ] **Step 4: Add the attribution-change refresh**
|
||||
|
||||
Editor decorations must refresh when attribution changes (e.g. after a human edit). If `AttributionController` exposes a change event, subscribe to it and call `renderEditor`; otherwise refresh on `vscode.workspace.onDidChangeTextDocument` for the active editor (debounced like `scheduleApply`). Add to the constructor disposables:
|
||||
|
||||
```ts
|
||||
vscode.workspace.onDidChangeTextDocument((e) => {
|
||||
const ed = vscode.window.activeTextEditor;
|
||||
if (ed && e.document === ed.document) this.scheduleRender(ed);
|
||||
}),
|
||||
```
|
||||
|
||||
with a small `scheduleRender(ed)` that debounces `renderEditor(ed)` (mirror `scheduleApply`, 50ms).
|
||||
|
||||
- [ ] **Step 5: Typecheck + build + E2E**
|
||||
|
||||
Run: `npm run typecheck && npm run build && npm run test:e2e`
|
||||
Expected: clean. E2E: a committed human edit shows green underline; an accepted Claude replace shows blue underline + purple struck hint; a pinned baseline shows nothing.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/editorProposalController.ts src/extension.ts test/trackChangesModel.test.ts test/e2e
|
||||
git commit -m "feat: author-colored committed track changes inline in the editor (reverse INV-32)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 8: Overlap — stacked marks where both authors touch one span
|
||||
|
||||
**Files:**
|
||||
- Test: `test/trackChangesModel.test.ts` (preview overlap) + editor E2E (editor overlap)
|
||||
- Modify (if needed): `media/preview.css` (ensure `<ins>` nested in `<del>` and vice-versa render both marks)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: existing emitted classes.
|
||||
- Produces: a span both inserted (author A) and being deleted (author B) shows both A's underline and B's strikethrough.
|
||||
|
||||
- [ ] **Step 1: Editor overlap — verify decorations stack**
|
||||
|
||||
In the editor, an overlap arises when a committed insertion range (author A) is also covered by a pending proposal deletion (Claude). VS Code applies multiple decoration types to overlapping ranges, so the author-A insertion underline and the Claude deletion hint already coexist. Add an editor E2E asserting both decoration types are present on the overlap region. No code change expected; if the proposal's optimistic apply *replaces* the text (so A's range no longer exists), document that committed-insert + pending-delete overlap manifests as the proposal's struck original (Claude purple) adjacent to A's surviving insertion — assert that instead.
|
||||
|
||||
- [ ] **Step 2: Preview overlap — CSS nesting**
|
||||
|
||||
Add a CSS test fixture / assertion: a `<del class="cw-del-claude"><span class="cw-ins-human">…</span></del>` renders with both strikethrough (Claude purple) and underline (human green). Add to `media/preview.css` if the nested case collapses:
|
||||
|
||||
```css
|
||||
.cw-del-claude .cw-ins-human, .cw-del-human .cw-ins-claude,
|
||||
.cw-del-claude .cw-by-human, .cw-del-human .cw-by-claude { text-decoration: inherit; }
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run tests**
|
||||
|
||||
Run: `npm test && npm run test:e2e`
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add media/preview.css test/trackChangesModel.test.ts test/e2e
|
||||
git commit -m "feat: overlap renders stacked author marks (insert + delete) in both panes"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 9: Sweep retired markup + full suite + manual smoke
|
||||
|
||||
**Files:**
|
||||
- `test/**`, `media/preview.css`, any code referencing retired classes.
|
||||
|
||||
- [ ] **Step 1: Grep for retired classes/behaviors**
|
||||
|
||||
Run:
|
||||
```bash
|
||||
grep -rn "cw-add\b\|cw-del\b\|diffEditor.insertedTextBackground\|gitDecoration.deletedResourceForeground" src/ media/ test/
|
||||
```
|
||||
Reconcile every hit: `cw-add`/`cw-del` (without `-author`) only legitimately remain in `#cw-summary`. The editor's old semantic ThemeColors are gone (replaced in Task 6).
|
||||
|
||||
- [ ] **Step 2: Full unit + typecheck + build**
|
||||
|
||||
Run: `npm run typecheck && npm test && npm run build`
|
||||
Expected: all green.
|
||||
|
||||
- [ ] **Step 3: Full E2E**
|
||||
|
||||
Run: `npm run test:e2e`
|
||||
Expected: all green (update any remaining old-class assertions).
|
||||
|
||||
- [ ] **Step 4: Manual smoke (both panes)**
|
||||
|
||||
Open the sandbox doc, make a human edit + ask Claude to edit. Confirm: editor shows green/blue underlines + purple/red struck hints; preview shows the same; unchanged text plain in both; pin baseline → both panes clean; accept a proposal → it recolors as a committed change until re-pin.
|
||||
|
||||
- [ ] **Step 5: Commit + open PR**
|
||||
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "chore: sweep retired semantic-diff markup; full suite green"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
**1. Spec coverage:**
|
||||
- Model (style=op, color=author) → Tasks 1-4 (preview), 6-7 (editor). ✓
|
||||
- Human green/red + Claude blue/purple, exact hexes → Global Constraints + Task 4 CSS + Task 6 decorations. ✓
|
||||
- Both panes → Phase 1 (preview) + Phase 2 (editor). ✓
|
||||
- Reverses INV-32 → Task 7. ✓
|
||||
- Both overlap directions, stacked → Task 8. ✓
|
||||
- Color = changed-since-baseline; pin→clean preserved → Task 2 (unchanged plain), Task 7 (`reason === "pinned"` guard). ✓
|
||||
- Deletion authorship = adjacency heuristic; standalone neutral → Task 1 (`wordDiffByAuthor` cluster author + `cw-del-none`), Task 7 (`authorAt(h.start)`). ✓
|
||||
- Components: trackChangesModel, editorProposalController, attributionController (read via spansFor), preview.css, extension.ts wiring → covered. ✓
|
||||
- Testing: unit (pure render), editor decorations (E2E), host E2E, retire old assertions → Tasks 1-3, 5, 7-9. ✓
|
||||
|
||||
**2. Placeholder scan:** Task 7 Step 2 intentionally shows a *wrong* placeholder (`hunkOriginal`/`original`) and immediately corrects it in the implementation note + Step 3 unit test that pins the exact offsets — this is a guided derivation, not an unresolved placeholder. No other TBD/TODO.
|
||||
|
||||
**3. Type consistency:** `AuthorKind` (`"claude" | "human"`) used throughout; decoration maps keyed `"human" | "claude"`; `authorAt` returns `AuthorKind | null` → `?? "human"`/`?? "none"` at every call site; `ProposalView.author?: AuthorKind`; `wordDiffByAuthor(beforeRaw, afterRaw, afterStart, spans)` signature matches both its test and its `renderReview` call site.
|
||||
|
||||
## Execution Handoff
|
||||
|
||||
(Filled in after you review.)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,150 +0,0 @@
|
||||
# Author-colored track changes (both panes) — design
|
||||
|
||||
**Date:** 2026-06-26
|
||||
**Status:** Design approved; ready for implementation planning
|
||||
**Mockups:** `.superpowers/brainstorm/15095-1782504559/content/panes-states-v2.html`
|
||||
|
||||
## Problem
|
||||
|
||||
Today the plugin uses two unrelated color systems:
|
||||
|
||||
- **The diff** (proposed/changed text in both panes) uses *semantic* colors —
|
||||
green = added, red = removed — regardless of who made the change.
|
||||
- **Authorship** (F3) uses *author* colors (blue = Claude, green = human) but
|
||||
only as a flat tint in the **preview** pane, and only on committed text, not
|
||||
as a diff.
|
||||
|
||||
So you cannot look at a change and immediately see **who** made it. The product
|
||||
goal is an experience like two humans collaborating in a track-changes document
|
||||
(Google Docs suggesting mode / Word track changes): every edit is a diff, and a
|
||||
glance tells you both *what changed* and *who changed it*.
|
||||
|
||||
## The model
|
||||
|
||||
Every change is rendered as a diff — insertions **and** deletions — where:
|
||||
|
||||
- **Style encodes the operation:** underline = inserted, strikethrough = removed.
|
||||
- **Color encodes the author.**
|
||||
|
||||
| | Added | Removed |
|
||||
| ------ | ---------------- | ---------------------- |
|
||||
| Human | green underline | red strikethrough |
|
||||
| Claude | blue underline | purple strikethrough |
|
||||
|
||||
Human keeps today's exact green/red. Claude gets blue/purple (blue is already
|
||||
Claude's established attribution hue; purple reads as a removal without colliding
|
||||
with human red).
|
||||
|
||||
**Color means "changed since the pinned baseline,"** not "authored forever." Once
|
||||
a change is accepted and the baseline re-pins, its marks clear and the text
|
||||
returns to plain. This preserves the existing pin→clean behavior (#48): a pinned,
|
||||
zero-diff document renders with no annotation.
|
||||
|
||||
### Concrete colors
|
||||
|
||||
Carry the existing human values; add Claude's pair. (Final hex values are a
|
||||
polish detail for implementation; these are the design intent.)
|
||||
|
||||
- Human added: `#3fb950` underline, bg `rgba(63,185,80,0.14)`
|
||||
- Human removed: `#f85149` strikethrough, bg `rgba(248,81,73,0.11)`
|
||||
- Claude added: `#58a6ff` underline, bg `rgba(88,166,255,0.15)`
|
||||
- Claude removed: `#bc8cff` strikethrough, bg `rgba(188,140,255,0.13)`
|
||||
|
||||
Each change run is a subtle author-hued background tint **plus** a solid 2px
|
||||
underline (insert) or strikethrough (delete) in the full author color — the solid
|
||||
line carries the signal even where backgrounds are faint.
|
||||
|
||||
## Both panes (decision A)
|
||||
|
||||
Author-colored track changes appear in **both** the main editor pane and the
|
||||
rendered preview pane.
|
||||
|
||||
- **Main editor pane:** gains full inline track-changes for *all*
|
||||
changes-since-baseline — human and Claude, committed and pending — not just
|
||||
pending proposals. **This reverses INV-32** ("editor fully clean") from F10:
|
||||
the editor was deliberately kept clean, with all who-wrote-what coloring living
|
||||
only in the preview. We are intentionally undoing that.
|
||||
- **Rendered preview pane:** shows the same model (it already renders a diff +
|
||||
authorship; this unifies them so ins/del runs are author-colored rather than
|
||||
semantically colored).
|
||||
|
||||
Pending Claude proposals keep their Accept/Reject affordance in both panes —
|
||||
CodeLens (`✓ Accept ▾ / ✗ Reject ▾`) in the editor, buttons in the preview.
|
||||
|
||||
## States (must all render correctly)
|
||||
|
||||
Base states: human-added, human-removed, Claude-added, Claude-removed.
|
||||
|
||||
**Overlap** — a single span both authors touched — stacks both marks:
|
||||
|
||||
- Human added it, Claude is removing it → green underline **+** purple strikethrough.
|
||||
- Claude added it, human is removing it → blue underline **+** red strikethrough.
|
||||
|
||||
Block-level: a whole added block carries the author's add treatment (left border +
|
||||
tint); a whole removed block carries the author's remove treatment (struck + tint).
|
||||
|
||||
Resting state: unchanged-since-baseline text renders plain. After Accept + re-pin,
|
||||
changed text returns to plain.
|
||||
|
||||
## Architecture
|
||||
|
||||
The core change is **fusing the currently-separate semantic-diff and authorship
|
||||
systems** so that every inserted/deleted run carries its author, and rendering
|
||||
colors by that author rather than by add/remove semantics.
|
||||
|
||||
Components affected (per the current code map):
|
||||
|
||||
- **`src/trackChangesModel.ts`** — `renderReview` / `renderOp` /
|
||||
`wordMergedMarkdown` / `colorByAuthor`. Today `<ins>`/`<del>` are emitted with
|
||||
semantic green/red classes independent of author. Change: ins/del runs become
|
||||
author-aware and emit author-colored classes; overlap emits a stacked-mark
|
||||
class.
|
||||
- **`src/editorProposalController.ts`** — today only pending proposals decorate,
|
||||
using semantic `ThemeColor`s. Change: per-author/op `TextEditorDecorationType`s
|
||||
(human-add/human-del/claude-add/claude-del + overlap), and decorate **all**
|
||||
changes-since-baseline, not just proposals (the INV-32 reversal).
|
||||
- **`src/attributionController.ts`** — supplies the per-character/per-run author
|
||||
spans the diff needs to attribute insertions (and, see below, deletions).
|
||||
- **`media/preview.css`** — recolor: keep human green/red, add Claude
|
||||
blue/purple, encode underline=insert / strikethrough=delete, add overlap
|
||||
(stacked-mark) classes for both directions.
|
||||
|
||||
## Open technical question (for the plan / tech-design stage)
|
||||
|
||||
**Deletion authorship.** Removed text is no longer in the buffer, so the renderer
|
||||
must know *who deleted it* to color the strikethrough.
|
||||
|
||||
- For **pending proposals**, the deleter is trivially Claude (the proposal owns
|
||||
the deletion).
|
||||
- For **committed deletions** (baseline → current), we must confirm the F3 seam /
|
||||
attribution model carries the **deleting actor**. F3 attributes
|
||||
*current-buffer* characters; deleted characters are gone. If the seam's edit
|
||||
events carry the actor that performed each removal, we attribute from that; if
|
||||
not, deriving deletion authorship is the main thing the implementation plan has
|
||||
to solve. Until resolved, a safe fallback is to color committed deletions by the
|
||||
**turn actor** that produced the diff hunk.
|
||||
|
||||
This is the one genuinely open architectural item; everything else is
|
||||
presentation.
|
||||
|
||||
## Out of scope (YAGNI)
|
||||
|
||||
- More than two authors / arbitrary per-collaborator palettes. Two roles
|
||||
(human, Claude) only.
|
||||
- User-configurable colors / theme settings. Ship one good scheme.
|
||||
- Changing accept/reject *mechanics* — this is purely how changes are
|
||||
**visualized**; the F4 proposal lifecycle is unchanged.
|
||||
- Per-word authorship inside an accepted, re-pinned (plain) document.
|
||||
|
||||
## Testing
|
||||
|
||||
- **Unit (pure render):** `trackChangesModel` renders each state to the expected
|
||||
author-colored markup — the four base states, both overlap directions, block
|
||||
add/remove, and resting/plain. Reuse the existing pure-render test pattern.
|
||||
- **Editor decorations:** the decoration plan produces the right per-author/op
|
||||
ranges, including the INV-32-reversal (committed changes now decorate) and
|
||||
stacked overlap ranges.
|
||||
- **Host E2E:** open a co-edited doc, assert both panes show author-colored
|
||||
marks; accept a proposal + re-pin → marks clear (pin→clean preserved).
|
||||
- Update/replace any test that asserts the **old** semantic green=add/red=remove
|
||||
classes or the INV-32 clean-editor behavior.
|
||||
+20
-35
@@ -18,40 +18,19 @@ body {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
}
|
||||
/* Author-colored track changes — style = operation, color = author.
|
||||
underline = inserted, strikethrough = removed; human green/red, Claude blue/purple. */
|
||||
#cw-summary .cw-add { color: #3fb950; }
|
||||
#cw-summary .cw-del { color: #f85149; }
|
||||
#cw-summary .cw-add { color: var(--vscode-gitDecoration-addedResourceForeground); }
|
||||
#cw-summary .cw-del { color: var(--vscode-gitDecoration-deletedResourceForeground); }
|
||||
.cw-blk { position: relative; }
|
||||
|
||||
/* base ins/del carry the operation; author classes carry the color */
|
||||
ins { text-decoration: none; }
|
||||
del { text-decoration: line-through; opacity: 0.7; }
|
||||
|
||||
.cw-ins-human { background: rgba(63,185,80,0.14); border-bottom: 2px solid #3fb950; text-decoration: none; }
|
||||
.cw-ins-claude { background: rgba(88,166,255,0.15); border-bottom: 2px solid #58a6ff; text-decoration: none; }
|
||||
.cw-ins-none { background: var(--vscode-diffEditor-insertedTextBackground, rgba(63,185,80,0.14)); text-decoration: none; }
|
||||
.cw-del-human { background: rgba(248,81,73,0.11); text-decoration: line-through; text-decoration-color: #f85149; }
|
||||
.cw-del-claude { background: rgba(188,140,255,0.13); text-decoration: line-through; text-decoration-color: #bc8cff; }
|
||||
.cw-del-none { background: var(--vscode-diffEditor-removedTextBackground, rgba(248,81,73,0.11)); text-decoration: line-through; opacity: 0.7; }
|
||||
|
||||
/* Task 8 — overlap: if a future render path nests cw-ins-{A} inside cw-del-{B},
|
||||
both marks must show. cw-ins-* sets text-decoration:none which would otherwise
|
||||
suppress the parent del's strikethrough. `inherit` restores the parent's
|
||||
line-through while the child's border-bottom underline is unaffected.
|
||||
The engine currently emits SIBLING ins/del (never nested) so this rule is a
|
||||
forward defensive guarantee only. See task-8-report.md for details. */
|
||||
.cw-del-claude .cw-ins-human, .cw-del-human .cw-ins-claude { text-decoration: inherit; }
|
||||
|
||||
/* whole-block ops: an added block is an insertion (its author runs are emitted as
|
||||
cw-ins-* via colorByAuthor with kind="ins"); a standalone removed block is neutral
|
||||
struck (adjacency heuristic fallback) */
|
||||
.cw-added { background: transparent; }
|
||||
.cw-removed { background: var(--vscode-diffEditor-removedTextBackground, rgba(248,81,73,0.10)); text-decoration: line-through; opacity: 0.65; }
|
||||
.cw-changed { outline: none; }
|
||||
|
||||
#cw-legend .cw-swatch { padding: 0 0.4em; border-radius: 3px; }
|
||||
#cw-summary .cw-prop { opacity: 0.85; }
|
||||
ins, .cw-added {
|
||||
background: var(--vscode-diffEditor-insertedTextBackground, rgba(0, 255, 0, 0.15));
|
||||
text-decoration: none;
|
||||
}
|
||||
del, .cw-removed {
|
||||
background: var(--vscode-diffEditor-removedTextBackground, rgba(255, 0, 0, 0.15));
|
||||
text-decoration: line-through;
|
||||
opacity: 0.7;
|
||||
}
|
||||
.cw-changed { outline: 2px solid var(--vscode-diffEditor-insertedTextBackground, rgba(0, 255, 0, 0.25)); outline-offset: 2px; }
|
||||
.cw-badge {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
@@ -73,6 +52,12 @@ del { text-decoration: line-through; opacity: 0.7; }
|
||||
pre.mermaid { text-align: center; background: transparent; }
|
||||
pre.mermaid[data-cw-error] { color: var(--vscode-errorForeground); }
|
||||
|
||||
/* F9 authorship mode — inline author tints + block-level fence badges + toggle. */
|
||||
.cw-by-claude { background: var(--vscode-editorInfo-foreground, rgba(64, 120, 242, 0.18)); text-decoration: none; }
|
||||
.cw-by-human { background: var(--vscode-gitDecoration-addedResourceForeground, rgba(46, 160, 67, 0.18)); text-decoration: none; }
|
||||
.cw-blk.cw-by-claude, .cw-blk.cw-by-human, .cw-blk.cw-mixed { outline: 2px solid currentColor; outline-offset: 2px; background: transparent; }
|
||||
#cw-legend .cw-swatch { padding: 0 0.4em; border-radius: 3px; }
|
||||
#cw-summary .cw-prop { opacity: 0.85; }
|
||||
|
||||
/* F11 — preview toolbar buttons (Pin baseline; adaptive Ask Claude). Theme-aware. */
|
||||
#cw-header button {
|
||||
@@ -91,8 +76,8 @@ pre.mermaid[data-cw-error] { color: var(--vscode-errorForeground); }
|
||||
#cw-toggle { display: inline-flex; align-items: center; gap: 0.35em; cursor: pointer; }
|
||||
.cw-proposal {
|
||||
position: relative;
|
||||
border-left: 3px solid var(--vscode-panel-border, #555);
|
||||
background: color-mix(in srgb, var(--vscode-foreground) 5%, transparent);
|
||||
border-left: 3px solid var(--vscode-charts-blue, #4daafc);
|
||||
background: color-mix(in srgb, var(--vscode-charts-blue, #4daafc) 12%, transparent);
|
||||
padding: 0.4em 0.6em; margin: 0.4em 0; border-radius: 3px;
|
||||
}
|
||||
.cw-proposal-unanchored { border-left-style: dashed; opacity: 0.85; }
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
# Session 0059.0 — Transcript
|
||||
|
||||
> App: vscode-cowriting-plugin
|
||||
> Start: 2026-06-26T06-01 (PST)
|
||||
> End: 2026-06-26T08-32 (PST)
|
||||
> Type: planning-and-executing
|
||||
> Posture: autonomous (yolo)
|
||||
> Status: **FINALIZED**
|
||||
|
||||
## Launch prompt
|
||||
|
||||
Plan-and-execute #64 (F12 inline editable proposed-change diff in the Markdown
|
||||
editor) from the graduated spec `specs/coauthoring-inline-editor-diff.md`, in
|
||||
isolated worktree `vscode-cowriting-plugin-s58` (branch `s58-inline-editor-diff`),
|
||||
opened straight off brainstorming session 0058.
|
||||
|
||||
## Plan
|
||||
|
||||
Implement #64 per spec: optimistic-apply the proposed change into the editor
|
||||
buffer (editable, tinted insertions + struck-red deletion hints), accept =
|
||||
finalize-in-place / reject = revert-in-place, `Accept ▾`/`Reject ▾` (+ Accept-all
|
||||
/Reject-all) from both editor (CodeLens+QuickPick) and webview. Reverses
|
||||
INV-10/INV-32; INV-48..54. Implementation plan:
|
||||
`docs/superpowers/plans/2026-06-26-inline-editor-diff.md`.
|
||||
|
||||
## Outcome — SHIPPED
|
||||
|
||||
#64 (F12) **shipped to main** — PR #66 squash `7b98249`, issue auto-closed.
|
||||
Worktree built, subagent-driven (fresh implementer per task + two-stage review),
|
||||
adversarial final review, then merged through the concurrent #65 landing.
|
||||
|
||||
## Turn-by-turn arc
|
||||
|
||||
1. **Init** — claimed session 0059 (0057 still in-flight; isolated worktree made
|
||||
it §5.4-safe). Synced worktree, `npm ci`, green baseline (242 unit).
|
||||
2. **Plan** — read the whole subsystem (proposalController, trackChangesModel,
|
||||
attributionController, trackChangesPreview, preview.ts/css, extension.ts,
|
||||
package.json, E2E harness); wrote an 8-task TDD plan. Surfaced a **spec
|
||||
refinement**: optimistic apply must re-anchor the proposal to the applied text
|
||||
+ store `Proposal.original` (F4's `fp.text` is the original, gone once applied).
|
||||
3. **Execute (subagent-driven, sonnet implementers):**
|
||||
- T1 `Proposal.original` (model) — `bea9fd5`.
|
||||
- T2 `setProposalApplied` re-anchor helper — `92ff4dd`.
|
||||
- T3 seam `landBaseline` opt + `signalLanded` — `6d54963`. **Surfaced the
|
||||
host-E2E was blocked by a macOS UNIX-socket-length `EINVAL`** (the long
|
||||
worktree path). Fixed by pinning `--user-data-dir` to a short `/tmp` path
|
||||
(`930b4ab`) → host-E2E now launches from a worktree.
|
||||
- T4 `optimisticApply`/`finalizeInPlace`/`revertInPlace`/`rejectAll` —
|
||||
`ddbbb7a` (subagent caught a real `keyOf` vs `uri.toString()` test bug).
|
||||
- T5 `EditorProposalController` + pure `decorationPlan` — `8c6e782`+`e599284`
|
||||
(subagent added a setTimeout(0) apply-debounce for the batch race; updated 5
|
||||
existing E2E for the INV-10 reversal — verified legitimate, not weakened).
|
||||
- T6 render-once INV-50 reconciliation — `6529332`; I added a coloring-
|
||||
alignment fix (`landedSpans` via `toLanded`) the subagent's note flagged —
|
||||
`3805323`.
|
||||
- T7 webview `Accept ▾`/`Reject ▾` + dropdown + `rejectAllProposals` — `f4594da`.
|
||||
4. **Adversarial final review (opus subagent)** — found a **CRITICAL** (revert
|
||||
target clobbered on save+reload, in-memory `applied` empty post-reload) and a
|
||||
MINOR (toolbar summary double-counts). Both fixed + a reload-safety regression
|
||||
E2E — `6560894`. Verdict invariants INV-48..54 upheld; decorationPlan alignment
|
||||
verified correct.
|
||||
5. **Concurrency** — session 0057 had merged **#65** (unify Ask-Claude on a
|
||||
split-below webview; removed `InlineAskController`) to main mid-session. Merged
|
||||
origin/main into the branch, resolved the one `extension.ts` conflict (drop
|
||||
inlineAsk, keep `EditorProposalController`); suite green; squash-merged PR #66.
|
||||
6. **Hygiene** — a `git add -A` during the merge accidentally tracked the spec
|
||||
copy in the code repo; removed it (PR #67 `844a278`) — specs are canonical in
|
||||
the content repo. Plan archived (`8c14f54`); spec patched to **v0.1.1** with the
|
||||
re-anchor refinement and submitted (`43913dc`).
|
||||
|
||||
## Cut state
|
||||
|
||||
- **main @ `844a278`** (clean, pushed). #64 closed.
|
||||
- Tests: **249 unit + 87/5 host-E2E green**, typecheck clean.
|
||||
- Content repo: spec v0.1.1 (`43913dc`) + plan (`8c14f54`).
|
||||
- Worktree removed.
|
||||
|
||||
## Deferred decisions
|
||||
|
||||
- **Re-anchor on optimistic apply (spec refinement, RESOLVED into v0.1.1).** Added
|
||||
`Proposal.original` + re-fingerprint to the applied text; captured once →
|
||||
reload-safe. Folded into the spec.
|
||||
- **`finalizeInPlace` has no orphan re-resolve guard** (CodeLens Accept), unlike
|
||||
the webview `acceptById`. Intentional — spec §2.2 says Accept keeps the human's
|
||||
in-place edits (which would orphan the exact-text fp) — but it's asymmetric. Left
|
||||
as-is; noted as a follow-up nit.
|
||||
- **Per-proposal webview carets always show Accept-all/Reject-all** even at 1
|
||||
pending (the toolbar button correctly hides <2). Cosmetic; not fixed.
|
||||
|
||||
## Not done
|
||||
|
||||
- **Manual smoke (interactive F5)** — the live editor diff, CodeLens dropdown,
|
||||
both-surface parity, and save-while-pending need an Extension Development Host
|
||||
run (operator-side). No flotilla/PPE for this app — the PR-merge to main is the
|
||||
ship.
|
||||
|
||||
## Next-session prompt
|
||||
|
||||
```
|
||||
/goal Manually smoke-test #64 (F12 inline editor diff) in an Extension Development Host (F5) — verify the live editable diff + deletion hints, the Accept ▾/Reject ▾ CodeLens dropdown, editor↔webview parity, and save-while-pending — then start the next backlog item; #59 (P1, macOS Apple-Events prompt, likely @cline/sdk) is highest priority
|
||||
```
|
||||
+4
-4
@@ -1,13 +1,13 @@
|
||||
# Session 0061.0 — Transcript
|
||||
# Session 0059.0 — Transcript
|
||||
|
||||
> App: vscode-cowriting-plugin
|
||||
> Start: 2026-06-27T05-14 (PST)
|
||||
> Start: 2026-06-26T06-01 (PST)
|
||||
> Type: planning-and-executing
|
||||
> Status: **PLACEHOLDER — claimed at session start; finalized at session end.**
|
||||
>
|
||||
> This file reserves session ID 0061 for vscode-cowriting-plugin. The driver replaces this
|
||||
> This file reserves session ID 0059 for vscode-cowriting-plugin. The driver replaces this
|
||||
> body with the full transcript and renames the file to its final
|
||||
> SESSION-0061.0-TRANSCRIPT-2026-06-27T05-14--<end>.md form at session end.
|
||||
> SESSION-0059.0-TRANSCRIPT-2026-06-26T06-01--<end>.md form at session end.
|
||||
|
||||
## Launch prompt
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
# Session 0060.0 — Transcript
|
||||
|
||||
> App: vscode-cowriting-plugin
|
||||
> Start: 2026-06-26T12-52 (PST)
|
||||
> End: 2026-06-26T13-14 (PST)
|
||||
> Type: planning-and-executing
|
||||
> Posture: autonomous (yolo)
|
||||
> Status: **FINALIZED**
|
||||
|
||||
## Launch prompt
|
||||
|
||||
`/goal next` — resume the stored next-goal from session 0059's finalize:
|
||||
"Manually smoke-test #64 in an Extension Development Host (F5), then pick the
|
||||
next backlog item — #59 (P1 Apple-Events prompt) is highest priority."
|
||||
|
||||
The #64 F5 smoke is an interactive operator gesture (flagged, not performed by
|
||||
the session). The autonomous substantive work was **fixing #59** — a standalone
|
||||
leaf `type/bug` (P1), eligible for plan-and-execute under §4.3 R2(b) with no
|
||||
design required.
|
||||
|
||||
## Plan
|
||||
|
||||
Fix #59: the plugin triggers a spurious macOS "control other applications"
|
||||
(Apple Events / Automation TCC) permission prompt; works fine when declined.
|
||||
Root-cause via systematic-debugging, fix via TDD, ship through branch → PR →
|
||||
merge to main.
|
||||
|
||||
## Turn-by-turn arc
|
||||
|
||||
1. **Session init.** Classified `/goal next` → planning-and-executing; claimed
|
||||
session 0060 (`claim-session-id.sh`, no other sessions in flight). Baseline:
|
||||
pulled `main` (was 1 behind), clean apart from two pre-existing stray
|
||||
untracked files (`specs/coauthoring-live-progress.md`,
|
||||
`docs/superpowers/plans/2026-06-26-live-turn-progress.md` — canonical copies
|
||||
live in the content repo; left untouched).
|
||||
|
||||
2. **Read #59** (Gitea API). P1, type/bug. Lead in the issue: not the extension's
|
||||
own code; probable origin `@cline/sdk` agent activation / Claude-Code
|
||||
hub-discovery, which falls back gracefully when denied.
|
||||
|
||||
3. **Root-cause investigation (systematic-debugging Phase 1–2).**
|
||||
- The extension's own code and the **entire JS dependency tree** contain no
|
||||
osascript/AppleScript (only the build-only `vite`). The Apple Event is sent
|
||||
by a spawned subprocess.
|
||||
- Traced the spawn chain: `src/liveTurn.ts` `new sdk.Agent({providerId:
|
||||
"claude-code"})` → `@cline/sdk` → `@cline/llms` `createClaudeCodeProviderModule`
|
||||
→ `ai-sdk-provider-claude-code` `createClaudeCode(options)` → `@anthropic-ai/
|
||||
claude-agent-sdk` `query()` → **spawns the bundled `claude` CLI**
|
||||
(`@anthropic-ai/claude-agent-sdk-darwin-arm64/claude`) headless
|
||||
(`--print --output-format stream-json`).
|
||||
- `runEditTurn` (liveTurn.ts:63) is the **sole** agent-spawn site (`cline.ts`
|
||||
only reads the static tool catalog).
|
||||
- Binary forensics: the `claude` binary contains **26 osascript calls** incl.
|
||||
`tell application "Terminal"/"iTerm"/"Electron"/"Finder"/"System Events"`.
|
||||
Categorized all 26 — every real call is **user-action-gated** (clipboard
|
||||
image, screenshot, `Apple_Terminal`-only theme read, notifications,
|
||||
terminal-setup, Claude-Desktop deep link via `tell application "Electron"`,
|
||||
browser-default-handler detection). The only path that fires **without user
|
||||
action** when `claude` is launched inside the VS Code extension host is
|
||||
**IDE auto-connect** (osascripts to identify/activate the editor). We never
|
||||
use the IDE connection → declining is harmless = exact symptom.
|
||||
- Gate confirmed: `if(!((autoConnectIde||…||CLAUDE_CODE_SSE_PORT||…||
|
||||
CH(CLAUDE_CODE_AUTO_CONNECT_IDE)) && !mK(CLAUDE_CODE_AUTO_CONNECT_IDE))) return;`
|
||||
with `mK("0")===true` → `CLAUDE_CODE_AUTO_CONNECT_IDE=0` hard-disables it.
|
||||
|
||||
4. **Fix design (verified end-to-end, statically).** Pass `options.env` to the
|
||||
Agent. The provider merges `{...getBaseProcessEnv(), ...settings.env}` and the
|
||||
agent-SDK spawns the child with `env = L4 ? {...L4} : {...process.env}`. Seeding
|
||||
`options.env` with the full `process.env` keeps default inheritance intact
|
||||
(login under HOME, proxy/CA vars) and adds only `CLAUDE_CODE_AUTO_CONNECT_IDE=0`
|
||||
(+ `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL=1`, belt-and-suspenders for the
|
||||
extension-install deep link). `options` type is `Record<string,unknown>` — no
|
||||
cast.
|
||||
|
||||
5. **TDD.** RED: unit test asserts `runEditTurn` constructs the Agent with both
|
||||
switches set and the rest of `process.env` preserved (fake Agent captures
|
||||
`cfg`). Watched it fail (`env` undefined). GREEN: added `options.env` to the
|
||||
Agent constructor in `liveTurn.ts`. 250 unit + typecheck + build green.
|
||||
|
||||
6. **Empirical live-turn smoke (`scripts/smoke-live-turn.mjs` + osascript shim)
|
||||
was DECLINED** by the operator (it makes a live network/auth'd agent call).
|
||||
Env-preservation rests on the static chain proof + the unit test instead.
|
||||
|
||||
7. **Ship.** Branch `s60-59-apple-events-prompt` → commit → push → **PR #68** →
|
||||
squash-merge to main (`e671c4b`), branch deleted, **#59 auto-closed**.
|
||||
Post-merge: 250 unit green on fresh main.
|
||||
|
||||
## Cut state
|
||||
|
||||
- **#59 SHIPPED** to main (squash `e671c4b`, PR #68; issue closed).
|
||||
- `src/liveTurn.ts` (+19) and `test/liveTurn.test.ts` (+38) only.
|
||||
- 250 unit + typecheck + build green; E2E unaffected (it stubs the turn, never
|
||||
reaching the real spawn path).
|
||||
- No implementation-plan artifact (small leaf bug) → nothing to archive in
|
||||
`plans/`. No deploy pipeline stage (VS Code extension, no flotilla/PPE) →
|
||||
change ships at merge.
|
||||
|
||||
## Deferred decisions
|
||||
|
||||
- **Did not run the real-turn empirical smoke** (operator declined the live
|
||||
agent call). Alternative: run it with an osascript shim to observe the trigger
|
||||
directly. Why proceeded: the env→spawn chain and gate semantics are proven by
|
||||
static analysis, the plumbing is unit-tested, and the definitive confirmation
|
||||
(fresh-TCC GUI check) is inherently an operator gesture per the issue's
|
||||
acceptance — so the smoke was not load-bearing for shipping.
|
||||
- **Set both `AUTO_CONNECT_IDE=0` and `IDE_SKIP_AUTO_INSTALL=1`** rather than the
|
||||
single minimal switch. Alternative: auto-connect=0 alone (likely sufficient,
|
||||
since auto-install rides the auto-connect flow). Why both: cheap, explicit,
|
||||
both are no-ops outside an IDE; defense-in-depth against a separately-gated
|
||||
install path.
|
||||
|
||||
## Operator plate (next session)
|
||||
|
||||
1. **Operator F5 smoke of #64** (F12 inline editor diff) — still pending from 0059.
|
||||
2. **Fresh-TCC GUI smoke of #59** — reset macOS Automation TCC for the host app,
|
||||
exercise a Claude edit, confirm the "control other applications" prompt is
|
||||
gone and the edit still works.
|
||||
3. Then a backlog item — **#58** (P2 story, self-contained) is the most actionable.
|
||||
|
||||
## Next-session prompt
|
||||
|
||||
```
|
||||
/goal Operator-smoke #64 (F5) + fresh-TCC GUI smoke of #59, then plan-and-execute #58 (proposal accept/decline word-level diff — route proposalBlockHtml through wordMergedMarkdown)
|
||||
```
|
||||
@@ -1,23 +0,0 @@
|
||||
# Session 0062.0 — Transcript
|
||||
|
||||
> App: vscode-cowriting-plugin
|
||||
> Start: 2026-06-27T17-02 (PST)
|
||||
> Type: brainstorming
|
||||
> Posture: careful
|
||||
> Claude-Session: 2c832f9a-a70c-4d71-ab13-c4f39d6eb595
|
||||
> Checkout: /Users/benstull/git/benstull.org/benstull/vscode-cowriting-plugin
|
||||
> Status: **PLACEHOLDER — claimed at session start; finalized at session end.**
|
||||
>
|
||||
> This file reserves session ID 0062 for vscode-cowriting-plugin. The driver replaces this
|
||||
> body with the full transcript and renames the file to its final
|
||||
> SESSION-0062.0-TRANSCRIPT-2026-06-27T17-02--<end>.md form at session end.
|
||||
|
||||
## Launch prompt
|
||||
|
||||
_(launch prompt not captured at claim time)_
|
||||
|
||||
## Deferred decisions
|
||||
|
||||
_Autonomous-mode low-confidence calls the driver made and would have
|
||||
liked operator input on. Appended as the session runs; surfaced at
|
||||
finalize. Empty if none._
|
||||
@@ -1,65 +0,0 @@
|
||||
# Session 0063.0 — Transcript
|
||||
|
||||
> App: vscode-cowriting-plugin
|
||||
> Start: 2026-07-01T18-49 (PST)
|
||||
> Type: brainstorming
|
||||
> Posture: careful
|
||||
> Claude-Session: 1a8fc96b-6f36-4102-be7b-decb53251b2b
|
||||
> Checkout: /Users/benstull/git/benstull.org/benstull/vscode-cowriting-plugin-s0063
|
||||
> Status: **PLACEHOLDER — claimed at session start; finalized at session end.**
|
||||
>
|
||||
> This file reserves session ID 0063 for vscode-cowriting-plugin. The driver replaces this
|
||||
> body with the full transcript and renames the file to its final
|
||||
> SESSION-0063.0-TRANSCRIPT-2026-07-01T18-49--<end>.md form at session end.
|
||||
|
||||
## Launch prompt
|
||||
|
||||
```
|
||||
Examine the existing vs plugin, the prototype, and the half-baked spec that I used Opus to create and make a recommendation for a VS Code experience that allows humans and machines to collaborate on a document, with the machine making suggestions based on human input and the human able to approve, reject, or modify those suggestions. This should use as many VS Code UX paradigms as possible, use as many existing VS Code components or extensions, but create custom components/UX when needed. You can assume this is just Claude as the 'machine' to start
|
||||
|
||||
```
|
||||
|
||||
## Plan
|
||||
|
||||
> Anchor: design-only north-star recommendation (no tracker anchor; lineage =
|
||||
> Epic #1 / F1–F12 + session 0062's `coauthoring-native-surfaces.md` draft —
|
||||
> same anchor treatment 0062 recorded)
|
||||
|
||||
1. Examine the three inputs: the shipped plugin (F1–F12 code on `main`), the
|
||||
prototype, and the half-baked Opus-authored spec (untracked `specs/` in the
|
||||
primary checkout).
|
||||
2. Identify/confirm the anchoring issue (§4.3 R1 gate) — capture one if none fits.
|
||||
3. Walk the consequential UX decisions with the operator (AskUserQuestion
|
||||
checkpoints), grounded in native VS Code paradigms vs custom components.
|
||||
4. Draft the recommendation as a Solution-Design spec in the content repo's
|
||||
`specs/`; whole-document review at the Gitea render URL.
|
||||
|
||||
## Session record (running)
|
||||
|
||||
- Examined the three inputs: shipped plugin (F1–F12 inventory), prototype
|
||||
(`vscode-cowriting-prototype` = rung-2 spike: E1/E3/E5 PASS — key finding:
|
||||
CodeLens does not render in a diff editor; E2/E4 unbuilt), and the 0062 draft
|
||||
`coauthoring-native-surfaces.md` v0.1.0 + companion spike plan.
|
||||
- Recommendation delivered + four forks decided with the operator
|
||||
(AskUserQuestion checkpoints, all recommended options chosen):
|
||||
1. Review model = **in-buffer pending changes + per-hunk CodeLens** (D18;
|
||||
supersedes multi-diff Keep/Undo; amends INV-5/INV-12; resolves Q2/Q7).
|
||||
2. Packaging (Q1) = **evolve the shipped extension in place** (D17; §6.10
|
||||
rewritten from "greenfield").
|
||||
3. Ask surface = **comments-first** (D19; split-pane input webview sunsets).
|
||||
4. Artifact = **amend the 0062 spec to v0.2.0** on content-repo branch
|
||||
`session-0063` (0062's working tree untouched). Also D20 (tweaks × per-hunk
|
||||
decisions), D21 (D11 → shipped reality).
|
||||
- Spec v0.2.0 + spike-spec status committed (`431ebeb`) and pushed to
|
||||
`session-0063`; whole-document review handed to the operator at the Gitea
|
||||
render URL (terminal gate).
|
||||
|
||||
## Deferred decisions
|
||||
|
||||
- Proceeded past the concurrent-session warning (0061/0062 both INPROGRESS,
|
||||
placeholder-only claims from 2026-06-27) because the operator explicitly
|
||||
launched this session; isolated in worktree `session-0063` per #134/§5.4.
|
||||
|
||||
_Autonomous-mode low-confidence calls the driver made and would have
|
||||
liked operator input on. Appended as the session runs; surfaced at
|
||||
finalize. Empty if none._
|
||||
@@ -1,23 +0,0 @@
|
||||
# Session 0064.0 — Transcript
|
||||
|
||||
> App: vscode-cowriting-plugin
|
||||
> Start: 2026-07-01T22-19 (PST)
|
||||
> Type: writing-plans
|
||||
> Posture: careful
|
||||
> Claude-Session: 7c03a44e-1f92-4445-afd9-928efd55afba
|
||||
> Checkout: /Users/benstull/git/benstull.org/benstull/vscode-cowriting-plugin-wp
|
||||
> Status: **PLACEHOLDER — claimed at session start; finalized at session end.**
|
||||
>
|
||||
> This file reserves session ID 0064 for vscode-cowriting-plugin. The driver replaces this
|
||||
> body with the full transcript and renames the file to its final
|
||||
> SESSION-0064.0-TRANSCRIPT-2026-07-01T22-19--<end>.md form at session end.
|
||||
|
||||
## Launch prompt
|
||||
|
||||
_(launch prompt not captured at claim time)_
|
||||
|
||||
## Deferred decisions
|
||||
|
||||
_Autonomous-mode low-confidence calls the driver made and would have
|
||||
liked operator input on. Appended as the session runs; surfaced at
|
||||
finalize. Empty if none._
|
||||
@@ -175,20 +175,5 @@
|
||||
},
|
||||
"0059": {
|
||||
"title": ""
|
||||
},
|
||||
"0060": {
|
||||
"title": ""
|
||||
},
|
||||
"0061": {
|
||||
"title": ""
|
||||
},
|
||||
"0062": {
|
||||
"title": ""
|
||||
},
|
||||
"0063": {
|
||||
"title": ""
|
||||
},
|
||||
"0064": {
|
||||
"title": ""
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
---
|
||||
status: graduated
|
||||
---
|
||||
# Solution Design: Inline editable proposed-change diff in the Markdown editor (#64)
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| **Author(s)** | Ben Stull (with Claude) |
|
||||
| **Reviewers / approvers** | Ben Stull |
|
||||
| **Status** | `graduated` |
|
||||
| **Version** | v0.1.1 |
|
||||
| **Source artifacts** | Feature `benstull/vscode-cowriting-plugin#64` (Inline editable proposed-change diff in the Markdown editor + Accept/Reject controls in both surfaces, `type/feature`, `priority/P2`) · Brainstorming session `vscode-cowriting-plugin-0058` (2026-06-26) · Builds on (all shipped): F4 `#12` (propose/accept seam, INV-9/10/11/13), F6 `#17` (baseline / machine-landing), F7 `#21` (rendered preview, pure render engine INV-22), F10 `#29` (interactive review preview — the **clean-editor** decision INV-32; ✓/✗ accept-reject), F11 `#43` (preview toolbar, `data-src` block→source mapping INV-36), document-edit-flow `#42/#47/#46` (block proposals INV-39/40, accept-all INV-42) · Parent specs (graduated): `coauthoring-propose-accept.md`, `coauthoring-diff-view.md`, `coauthoring-rendered-preview.md`, `coauthoring-interactive-review.md`, `coauthoring-document-edit-flow.md` · Lineage: `ben.stull/rfc-app#48` |
|
||||
|
||||
**Change log**
|
||||
|
||||
| Date | Version | Change | By |
|
||||
| --- | --- | --- | --- |
|
||||
| 2026-06-26 | v0.1.1 | Implementation refinement (planning-and-executing session 0059): made the **re-anchor** explicit. Optimistic apply (§3.2) must store the pre-apply text on a new `Proposal.original` field **and** re-fingerprint the proposal's anchor to the *applied* text — F4's `fp.text` is the *original* target, which leaves the buffer once the replacement lands, so `resolve()` would orphan every applied proposal otherwise. `finalizeInPlace`/`revertInPlace`/decorate all key off the re-anchored fp; revert restores `original`. Reload-safety (INV-51/54): a proposal already carrying `original` is never re-captured (the in-memory applied-set is empty after a window reload), so the revert target survives save+reload. Shipped #64 (PR, session 0059). |
|
||||
| 2026-06-26 | v0.1.0 | Initial draft — brainstorming session 0058. Four forks locked with the operator: **(1) editor model** = *optimistic apply + decorations* — on propose, the editor buffer becomes the would-be-accepted text (insertions real & editable & tinted; deletions shown as struck-red non-editable hints); accept = finalize-in-place, reject = revert. **(2) timing** = *on proposal* (turn complete), not a live token-stream into the editor (that stays in #60's notification/OutputChannel). **(3) editor affordance** = CodeLens `Accept ▾ / Reject ▾` above each block, `▾` → QuickPick (this / all); the webview keeps HTML buttons with the same dropdown. **(4) controls parity** = Accept / Reject / Accept-all / Reject-all reachable from **both** the editor and the webview. Two sub-decisions confirmed: a **dedicated `EditorProposalController`** owns optimistic-apply + decorations + CodeLens (keeps `ProposalController` the pure F4 state/seam owner); **saving while pending persists** the proposed (accepted-result) text. Reverses INV-32 and INV-10; supersedes the ✓/✗ glyph controls. | Ben Stull + Claude |
|
||||
|
||||
---
|
||||
|
||||
## 1. Business Context
|
||||
|
||||
### 1.1 Executive Summary
|
||||
|
||||
Today, when Claude proposes an edit, the change is shown **only in the rendered
|
||||
review webview** (`<del>old</del><ins>new</ins>` with ✓/✗ controls); the Markdown
|
||||
**editor stays deliberately clean** (F10 / INV-32 — "the preview is the single
|
||||
review surface"). The writer who lives in the editor sees nothing: to review what
|
||||
Claude proposed they must open the preview panel, and they cannot *edit* the
|
||||
proposed text in place — they can only accept or reject it wholesale in the
|
||||
webview.
|
||||
|
||||
This design brings the proposed change **into the Markdown editor itself**:
|
||||
editable, with a track-changes diff that matches the webview and the post-accept
|
||||
result **exactly**. It also replaces the per-proposal `✓`/`✗` glyphs with labelled
|
||||
**Accept** / **Reject** controls — each carrying a `▾` dropdown for **Accept all**
|
||||
/ **Reject all** — and makes all four actions reachable from **both** the editor
|
||||
and the webview. The writer can now read, tweak, and resolve a proposal without
|
||||
leaving the document.
|
||||
|
||||
### 1.2 Background
|
||||
|
||||
The plugin's review model (graduated specs `coauthoring-propose-accept.md`,
|
||||
`coauthoring-rendered-preview.md`, `coauthoring-interactive-review.md`):
|
||||
|
||||
- A machine edit becomes an **F4 proposal** — a pending-only record
|
||||
(`Proposal{ id, anchorId, replacement, granularity }` + a `Fingerprint` anchor
|
||||
whose `text` is the exact target) that **never mutates the document** (INV-10),
|
||||
re-resolved against the live text at accept (INV-11) and cleared when
|
||||
accepted/rejected (INV-13).
|
||||
- The **render engine** (`trackChangesModel.ts`) is a pure, deterministic,
|
||||
`vscode`-free unit (INV-22): it diffs at **block** granularity (INV-39), word-
|
||||
merges prose blocks, and emits webview HTML — `renderReview` (annotated) /
|
||||
`renderPlain` (clean) — with proposal blocks (`proposalBlockHtml`) carrying the
|
||||
✓/✗ buttons and `data-src` offsets for selection mapping (INV-36).
|
||||
- The **F10 decision (INV-32)** removed *all* in-editor decorations
|
||||
(`grep` confirms zero `TextEditorDecorationType` / `setDecorations` in the tree)
|
||||
so the webview is the sole review surface; `ProposalController` carries the note
|
||||
*"no in-editor UI — INV-32 makes the rendered preview the single review surface."*
|
||||
- The sealed webview is **intent-only** (INV-35): it posts `{accept|reject|
|
||||
acceptAll|…}` to the host, which routes to `ProposalController.acceptById` /
|
||||
`rejectById` / `acceptAllProposals` (#46 / INV-42). Accept **applies** the
|
||||
replacement via the F4 seam (`applyAgentEdit`), which advances the F6 baseline
|
||||
(machine-landing, INV-18).
|
||||
|
||||
This feature **deliberately reverses two of those decisions** for the editor
|
||||
surface, and supersedes the ✓/✗ glyph controls in both surfaces.
|
||||
|
||||
### 1.3 Who feels it & why
|
||||
|
||||
The **human coauthor working in the editor** — the writer who asked Claude to edit
|
||||
and wants to see, adjust, and resolve the result without context-switching to the
|
||||
preview panel. The pain: the proposed change is invisible in the place they are
|
||||
actually writing, and it is not editable at all (only accept/reject-able). P2
|
||||
(issue #64): it materially deepens the inner-loop "edit-in-place" experience and
|
||||
unifies the review controls, but the webview review path already works, so it is
|
||||
an enhancement rather than a gap.
|
||||
|
||||
---
|
||||
|
||||
## 2. Product Design
|
||||
|
||||
### 2.1 The experience
|
||||
|
||||
When Claude's turn lands a proposal (or, for a document edit, N block proposals),
|
||||
the **editor** shows the change as track-changes, in place:
|
||||
|
||||
```
|
||||
Accept ▾ Reject ▾ ← CodeLens, above each proposed block
|
||||
The quick ~~brown~~ red fox jumps over the lazy dog.
|
||||
└ struck red ┘└ green/blue, editable ┘
|
||||
```
|
||||
|
||||
- **Insertions** are **real, editable buffer text**, tinted by origin
|
||||
(green = human-origin, blue = LLM) — the writer can click in and edit them like
|
||||
any other text.
|
||||
- **Deletions** appear as a **struck-red, non-editable hint** rendered adjacent to
|
||||
the insertion (a decoration, not buffer text) — visually mirroring the webview's
|
||||
`<del>…</del>`.
|
||||
- The buffer content **is exactly the would-be-accepted result**, so what the
|
||||
writer sees (and can edit) is precisely what accepting produces.
|
||||
|
||||
Above each proposed block sit two **CodeLens** actions — **`Accept ▾`** and
|
||||
**`Reject ▾`**. Clicking opens a small QuickPick:
|
||||
|
||||
```
|
||||
Accept ▾ → ┌───────────────────────┐ Reject ▾ → ┌───────────────────────┐
|
||||
│ Accept this proposal │ │ Reject this proposal │
|
||||
│ Accept ALL proposals │ │ Reject ALL proposals │
|
||||
└───────────────────────┘ └───────────────────────┘
|
||||
```
|
||||
|
||||
The **webview** shows the same proposal with the same diff, and its controls are
|
||||
the parallel HTML buttons — **`Accept ▾`** / **`Reject ▾`** — where the `▾`
|
||||
reveals *Accept all* / *Reject all*. The legacy ✓/✗ glyphs are **replaced** by
|
||||
these labelled controls in both surfaces.
|
||||
|
||||
All four actions — **Accept**, **Reject**, **Accept all**, **Reject all** — are
|
||||
reachable from **either** surface and route to the same controller logic
|
||||
(INV-53).
|
||||
|
||||
### 2.2 Accept / Reject semantics (editable-in-place)
|
||||
|
||||
- **Accept** finalizes the change *that is already in the buffer*: it records the
|
||||
span's attribution as landed, advances the F6 baseline (machine-landing), and
|
||||
clears the proposal. It does **not** re-apply text (the text is already there) —
|
||||
see §3.3.
|
||||
- **Reject** reverts that block's region back to the stored original
|
||||
(`Fingerprint.text`), and clears the proposal.
|
||||
- **If the writer edited the inserted text before deciding:** **Accept** keeps
|
||||
their edited text (their keystrokes layer on as human authorship over the
|
||||
proposed span); **Reject** still reverts the whole block to the original.
|
||||
- **Accept all / Reject all** operate on the current document's pending proposals,
|
||||
in descending anchor order, skipping orphans (the #46 / INV-42 shape; **Reject
|
||||
all is new**).
|
||||
|
||||
### 2.3 Save semantics
|
||||
|
||||
Because the proposed text is *in the buffer*, **saving while a proposal is pending
|
||||
persists the proposed (accepted-result) text** to disk. The deletion hints are
|
||||
decorations (never buffer text), so the **saved file is clean** — it contains the
|
||||
accepted-result text, not yet "finalized" only in the sense of attribution /
|
||||
baseline. "Pending" therefore means *provisional attribution, baseline not yet
|
||||
advanced* — **not** "document unchanged" (INV-54). We deliberately **allow** the
|
||||
save rather than block it or strip on save; once the editor shows the live
|
||||
document, blocking saves would be the surprising behavior.
|
||||
|
||||
### 2.4 What this is *not* (non-goals)
|
||||
|
||||
- **Not live token-streaming into the editor.** The diff appears when the turn
|
||||
produces a proposal; watching Claude type into the document is out of scope (the
|
||||
live token stream is #60's notification + OutputChannel).
|
||||
- **Not a new review *model*.** F4 proposals, anchoring (INV-11), block
|
||||
granularity (INV-39/40), accept-all (INV-42) are reused; this adds an editor
|
||||
*surface* and unifies the controls.
|
||||
- **Not non-Markdown.** Same Markdown-gated scope as the rest of the review UI.
|
||||
- **Not intra-diagram mermaid editing.** Atomic fences stay atomic (INV-23); a
|
||||
mermaid block proposal is editable as its whole fence, not sub-diagram.
|
||||
- **Not removing the webview.** The rendered preview remains a full review surface;
|
||||
it gains label/dropdown parity, not a demotion.
|
||||
|
||||
### 2.5 Surfaces considered & rejected
|
||||
|
||||
| Editor approach | Why not |
|
||||
| --- | --- |
|
||||
| **Read-only decoration overlay** (doc unchanged; ghost insertions via decoration) | The inserted text would **not be editable** — fails the core "human-editable" requirement. |
|
||||
| **Inline track-changes markup in the buffer** (`{~~old~~|++new++}`) | Pollutes the file on disk with markup until resolved; complex; conflicts with clean save. |
|
||||
| **Native `vscode.diff` two-pane** | The two-pane diff was *removed* in #34 (F10) precisely to make one review surface; a separate diff editor is not "in the Markdown file." |
|
||||
|
||||
Chosen: **optimistic apply + decorations** — the only model that yields an
|
||||
editable diff that is *exactly* the accepted result, in the document itself.
|
||||
|
||||
---
|
||||
|
||||
## 3. Engineering Design
|
||||
|
||||
### 3.1 Architecture
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────┐
|
||||
one F4 turn ───▶ │ ProposalController (F4 state/seam owner) │
|
||||
(#12 propose) │ propose() · finalizeInPlace() · revertInPlace│
|
||||
│ · rejectAll() · onDidChangeProposals │
|
||||
└───────────────┬──────────────────────────────┘
|
||||
│ proposals (pending records + anchors)
|
||||
┌─────────────────────┴───────────────────────┐
|
||||
▼ ▼
|
||||
┌───────────────────────────┐ ┌────────────────────────────┐
|
||||
│ EditorProposalController │ shared │ TrackChangesPreview- │
|
||||
│ (NEW, vscode host) │ pure diff │ Controller (webview) │
|
||||
│ · optimistic buffer write │◀──────────────▶ │ · renderReview HTML │
|
||||
│ · insertion tint deco │ trackChangesModel│ · Accept▾/Reject▾ buttons │
|
||||
│ · deletion-hint deco │ (diff → plan) │ · dropdown → acceptAll/ │
|
||||
│ · CodeLens Accept▾/Reject▾│ │ rejectAll │
|
||||
└───────────────────────────┘ └────────────────────────────┘
|
||||
▲ ▲
|
||||
└──────────── both route actions to ───────────┘
|
||||
ProposalController.{finalizeInPlace,revertInPlace,
|
||||
acceptAll,rejectAll}
|
||||
```
|
||||
|
||||
The decisive rule: **one pure diff is the single source of truth** for both
|
||||
surfaces (INV-49). The editor renders it as *buffer text + decorations + CodeLens*;
|
||||
the webview renders it as *HTML*. They cannot diverge because they consume the
|
||||
same hunks.
|
||||
|
||||
### 3.2 Optimistic apply (on propose) — INV-48
|
||||
|
||||
`propose()` gains a buffer-write step, owned by `EditorProposalController` (so
|
||||
`ProposalController` stays the pure state owner):
|
||||
|
||||
1. Record the pending proposal(s) + anchor(s) **exactly as today** (the sidecar
|
||||
record is unchanged: `replacement`, `Fingerprint{text,before,after,lineHint}`,
|
||||
`granularity`).
|
||||
2. Write the proposed text into the **live editor buffer**: replace the resolved
|
||||
anchor span with `replacement` (for a document turn, this makes the buffer
|
||||
Claude's full proposed document; for a selection turn, the single span). This
|
||||
write **does not advance the F6 baseline** — the baseline stays at the
|
||||
pre-proposal text, so the change reads as *pending*, not *landed*.
|
||||
3. Compute the **decoration plan** from the same per-block word/line diff used by
|
||||
`acceptBlock` (`wordEditHunks(fp.text, replacement)`): insertion segments →
|
||||
tinted ranges (buffer coords, offset by the live anchor); deletion segments →
|
||||
struck-red hint injections (decoration `before`/`after` content) at the segment
|
||||
boundary.
|
||||
|
||||
Critically, the optimistic write must **not** fire the F4 seam's
|
||||
`onDidApplyAgentEdit` (which would advance the baseline / register a landed edit).
|
||||
Optimistic apply is a *distinct* buffer-mutation path from accept; only **accept**
|
||||
advances the baseline (§3.3). This is the load-bearing distinction that keeps the
|
||||
change *pending* while *present*.
|
||||
|
||||
### 3.3 Accept = finalize-in-place; Reject = revert-in-place — INV-51
|
||||
|
||||
Because the proposed text is already in the buffer, the old "accept ⇒ apply via
|
||||
seam" path would **double-apply**. The accept/reject paths are reworked:
|
||||
|
||||
- **`finalizeInPlace(id)`** — resolve the proposal's anchor against the live text;
|
||||
record the span's attribution as **landed** (provenance from the proposal's
|
||||
`author`, word-precise per INV-40 for block granularity); **advance the F6
|
||||
baseline** for that region (the machine-landing the seam used to do on apply);
|
||||
`removeProposal(id)`. No text is re-applied. If the writer edited the inserted
|
||||
span, the *current* buffer text is what gets finalized (their edits become
|
||||
layered human authorship).
|
||||
- **`revertInPlace(id)`** — resolve the proposal's live span; replace it with the
|
||||
stored original `Fingerprint.text`; `removeProposal(id)`. Reverts the whole
|
||||
block regardless of any in-place edits.
|
||||
- **`acceptAll()` / `rejectAll()`** — iterate the current document's pending
|
||||
proposals in **descending** anchor order (so earlier resolutions don't shift
|
||||
later offsets), skipping orphans with a tally (INV-42 shape). `acceptAll` reuses
|
||||
the #46 batch ordering; **`rejectAll` is new** and symmetric.
|
||||
|
||||
Both surfaces (editor CodeLens/QuickPick and webview buttons/dropdown) call these
|
||||
**same four methods** (INV-53). The webview's existing intent messages are renamed/
|
||||
extended (`accept`/`reject`/`acceptAll` + new `rejectAll`) but stay intent-only
|
||||
(INV-35).
|
||||
|
||||
### 3.4 Single diff source & render-once — INV-49 / INV-50
|
||||
|
||||
- **INV-49 (single diff source).** The per-proposal diff (block hunks → word/line
|
||||
edit hunks) is produced by one pure function in `trackChangesModel.ts` (extends
|
||||
the existing `diffToBlockHunks` / `wordEditHunks`, INV-39/40). The webview HTML
|
||||
path and the editor decoration-plan path both consume it. Same proposal ⇒
|
||||
identical diff in both surfaces (this is the testable parity guarantee).
|
||||
- **INV-50 (render once).** With optimistic apply, the baseline→buffer delta now
|
||||
*contains* the proposed change. The renderer must attribute any baseline→buffer
|
||||
delta that is covered by a **pending proposal** to that proposal (rendered as a
|
||||
proposal block), and must **not** also render it as an already-landed
|
||||
machine-diff. Mechanism: the webview render reconciles baseline-diff spans
|
||||
against pending-proposal anchors; a span covered by a pending proposal is
|
||||
rendered exactly once, as the proposal. *(This reconciliation is the primary
|
||||
implementation risk; the implementation plan owns the exact span-mapping, but the
|
||||
invariant — rendered once — is fixed here.)*
|
||||
|
||||
### 3.5 Editor decorations & CodeLens (the editor surface)
|
||||
|
||||
`EditorProposalController` (new, `vscode` host module) owns:
|
||||
|
||||
- **Two `TextEditorDecorationType`s** — an *insertion tint* (green/blue background,
|
||||
by provenance) over real buffer ranges, and a *deletion hint* (a
|
||||
`before`/`after` render-option carrying the struck original text, red,
|
||||
strikethrough, non-editable). Both are recomputed from the decoration plan on
|
||||
every `onDidChangeProposals` and on active-editor change.
|
||||
- **A `CodeLensProvider`** — for each pending proposal whose anchor resolves in the
|
||||
active document, emit two lenses positioned above the block: `Accept ▾`
|
||||
(command `cowriting.proposalAcceptMenu` with the proposal id) and `Reject ▾`
|
||||
(`cowriting.proposalRejectMenu`). Each command opens a `vscode.window
|
||||
.showQuickPick(["… this proposal","… ALL proposals"])` and dispatches to
|
||||
`finalizeInPlace`/`acceptAll` or `revertInPlace`/`rejectAll`.
|
||||
- **Lifecycle wiring** — subscribes to `proposals.onDidChangeProposals` (the same
|
||||
event the preview uses) and `window.onDidChangeActiveTextEditor`; clears its
|
||||
decorations + lenses for documents with no pending proposals (so a clean editor
|
||||
stays clean — INV-32's spirit holds *when there is nothing pending*).
|
||||
|
||||
Deletion hints are **decoration-only** (never buffer text, never saved) and
|
||||
insertion tints decorate **real** buffer text (INV-52).
|
||||
|
||||
### 3.6 Webview controls (label + dropdown parity)
|
||||
|
||||
`proposalBlockHtml` (`trackChangesModel.ts`) swaps the ✓/✗ glyph buttons for an
|
||||
**`Accept ▾`** / **`Reject ▾`** control pair. The `▾` opens a small CSS/JS dropdown
|
||||
in the sealed webview (`preview.ts`/`preview.css`, no network — INV-21) offering
|
||||
*Accept all* / *Reject all*; selecting posts the corresponding intent
|
||||
(`acceptAll` / `rejectAll`) or the per-proposal `accept`/`reject`. The host routes
|
||||
all four to the controller methods of §3.3 (INV-35 preserved).
|
||||
|
||||
### 3.7 Components & files
|
||||
|
||||
| File | Change |
|
||||
| --- | --- |
|
||||
| `src/editorProposalController.ts` | **NEW** — optimistic apply, decoration types, deletion-hint injection, `CodeLensProvider`, QuickPick menus; subscribes to `onDidChangeProposals` + active-editor change. |
|
||||
| `src/proposalController.ts` | Add `finalizeInPlace(id)`, `revertInPlace(id)`, `rejectAll(docKey)`; `propose()` delegates the optimistic buffer write (so the controller stays state-pure); accept/reject routing now finalizes/reverts in place (no seam re-apply). |
|
||||
| `src/trackChangesModel.ts` | Factor the shared per-proposal diff into one pure producer feeding both surfaces; reconcile pending-proposal spans in `renderReview` (INV-50); swap ✓/✗ → `Accept ▾`/`Reject ▾` in `proposalBlockHtml`. |
|
||||
| `src/trackChangesPreview.ts` | Route new `rejectAll` intent; keep `accept`/`reject`/`acceptAll`; relabel toolbar/proposal controls. |
|
||||
| `src/preview.ts` / `preview.css` | Dropdown control for `Accept ▾`/`Reject ▾`; same diff CSS reused. |
|
||||
| `src/extension.ts` | Register `EditorProposalController`, its CodeLens provider, and the menu commands; wire it alongside `ProposalController`/`TrackChangesPreviewController`. |
|
||||
| `package.json` | Add `cowriting.rejectAllProposals`, `cowriting.proposalAcceptMenu`, `cowriting.proposalRejectMenu`; CodeLens contribution; markdown-gated `when` clauses. |
|
||||
|
||||
### 3.8 Invariants
|
||||
|
||||
- **INV-48 — Optimistic apply (with re-anchor).** On propose, the proposed text is
|
||||
written into the live editor buffer (the buffer becomes the would-be-accepted
|
||||
result); this write does **not** advance the F6 baseline and does **not** fire the
|
||||
F4 machine-landing seam. Because F4's `fp.text` is the *original* target — which
|
||||
leaves the buffer once the replacement lands — optimistic apply **stores the
|
||||
pre-apply text on `Proposal.original` and re-fingerprints the anchor to the applied
|
||||
text**, so `resolve()` keeps finding the proposal in the mutated buffer; finalize /
|
||||
revert / decorate all key off the re-anchored fp, and revert restores `original`.
|
||||
`original` is captured **exactly once** (first apply): a proposal that survives a
|
||||
save+reload already carries it, so a fresh session never re-captures it from the
|
||||
already-applied buffer (reload-safety, INV-51/54). **Reverses INV-10** (propose no
|
||||
longer leaves the document untouched) and **INV-32** (the editor is no longer kept
|
||||
unconditionally clean — it shows pending proposals).
|
||||
- **INV-49 — Single diff source.** Editor decorations and webview HTML both derive
|
||||
from one pure, deterministic per-proposal diff (extends `diffToBlockHunks` /
|
||||
`wordEditHunks`, INV-22/39/40). The same proposal yields the same diff in both
|
||||
surfaces.
|
||||
- **INV-50 — Rendered once.** A span covered by a pending proposal is rendered
|
||||
exactly once — as that proposal — never additionally as an already-landed
|
||||
baseline diff.
|
||||
- **INV-51 — Finalize / revert in place.** Accept finalizes the span already in the
|
||||
buffer (record attribution, advance baseline, clear proposal) without
|
||||
re-applying text; Reject reverts the block region to the stored
|
||||
`Fingerprint.text`. No double-apply.
|
||||
- **INV-52 — Decoration roles.** Deletion hints are decoration-only (non-editable
|
||||
`before`/`after` content, never buffer text, never saved); insertion tints
|
||||
decorate real, editable buffer text.
|
||||
- **INV-53 — Control parity.** Accept / Reject / Accept-all / Reject-all are
|
||||
reachable from **both** the editor (CodeLens + QuickPick) and the webview
|
||||
(buttons + dropdown) and route to the same `ProposalController` methods; the ✓/✗
|
||||
glyph controls are superseded by labelled `Accept ▾`/`Reject ▾`.
|
||||
- **INV-54 — Save persists pending.** Saving while a proposal is pending persists
|
||||
the proposed (accepted-result) text; "pending" denotes provisional attribution /
|
||||
un-advanced baseline, not document divergence. (Decorations are not persisted, so
|
||||
the saved file is clean text.)
|
||||
|
||||
### 3.9 Error & edge handling
|
||||
|
||||
- **Orphaned proposal** (anchor no longer resolves) — no editor decorations/lenses
|
||||
for it; it still surfaces in the webview at end with a dashed border (INV-34);
|
||||
accept-all/reject-all skip it with a tally (INV-42).
|
||||
- **Writer edits the inserted span, then accepts** — current buffer text is
|
||||
finalized (their edits layer as human authorship); **then rejects** — block
|
||||
reverts to original regardless.
|
||||
- **External / concurrent edit shifts geometry** — anchors re-resolve on
|
||||
`onDidChangeProposals` (existing resolve-or-flag); decoration plan + lenses
|
||||
recompute.
|
||||
- **Multiple proposals from one turn** — all optimistically applied (buffer = full
|
||||
proposed document); each block independently finalizable/revertible; descending
|
||||
order on accept-all/reject-all keeps offsets valid.
|
||||
- **Reject of an in-buffer span after partial accept of siblings** — each
|
||||
proposal's revert uses its own live-resolved span, independent of siblings.
|
||||
- **Non-authorable document** (read-only / not on disk) — controls disabled exactly
|
||||
as today (`authorable` gating).
|
||||
|
||||
---
|
||||
|
||||
## 4. Testing & E2E
|
||||
|
||||
Per the §9 pipeline and `coauthoring-*` precedent (this is a VS Code extension —
|
||||
**no flotilla/PPE**; the gate is unit + host-E2E green).
|
||||
|
||||
- **Unit (the core):**
|
||||
- The shared per-proposal diff producer: same hunks → insertion/deletion
|
||||
segments; parity assertion that the decoration plan and the webview HTML derive
|
||||
identical add/del spans for the same proposal (INV-49).
|
||||
- `renderReview` render-once reconciliation: a pending-proposal span is emitted
|
||||
as a proposal block and **not** as a landed baseline diff (INV-50).
|
||||
- Decoration-plan computation from `wordEditHunks(fp.text, replacement)`:
|
||||
insertion ranges in buffer coords; deletion-hint positions (INV-52).
|
||||
- **Host E2E:**
|
||||
- Propose (via the injectable `editTurn` stub) → editor shows insertion tint +
|
||||
deletion hint + `Accept ▾`/`Reject ▾` CodeLens; buffer equals the accepted
|
||||
result (INV-48).
|
||||
- Edit the inserted text → **finalizeInPlace** keeps the edited text; baseline
|
||||
advanced; proposal cleared (INV-51).
|
||||
- **revertInPlace** restores `Fingerprint.text`; proposal cleared.
|
||||
- Accept / Reject / Accept-all / Reject-all from **both** the editor command path
|
||||
and the webview intent path produce the same end state (INV-53); `rejectAll`
|
||||
clears all pending and reverts all blocks.
|
||||
- Save while a proposal is pending → file on disk has the proposed text; no
|
||||
decoration markup in the saved bytes (INV-54).
|
||||
- Webview/editor parity: same proposal renders the same diff in both (INV-49).
|
||||
- **Manual smoke:** ask Claude to edit a paragraph; confirm the editor diff is
|
||||
editable, the deletion hint reads correctly, both surfaces' controls resolve it,
|
||||
and a clean editor returns once nothing is pending.
|
||||
|
||||
---
|
||||
|
||||
## 5. Delivery Plan (rollout — not a task list)
|
||||
|
||||
One increment, single design-then-build (#64). Ships through branch → PR → `main`;
|
||||
no migration and no new persisted sidecar shape (the `Proposal` record is
|
||||
unchanged). The implementation plan (downstream `wgl-planning-and-executing`
|
||||
session) owns the Task breakdown; a natural cut:
|
||||
|
||||
1. **Shared diff + render-once** — factor the pure per-proposal diff producer;
|
||||
reconcile pending spans in `renderReview` (INV-49/50) + unit tests.
|
||||
2. **Accept/reject rework** — `finalizeInPlace` / `revertInPlace` / `rejectAll` on
|
||||
`ProposalController` (no seam re-apply); unit tests.
|
||||
3. **Editor surface** — `EditorProposalController`: optimistic apply, decorations,
|
||||
deletion hints, CodeLens + QuickPick menus; wire in `extension.ts`.
|
||||
4. **Control parity** — relabel ✓/✗ → `Accept ▾`/`Reject ▾` + dropdown in the
|
||||
webview; route `rejectAll`; `package.json` commands/`when`.
|
||||
5. **Host E2E + manual smoke** across both surfaces.
|
||||
|
||||
Reversible by reverting the PR (restores the clean-editor / ✓-✗ webview behavior).
|
||||
|
||||
---
|
||||
|
||||
## 6. Open Questions
|
||||
|
||||
- **OQ-1 — Provenance tint exactness.** Insertion tint uses green=human-origin /
|
||||
blue=LLM by the proposal `author`; whether to additionally word-tint *within* a
|
||||
block by the F3 attribution of edited-in-place text (vs a single block tint) can
|
||||
follow the existing F9/F10 coloring; v1 tints the proposed insertion by the
|
||||
proposal author. *(Not blocking.)*
|
||||
- **OQ-2 (inherited)** — The F11 design (`#43`) remains un-graduated (lives in code
|
||||
+ an issue draft); unrelated to #64 but noted in the shared lineage. Track
|
||||
separately.
|
||||
- **OQ-3 — Editor dropdown fidelity.** The editor uses a QuickPick to stand in for
|
||||
the webview's true `▾` dropdown (CodeLens cannot render a caret menu inline); if
|
||||
a more button-like affordance is wanted later, a webview-style overlay is a
|
||||
possible increment. *(Accepted for v1.)*
|
||||
+29
-128
@@ -7,34 +7,24 @@
|
||||
* for deletions (INV-52, decorationPlan/INV-49), and (3) provides a CodeLens
|
||||
* `Accept ▾ / Reject ▾` above each block whose ▾ opens a QuickPick (this / all).
|
||||
* Owns no proposal STATE — it is a view over ProposalController (which stays the
|
||||
* pure F4 owner). Phase 2 decorates ALL committed changes-since-baseline by author
|
||||
* (human green / Claude blue + struck hints for deletions), plus pending proposals;
|
||||
* a pinned baseline suppresses committed marks entirely (pin→clean, INV-48).
|
||||
* pure F4 owner). A document with no pending proposals shows nothing (INV-32's
|
||||
* spirit when nothing is pending).
|
||||
*/
|
||||
import * as vscode from "vscode";
|
||||
import type { ProposalController } from "./proposalController";
|
||||
import type { DiffViewController } from "./diffViewController";
|
||||
import type { AttributionController } from "./attributionController";
|
||||
import { decorationPlan, wordEditHunks, authorAt } from "./trackChangesModel";
|
||||
import { decorationPlan } from "./trackChangesModel";
|
||||
import { isAuthorable } from "./workspacePath";
|
||||
|
||||
export class EditorProposalController implements vscode.Disposable, vscode.CodeLensProvider {
|
||||
private readonly disposables: vscode.Disposable[] = [];
|
||||
private readonly insDeco: Record<"human" | "claude", vscode.TextEditorDecorationType> = {
|
||||
human: vscode.window.createTextEditorDecorationType({
|
||||
backgroundColor: "rgba(63,185,80,0.14)", borderColor: "#3fb950",
|
||||
border: "0 0 2px 0", borderStyle: "solid",
|
||||
}),
|
||||
claude: vscode.window.createTextEditorDecorationType({
|
||||
backgroundColor: "rgba(88,166,255,0.15)", borderColor: "#58a6ff",
|
||||
border: "0 0 2px 0", borderStyle: "solid",
|
||||
}),
|
||||
};
|
||||
private readonly delDeco: Record<"human" | "claude" | "none", vscode.TextEditorDecorationType> = {
|
||||
human: vscode.window.createTextEditorDecorationType({ after: { color: "#f85149" } }),
|
||||
claude: vscode.window.createTextEditorDecorationType({ after: { color: "#bc8cff" } }),
|
||||
none: vscode.window.createTextEditorDecorationType({ after: { color: new vscode.ThemeColor("descriptionForeground") } }),
|
||||
};
|
||||
private readonly insertionDeco = vscode.window.createTextEditorDecorationType({
|
||||
backgroundColor: new vscode.ThemeColor("diffEditor.insertedTextBackground"),
|
||||
});
|
||||
private readonly deletionDeco = vscode.window.createTextEditorDecorationType({
|
||||
// a non-editable struck-red hint injected AFTER the insertion (INV-52)
|
||||
after: { color: new vscode.ThemeColor("gitDecoration.deletedResourceForeground") },
|
||||
textDecoration: "none",
|
||||
});
|
||||
private readonly lensEmitter = new vscode.EventEmitter<void>();
|
||||
readonly onDidChangeCodeLenses = this.lensEmitter.event;
|
||||
/** Pending debounce timers — one per URI — coalesce rapid-fire propose events
|
||||
@@ -44,29 +34,13 @@ export class EditorProposalController implements vscode.Disposable, vscode.CodeL
|
||||
* optimisticApply runs concurrently with the still-in-progress propose loop,
|
||||
* causing "file changed in the meantime" workspace-edit conflicts. */
|
||||
private readonly pendingApply = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
/** Debounce timers for committed-change re-render (one per URI, 50 ms). */
|
||||
private readonly pendingRender = new Map<string, ReturnType<typeof setTimeout>>();
|
||||
|
||||
constructor(
|
||||
private readonly proposals: ProposalController,
|
||||
private readonly diffView: DiffViewController,
|
||||
private readonly attribution: AttributionController,
|
||||
) {
|
||||
constructor(private readonly proposals: ProposalController) {
|
||||
this.disposables.push(
|
||||
this.insDeco.human, this.insDeco.claude, this.delDeco.human, this.delDeco.claude, this.delDeco.none, this.lensEmitter,
|
||||
this.insertionDeco, this.deletionDeco, this.lensEmitter,
|
||||
vscode.languages.registerCodeLensProvider({ language: "markdown" }, this),
|
||||
this.proposals.onDidChangeProposals(({ uri }) => this.scheduleApply(uri)),
|
||||
vscode.window.onDidChangeActiveTextEditor((ed) => ed && this.renderEditor(ed)),
|
||||
// Refresh committed decorations when the baseline advances (pin / machine-landing / open).
|
||||
this.diffView.onDidChangeBaseline(({ uri }) => {
|
||||
const ed = vscode.window.visibleTextEditors.find((e) => e.document.uri.toString() === uri);
|
||||
if (ed) this.renderEditor(ed);
|
||||
}),
|
||||
// Refresh committed decorations (debounced) when the active doc changes — attribution spans shift.
|
||||
vscode.workspace.onDidChangeTextDocument((e) => {
|
||||
const ed = vscode.window.activeTextEditor;
|
||||
if (ed && e.document === ed.document) this.scheduleRender(ed);
|
||||
}),
|
||||
// the four QuickPick-backed menu commands
|
||||
vscode.commands.registerCommand("cowriting.proposalAcceptMenu", (id?: string) => this.menu("accept", id)),
|
||||
vscode.commands.registerCommand("cowriting.proposalRejectMenu", (id?: string) => this.menu("reject", id)),
|
||||
@@ -88,20 +62,6 @@ export class EditorProposalController implements vscode.Disposable, vscode.CodeL
|
||||
);
|
||||
}
|
||||
|
||||
/** Debounce a committed-change re-render for `editor` (50 ms — lets rapid typing settle). */
|
||||
private scheduleRender(editor: vscode.TextEditor): void {
|
||||
const uri = editor.document.uri.toString();
|
||||
const prev = this.pendingRender.get(uri);
|
||||
if (prev !== undefined) clearTimeout(prev);
|
||||
this.pendingRender.set(
|
||||
uri,
|
||||
setTimeout(() => {
|
||||
this.pendingRender.delete(uri);
|
||||
this.renderEditor(editor);
|
||||
}, 50),
|
||||
);
|
||||
}
|
||||
|
||||
/** Apply any not-yet-applied proposals on the doc, then re-decorate + refresh lenses. */
|
||||
private async onProposalsChanged(uri: string): Promise<void> {
|
||||
const doc = vscode.workspace.textDocuments.find((d) => d.uri.toString() === uri);
|
||||
@@ -120,86 +80,29 @@ export class EditorProposalController implements vscode.Disposable, vscode.CodeL
|
||||
/** Decorate the editor for every applied proposal on its document (INV-52). */
|
||||
private renderEditor(editor: vscode.TextEditor): void {
|
||||
const doc = editor.document;
|
||||
const clearAll = () => {
|
||||
for (const a of ["human", "claude"] as const) editor.setDecorations(this.insDeco[a], []);
|
||||
for (const a of ["human", "claude", "none"] as const) editor.setDecorations(this.delDeco[a], []);
|
||||
};
|
||||
if (doc.languageId !== "markdown") return clearAll();
|
||||
if (doc.languageId !== "markdown") {
|
||||
editor.setDecorations(this.insertionDeco, []);
|
||||
editor.setDecorations(this.deletionDeco, []);
|
||||
return;
|
||||
}
|
||||
const key = this.proposals.keyFor(doc);
|
||||
const ins: Record<"human" | "claude", vscode.Range[]> = { human: [], claude: [] };
|
||||
const del: Record<"human" | "claude" | "none", vscode.DecorationOptions[]> = { human: [], claude: [], none: [] };
|
||||
// Pending proposals — always Claude (INV: proposals are agent-authored).
|
||||
const insertions: vscode.Range[] = [];
|
||||
const deletions: vscode.DecorationOptions[] = [];
|
||||
for (const v of this.proposals.listProposals(doc)) {
|
||||
if (v.anchorStart === null || v.original === undefined || !this.proposals.isApplied(key, v.id)) continue;
|
||||
const plan = decorationPlan(v.anchorStart, v.original, v.replacement);
|
||||
for (const i of plan.insertions) ins.claude.push(new vscode.Range(doc.positionAt(i.start), doc.positionAt(i.end)));
|
||||
for (const d of plan.deletions) {
|
||||
del.claude.push({
|
||||
range: new vscode.Range(doc.positionAt(d.at), doc.positionAt(d.at)),
|
||||
renderOptions: { after: { contentText: ` ${d.text} `, textDecoration: "line-through" } },
|
||||
});
|
||||
}
|
||||
}
|
||||
// Committed changes-since-baseline are added by decorateCommitted (pushes into ins/del[author]).
|
||||
this.decorateCommitted(editor, ins, del);
|
||||
for (const a of ["human", "claude"] as const) editor.setDecorations(this.insDeco[a], ins[a]);
|
||||
for (const a of ["human", "claude", "none"] as const) editor.setDecorations(this.delDeco[a], del[a]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decorates committed (non-proposal) changes-since-baseline by author (Task 7 / reverse INV-32).
|
||||
* Diffs current buffer against the F6 baseline; attributes each changed run to its author;
|
||||
* skips any hunk overlapping an applied pending proposal (the proposal loop owns those).
|
||||
* pin→clean: returns without marking when baseline.reason === "pinned".
|
||||
* Adjacency heuristic: a deletion in a hunk that has insertions inherits the hunk author;
|
||||
* a standalone deletion (hunk with no insertions) renders neutral ("none") — matching the
|
||||
* preview's cw-del-none treatment.
|
||||
*/
|
||||
private decorateCommitted(
|
||||
editor: vscode.TextEditor,
|
||||
ins: Record<"human" | "claude", vscode.Range[]>,
|
||||
del: Record<"human" | "claude" | "none", vscode.DecorationOptions[]>,
|
||||
): void {
|
||||
const doc = editor.document;
|
||||
const baseline = this.diffView.getBaseline(doc.uri.toString());
|
||||
// No baseline yet, or baseline was pinned (pin→clean: no committed marks, INV-48).
|
||||
if (!baseline || baseline.reason === "pinned") return;
|
||||
const current = doc.getText();
|
||||
// Nothing changed — short-circuit before the diff.
|
||||
if (current === baseline.text) return;
|
||||
const spans = this.attribution.spansFor(doc);
|
||||
const key = this.proposals.keyFor(doc);
|
||||
// Build the set of current-buffer ranges owned by applied pending proposals so we
|
||||
// can skip hunks that fall inside them — the proposal loop already decorates those.
|
||||
const appliedRanges: { start: number; end: number }[] = [];
|
||||
for (const v of this.proposals.listProposals(doc)) {
|
||||
if (v.anchorStart !== null && v.original !== undefined && this.proposals.isApplied(key, v.id)) {
|
||||
appliedRanges.push({ start: v.anchorStart, end: v.anchorStart + v.replacement.length });
|
||||
}
|
||||
}
|
||||
// wordEditHunks(current, baseline.text): start/end are in current coords; replacement is baseline text.
|
||||
const hunks = wordEditHunks(current, baseline.text);
|
||||
for (const h of hunks) {
|
||||
// Skip hunks whose current-buffer range overlaps an applied pending proposal.
|
||||
// The skip is whole-hunk and therefore conservative: a committed edit word-merged
|
||||
// into a proposal's hunk is skipped entirely — rare at word granularity.
|
||||
if (appliedRanges.some((r) => h.start < r.end && h.end > r.start)) continue;
|
||||
const author = authorAt(h.start, spans) ?? "human";
|
||||
// h.replacement = baseline text for this span; current.slice(h.start, h.end) = applied text.
|
||||
const plan = decorationPlan(h.start, h.replacement, current.slice(h.start, h.end));
|
||||
for (const i of plan.insertions) {
|
||||
ins[author].push(new vscode.Range(doc.positionAt(i.start), doc.positionAt(i.end)));
|
||||
}
|
||||
// Adjacency heuristic: a deletion paired with an insertion in THIS hunk inherits the
|
||||
// insertion author; a standalone deletion (no insertion in the hunk) is neutral.
|
||||
const delAuthor = plan.insertions.length > 0 ? author : "none";
|
||||
for (const d of plan.deletions) {
|
||||
del[delAuthor].push({
|
||||
range: new vscode.Range(doc.positionAt(d.at), doc.positionAt(d.at)),
|
||||
renderOptions: { after: { contentText: ` ${d.text} `, textDecoration: "line-through" } },
|
||||
for (const ins of plan.insertions) {
|
||||
insertions.push(new vscode.Range(doc.positionAt(ins.start), doc.positionAt(ins.end)));
|
||||
}
|
||||
for (const del of plan.deletions) {
|
||||
deletions.push({
|
||||
range: new vscode.Range(doc.positionAt(del.at), doc.positionAt(del.at)),
|
||||
renderOptions: { after: { contentText: ` ${del.text} `, textDecoration: "line-through" } },
|
||||
});
|
||||
}
|
||||
}
|
||||
editor.setDecorations(this.insertionDeco, insertions);
|
||||
editor.setDecorations(this.deletionDeco, deletions);
|
||||
}
|
||||
|
||||
/** CodeLensProvider: a `Accept ▾` / `Reject ▾` pair above each applied block. */
|
||||
@@ -243,8 +146,6 @@ export class EditorProposalController implements vscode.Disposable, vscode.CodeL
|
||||
dispose(): void {
|
||||
for (const t of this.pendingApply.values()) clearTimeout(t);
|
||||
this.pendingApply.clear();
|
||||
for (const t of this.pendingRender.values()) clearTimeout(t);
|
||||
this.pendingRender.clear();
|
||||
for (const d of this.disposables) d.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -119,7 +119,7 @@ export function activate(context: vscode.ExtensionContext): CowritingApi | undef
|
||||
|
||||
// --- F12 (#64): the editor surface — optimistic-apply proposals into the buffer,
|
||||
// decorate the diff, and provide Accept ▾/Reject ▾ CodeLens (INV-48/49/52/53). ---
|
||||
const editorProposalController = new EditorProposalController(proposalController, diffViewController, attributionController);
|
||||
const editorProposalController = new EditorProposalController(proposalController);
|
||||
context.subscriptions.push(editorProposalController);
|
||||
|
||||
// #46 (INV-42): accept every pending proposal on the active doc in one gesture
|
||||
|
||||
@@ -64,25 +64,6 @@ export async function runEditTurn(
|
||||
providerId: "claude-code",
|
||||
modelId,
|
||||
systemPrompt: SYSTEM_PROMPT,
|
||||
// The claude-code provider spawns the bundled `claude` CLI. On macOS, when
|
||||
// that process is launched from inside VS Code it performs IDE auto-connect,
|
||||
// which shells out to `osascript` (`tell application …`) to identify/activate
|
||||
// the editor — raising the macOS "control other applications" (Apple Events)
|
||||
// permission prompt (#59). We only consume the turn's text result and never
|
||||
// use the IDE connection, so we disable it: `CLAUDE_CODE_AUTO_CONNECT_IDE=0`
|
||||
// hard-returns out of the auto-connect path in the binary, and
|
||||
// `CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL=1` skips the extension-install deep link.
|
||||
// Seeding with the full `process.env` keeps the default inheritance intact
|
||||
// (login under HOME, proxy/CA vars) — we only add the two switches. The
|
||||
// provider forwards `options.env` into the spawned child (verified end to end
|
||||
// through @cline/sdk → ai-sdk-provider-claude-code → @anthropic-ai/claude-agent-sdk).
|
||||
options: {
|
||||
env: {
|
||||
...process.env,
|
||||
CLAUDE_CODE_AUTO_CONNECT_IDE: "0",
|
||||
CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL: "1",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Stream reduced progress snapshots out (INV-44 additive) and wire cancellation
|
||||
|
||||
@@ -94,7 +94,6 @@ export class ProposalController implements vscode.Disposable {
|
||||
replaced: p.original ?? fp?.text ?? "",
|
||||
replacement: p.replacement,
|
||||
original: p.original,
|
||||
author: p.author?.kind === "agent" ? "claude" : "human",
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
+32
-142
@@ -474,76 +474,6 @@ function wordMergedMarkdown(beforeRaw: string, afterRaw: string): string {
|
||||
.join("");
|
||||
}
|
||||
|
||||
/** The author whose span covers `offset` (half-open [start,end)), or null. */
|
||||
export function authorAt(offset: number, spans: AuthorSpan[]): AuthorKind | null {
|
||||
for (const s of spans) if (offset >= s.start && offset < s.end) return s.author;
|
||||
return null;
|
||||
}
|
||||
|
||||
const insClass = (a: AuthorKind | null): string => `cw-ins-${a ?? "none"}`;
|
||||
const delClass = (a: AuthorKind | null): string => `cw-del-${a ?? "none"}`;
|
||||
|
||||
/**
|
||||
* Author-colored word diff for a changed PROSE block in the review.
|
||||
* `afterStart` is the landed-text offset of `afterRaw[0]` so an inserted run's
|
||||
* offset maps into `spans`. Insertions are colored by the author covering their
|
||||
* offset; deletions inherit the author of the insertion they are paired with in
|
||||
* the same contiguous change cluster (adjacency heuristic) — `cw-del-none` when a
|
||||
* cluster has no insertion. Pure, deterministic.
|
||||
*/
|
||||
export function wordDiffByAuthor(
|
||||
beforeRaw: string,
|
||||
afterRaw: string,
|
||||
afterStart: number,
|
||||
spans: AuthorSpan[],
|
||||
): string {
|
||||
const parts = diffWordsWithSpace(beforeRaw, afterRaw);
|
||||
// First pass: find each change cluster's insertion author (first added run).
|
||||
// A cluster is a maximal run of added/removed parts bounded by unchanged parts.
|
||||
let afterOff = afterStart;
|
||||
const clusterAuthor: (AuthorKind | null)[] = []; // per part index, the cluster's del author
|
||||
{
|
||||
let off = afterStart;
|
||||
let i = 0;
|
||||
while (i < parts.length) {
|
||||
const p = parts[i];
|
||||
if (!p.added && !p.removed) {
|
||||
clusterAuthor[i] = null;
|
||||
off += p.value.length;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
// a cluster: scan to its end, capturing the first added run's author
|
||||
let j = i;
|
||||
let author: AuthorKind | null = null;
|
||||
let scanOff = off;
|
||||
while (j < parts.length && (parts[j].added || parts[j].removed)) {
|
||||
if (parts[j].added && author === null) author = authorAt(scanOff, spans);
|
||||
if (parts[j].added) scanOff += parts[j].value.length;
|
||||
j++;
|
||||
}
|
||||
for (let k = i; k < j; k++) clusterAuthor[k] = author;
|
||||
off = scanOff;
|
||||
i = j;
|
||||
}
|
||||
}
|
||||
// Second pass: emit.
|
||||
const out: string[] = [];
|
||||
parts.forEach((p, i) => {
|
||||
if (p.added) {
|
||||
const a = authorAt(afterOff, spans);
|
||||
out.push(`<ins class="${insClass(a)}">${p.value}</ins>`);
|
||||
afterOff += p.value.length;
|
||||
} else if (p.removed) {
|
||||
out.push(`<del class="${delClass(clusterAuthor[i] ?? null)}">${p.value}</del>`);
|
||||
} else {
|
||||
out.push(p.value);
|
||||
afterOff += p.value.length;
|
||||
}
|
||||
});
|
||||
return out.join("");
|
||||
}
|
||||
|
||||
export interface RenderOptions {
|
||||
/** Per-block markdown→HTML renderer (test seam). Defaults to the bundled markdown-it. */
|
||||
render?: (src: string) => string;
|
||||
@@ -642,6 +572,15 @@ function isCloseSentinel(m: string): boolean {
|
||||
return m === SENT.claude.close || m === SENT.human.close;
|
||||
}
|
||||
|
||||
function authorBadge(authors: Set<AuthorKind>): { cls: string; label: string } | null {
|
||||
if (authors.size === 0) return null;
|
||||
if (authors.size > 1) return { cls: "cw-mixed", label: "mixed" };
|
||||
const only = [...authors][0];
|
||||
return only === "claude"
|
||||
? { cls: "cw-by-claude", label: "Claude" }
|
||||
: { cls: "cw-by-human", label: "You" };
|
||||
}
|
||||
|
||||
// Markdown emphasis / code delimiters whose RUNS must never be split by an
|
||||
// injected sentinel — a sentinel between two run chars (e.g. `*|*`) breaks
|
||||
// markdown-it's delimiter pairing (#33 CASE1).
|
||||
@@ -662,38 +601,11 @@ function clampOffDelimiterRun(raw: string, at: number): number {
|
||||
return p;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the offset within `raw` after block-level markdown markers (ATX
|
||||
* headings, list markers, blockquote markers). Open sentinels must not be
|
||||
* injected before these markers — a PUA char at position 0 would prevent
|
||||
* markdown-it from recognising the block construct (e.g. `##` is only a
|
||||
* heading marker when it is the very first char on the line).
|
||||
*/
|
||||
function blockContentStart(raw: string): number {
|
||||
// ATX headings: "#{1,6} " at the start of the line.
|
||||
const heading = raw.match(/^#{1,6} /);
|
||||
if (heading) return heading[0].length;
|
||||
// Unordered list markers: "- ", "* ", "+ ".
|
||||
const ul = raw.match(/^[-*+] /);
|
||||
if (ul) return ul[0].length;
|
||||
// Ordered list markers: "N. " or "N) ".
|
||||
const ol = raw.match(/^\d+[.)]\s+/);
|
||||
if (ol) return ol[0].length;
|
||||
// Blockquotes: "> " or ">".
|
||||
const bq = raw.match(/^> ?/);
|
||||
if (bq) return bq[0].length;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Inject paired sentinels into a prose block's raw text for the spans clipped to it. */
|
||||
function injectSentinels(raw: string, blockStart: number, spans: AuthorSpan[]): string {
|
||||
const inserts: { at: number; marker: string }[] = [];
|
||||
// Open sentinels must not precede block-level markdown markers (heading/list/
|
||||
// blockquote syntax at position 0) — a PUA char before "## " prevents markdown-it
|
||||
// from recognising the heading. Clamp to the content-start offset.
|
||||
const minOpen = blockContentStart(raw);
|
||||
for (const s of spans) {
|
||||
const lo = Math.max(minOpen, clampOffDelimiterRun(raw, Math.max(0, s.start - blockStart)));
|
||||
const lo = clampOffDelimiterRun(raw, Math.max(0, s.start - blockStart));
|
||||
const hi = clampOffDelimiterRun(raw, Math.min(raw.length, s.end - blockStart));
|
||||
if (hi <= lo) continue; // empty (or clamped to empty) span contributes nothing
|
||||
inserts.push({ at: lo, marker: SENT[s.author].open });
|
||||
@@ -720,7 +632,7 @@ const ALL_SENTINELS = new RegExp(
|
||||
);
|
||||
|
||||
/**
|
||||
* #33: token-aware replacement of the rendered author sentinels with `cw-ins-*`
|
||||
* #33: token-aware replacement of the rendered author sentinels with `cw-by-*`
|
||||
* spans. A naive global string-replace (the old approach) could emit a span that
|
||||
* CROSSES an element boundary — `<span><strong>bo</span>ld</strong>` — when a
|
||||
* boundary fell inside an emphasis run (CASE3). This walks the rendered HTML and
|
||||
@@ -729,13 +641,13 @@ const ALL_SENTINELS = new RegExp(
|
||||
* (one `<span>` segment per text run). Tags are copied verbatim (with any stray
|
||||
* sentinel stripped, so no Private-Use-Area char ever leaks). Pure, deterministic.
|
||||
*/
|
||||
function sentinelsToSpans(html: string, kind: "by" | "ins" = "by"): string {
|
||||
function sentinelsToSpans(html: string): string {
|
||||
const out: string[] = [];
|
||||
let current: AuthorKind | null = null; // which author region we're inside
|
||||
let spanOpen = false; // whether a <span> is currently open in `out`
|
||||
const openSpan = () => {
|
||||
if (current && !spanOpen) {
|
||||
out.push(`<span class="cw-${kind}-${current}">`);
|
||||
out.push(`<span class="cw-by-${current}">`);
|
||||
spanOpen = true;
|
||||
}
|
||||
};
|
||||
@@ -783,11 +695,10 @@ export function colorByAuthor(
|
||||
blockStart: number,
|
||||
spans: AuthorSpan[],
|
||||
render: (src: string) => string,
|
||||
kind: "by" | "ins" = "by",
|
||||
): string {
|
||||
const overlapping = spans.filter((s) => s.end > blockStart && s.start < blockStart + raw.length);
|
||||
const injected = injectSentinels(raw, blockStart, overlapping);
|
||||
return sentinelsToSpans(render(injected), kind);
|
||||
return sentinelsToSpans(render(injected));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -828,8 +739,6 @@ export interface ProposalView {
|
||||
replacement: string;
|
||||
/** F12/#64 (INV-48): the pre-apply original, set after optimistic apply. */
|
||||
original?: string;
|
||||
/** Who made the proposal — colors the del/ins. Defaults to "claude". */
|
||||
author?: AuthorKind;
|
||||
}
|
||||
|
||||
function proposalBlockHtml(p: ProposalView, render: (src: string) => string): string {
|
||||
@@ -841,9 +750,8 @@ function proposalBlockHtml(p: ProposalView, render: (src: string) => string): st
|
||||
}
|
||||
};
|
||||
const unanchored = p.anchorStart === null ? " cw-proposal-unanchored" : "";
|
||||
const who = p.author ?? "claude";
|
||||
const before = p.replaced ? `<del class="cw-del-${who}">${safe(p.replaced)}</del>` : "";
|
||||
const after = `<ins class="cw-ins-${who}">${safe(p.replacement)}</ins>`;
|
||||
const before = p.replaced ? `<del class="cw-del">${safe(p.replaced)}</del>` : "";
|
||||
const after = `<ins class="cw-add">${safe(p.replacement)}</ins>`;
|
||||
const actions =
|
||||
`<span class="cw-actions">` +
|
||||
`<span class="cw-btngroup">` +
|
||||
@@ -861,27 +769,20 @@ function proposalBlockHtml(p: ProposalView, render: (src: string) => string): st
|
||||
function renderReviewOp(
|
||||
op: BlockOp,
|
||||
render: (src: string) => string,
|
||||
colored: (raw: string) => string,
|
||||
src: string,
|
||||
changedHtml?: string,
|
||||
): string {
|
||||
// A non-atomic changed prose block is pre-rendered with author-colored ins/del
|
||||
// (changedHtml). Removed blocks and atomic changed fences stay neutral via renderOp
|
||||
// (standalone deletion → neutral, per the adjacency heuristic). `src` is "" for a
|
||||
// removed block (no live source — INV-36).
|
||||
if (op.kind === "changed" && !op.atomic && changedHtml !== undefined) {
|
||||
return `<div class="cw-blk cw-changed"${src}>${changedHtml}</div>`;
|
||||
}
|
||||
// removed blocks and any changed block (atomic fences diffed whole; non-atomic prose
|
||||
// word-merged) render via renderOp — no author sentinels (deletions neutral, spec §6.7).
|
||||
// `src` is "" for a removed block (no live source — INV-36).
|
||||
if (op.kind === "removed" || op.kind === "changed") return renderOp(op, render, src);
|
||||
// "added": changedHtml is colorByAuthor sentinel output (markdown-safe, cw-ins-*).
|
||||
// "unchanged": render(raw) — plain, no author coloring (color = "changed since baseline").
|
||||
return `<div class="cw-blk ${op.kind === "added" ? "cw-added" : "cw-unchanged"}"${src}>${changedHtml ?? render(op.block.raw)}</div>`;
|
||||
return `<div class="cw-blk ${op.kind === "added" ? "cw-added" : "cw-unchanged"}"${src}>${colored(op.block.raw)}</div>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* On-state body: the F7 baseline diff — added/changed PROSE author-colored via
|
||||
* wordDiffByAuthor (cw-ins-{author}/cw-del-{author} per token), unchanged blocks render plain,
|
||||
* deletions struck neutral — overlaid with F4 pending proposals as blue cw-proposal
|
||||
* blocks (✓/✗). One pass, pure, vscode-free.
|
||||
* On-state body (INV-33): the F7 baseline diff — added/changed PROSE author-colored
|
||||
* via colorByAuthor (F9 sentinels), deletions struck — overlaid with F4 pending
|
||||
* proposals as blue cw-proposal blocks (✓/✗). One pass, pure, vscode-free.
|
||||
*
|
||||
* A resolved proposal renders INLINE, right after the current-side block its anchor
|
||||
* falls in (#31) — so "what is Claude proposing, and where?" is answered by
|
||||
@@ -932,9 +833,11 @@ export function renderReview(
|
||||
const ops = diffBlocks(baselineText, landedText);
|
||||
// #48: right after a PIN (baseline reason "pinned") with no changes since, the
|
||||
// panel is fully clean: no change marks (already absent) AND no authorship
|
||||
// coloring, so the pin reads as "this is my clean starting point". Suppress
|
||||
// wordDiffByAuthor for every block in this case; data-src mapping and any pending
|
||||
// proposals (review actions, not annotations) are kept below.
|
||||
// coloring, so the pin reads as "this is my clean starting point". Skip
|
||||
// colorByAuthor for every block in this case; data-src mapping and any pending
|
||||
// proposals (review actions, not annotations) are kept below. A baseline advanced
|
||||
// by a machine-landing (accept) is ALSO zero-diff but is NOT pinned — it keeps
|
||||
// its authorship coloring (F10 INV-33), so this is gated on the pin specifically.
|
||||
const clean = opts.pinned === true && ops.every((o) => o.kind === "unchanged");
|
||||
|
||||
// Map a currentText offset to its landedText offset (account for reverted spans
|
||||
@@ -986,22 +889,9 @@ export function renderReview(
|
||||
for (const op of ops) {
|
||||
const blockIndex = op.kind === "removed" ? -1 : ci;
|
||||
const blk = op.kind === "removed" ? undefined : ranges[ci++];
|
||||
// Only ADDED and CHANGED prose blocks are author-colored (they differ since baseline);
|
||||
// UNCHANGED blocks render plain (color means "changed since baseline").
|
||||
// A non-atomic changed prose block: author-colored word diff (ins by author,
|
||||
// del by adjacency). An added block: sentinel-safe colorByAuthor with kind="ins"
|
||||
// (markdown-it parses the block first, so ## → <h2> before sentinels become spans;
|
||||
// the old wordDiffByAuthor path wrapped raw in <ins> BEFORE parsing — structural bug).
|
||||
// `blk.start` is the landed offset of the after-side text.
|
||||
const changedHtml =
|
||||
blk && !clean
|
||||
? op.kind === "changed" && !op.atomic
|
||||
? render(wordDiffByAuthor(op.before.raw, op.block.raw, blk.start, landedSpans))
|
||||
: op.kind === "added"
|
||||
? colorByAuthor(op.block.raw, blk.start, landedSpans, render, "ins")
|
||||
: undefined
|
||||
: undefined;
|
||||
bodyParts.push(renderReviewOp(op, render, srcAttr(blk), changedHtml));
|
||||
const colored = (raw: string): string =>
|
||||
blk && !clean ? colorByAuthor(raw, blk.start, landedSpans, render) : render(raw);
|
||||
bodyParts.push(renderReviewOp(op, render, colored, srcAttr(blk)));
|
||||
const here = blockIndex >= 0 ? byBlock.get(blockIndex) : undefined;
|
||||
if (here) for (const p of here) bodyParts.push(proposalBlockHtml(p, render));
|
||||
}
|
||||
|
||||
@@ -16,16 +16,15 @@ async function getApi(): Promise<CowritingApi> {
|
||||
|
||||
// F10 host E2E (no LLM): the rewrite of the obsolete F9 authorship-mode test.
|
||||
// F9's "authorship" mode / renderAuthorship is gone — the on-state renderReview
|
||||
// now author-colors Claude's PENDING proposal blocks as cw-ins-claude. After the
|
||||
// proposal is accepted the baseline advances (INV-18/F12) and the text becomes
|
||||
// "unchanged" → renders plain. The class to check is cw-ins-claude (proposal block),
|
||||
// NOT cw-by-claude (the old F9 authorship render). Owns its own markdown doc.
|
||||
suite("F10 review preview — pending Claude proposal renders cw-ins-claude in the on-state (host E2E, no LLM)", () => {
|
||||
// now author-colors Claude's landed prose. This suite confirms a Claude-landed
|
||||
// span renders as a cw-by-claude span in the on-state preview HTML. Owns its own
|
||||
// markdown doc, disjoint from the other suites' fixtures.
|
||||
suite("F10 review preview — Claude-authored prose is cw-by-claude in the on-state (host E2E, no LLM)", () => {
|
||||
const DOC_REL = "docs/f10claude.md";
|
||||
const TARGET = "The sentence Claude will compose over.";
|
||||
const REPLACEMENT = "The sentence CLAUDE COMPOSED via the seam.";
|
||||
|
||||
test("a pending Claude proposal carries cw-ins-claude; accepted proposal leaves attribution data intact; mode defaults to on", async () => {
|
||||
test("an accepted Claude edit author-colors as cw-by-claude in the on-state render; mode defaults to on", async () => {
|
||||
const abs = path.join(WS, DOC_REL);
|
||||
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
||||
fs.writeFileSync(abs, `# F10\n\n${TARGET}\n`, "utf8");
|
||||
@@ -42,7 +41,7 @@ suite("F10 review preview — pending Claude proposal renders cw-ins-claude in t
|
||||
assert.ok(api.trackChangesPreviewController.isOpen(key), "preview open");
|
||||
assert.strictEqual(api.trackChangesPreviewController.getMode(key), "on", "annotations default to on");
|
||||
|
||||
// Claude proposes via the seam (F12 optimistic-apply; proposal stays PENDING)
|
||||
// Claude composes via the seam (propose → accept)
|
||||
const start = doc.getText().indexOf(TARGET);
|
||||
const id = await vscode.commands.executeCommand<string>("cowriting.proposeAgentEdit", {
|
||||
uri: key,
|
||||
@@ -53,26 +52,17 @@ suite("F10 review preview — pending Claude proposal renders cw-ins-claude in t
|
||||
sessionId: "e2e-f10",
|
||||
turnId: "turn-f10",
|
||||
});
|
||||
assert.ok(id, "propose returns an id");
|
||||
await settle();
|
||||
|
||||
// PENDING proposal: the preview renders the proposal block with cw-ins-claude.
|
||||
// After accepting, the baseline advances (INV-18) → the text becomes "unchanged"
|
||||
// and renders plain — so we check BEFORE accepting.
|
||||
const pendingHtml = api.trackChangesPreviewController.renderHtmlFor(key);
|
||||
assert.ok(
|
||||
pendingHtml.includes("cw-ins-claude"),
|
||||
"pending Claude proposal block carries cw-ins-claude in the on-state render",
|
||||
);
|
||||
|
||||
// accept via the seam — baseline advances (machine-landing, INV-18/F12)
|
||||
assert.ok(await api.proposalController.acceptById(DOC_REL, id!), "accept applies via the seam");
|
||||
await settle();
|
||||
|
||||
// attribution recorded a Claude (agent) span (data layer intact)
|
||||
const claudeSpan = api.attributionController.getSpans(DOC_REL).find((s) => s.authorKind === "agent");
|
||||
assert.ok(claudeSpan, "Claude span recorded by F3 (data layer intact after accept)");
|
||||
assert.ok(claudeSpan, "Claude span recorded by F3");
|
||||
const spans = api.attributionController.spansFor(doc);
|
||||
assert.ok(spans.some((s) => s.author === "claude"), "spansFor reports a Claude span for the preview");
|
||||
|
||||
// the on-state render author-colors the landed Claude text as cw-by-claude
|
||||
const html = api.trackChangesPreviewController.renderHtmlFor(key);
|
||||
assert.match(html, /<span class="cw-by-claude">/, "landed Claude prose is author-colored in the on-state render");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -74,7 +74,7 @@ suite("F10 interactive review (host E2E — preview is the single review surface
|
||||
void doc;
|
||||
});
|
||||
|
||||
test("typing produces an added/changed block and a cw-ins-human span in the on-state render (PUC-2)", async () => {
|
||||
test("typing produces an added/changed block and a cw-by-human span in the on-state render (PUC-2)", async () => {
|
||||
const { key } = await reopen(DOC_REL);
|
||||
const api = await getApi();
|
||||
const doc = byKey(key)!;
|
||||
@@ -85,13 +85,13 @@ suite("F10 interactive review (host E2E — preview is the single review surface
|
||||
const kinds = (api.trackChangesPreviewController.getLastModel(key) ?? []).map((o) => o.kind);
|
||||
assert.ok(kinds.some((k) => k === "added" || k === "changed"), "an added/changed block after typing");
|
||||
// Attribution recorded the human span (data layer), and the on-state render
|
||||
// author-colors that prose as cw-ins-human (added blocks use cw-ins-{author} since Task 3/44ef0a2).
|
||||
// author-colors that prose as cw-by-human.
|
||||
assert.ok(
|
||||
api.attributionController.spansFor(doc).some((s) => s.author === "human"),
|
||||
"a human span was recorded for the typed text",
|
||||
);
|
||||
const html = api.trackChangesPreviewController.renderHtmlFor(key);
|
||||
assert.ok(html.includes("cw-ins-human"), "typed text is author-colored human in the on-state (cw-ins-human for added blocks)");
|
||||
assert.match(html, /<span class="cw-by-human">/, "typed text is author-colored human in the on-state");
|
||||
});
|
||||
|
||||
test("propose → the preview surfaces it as a cw-proposal block with ✓/✗ actions (PUC-3)", async () => {
|
||||
@@ -175,7 +175,7 @@ suite("F10 interactive review (host E2E — preview is the single review surface
|
||||
// (INV-33). Assert the actual off-state body the controller posts has no cw-
|
||||
// author/proposal marks — meaningful because the on-state above DID carry one.
|
||||
const offBody = renderPlain(doc.getText());
|
||||
assert.ok(!/cw-proposal|cw-by-|cw-ins-|cw-del/.test(offBody), "off-state render carries no cw- marks");
|
||||
assert.ok(!/cw-proposal|cw-by-claude|cw-by-human|cw-del/.test(offBody), "off-state render carries no cw- marks");
|
||||
|
||||
// toggle back on → marks return.
|
||||
api.trackChangesPreviewController.setMode(key, "on");
|
||||
@@ -232,60 +232,6 @@ suite("F10 interactive review (host E2E — preview is the single review surface
|
||||
assert.ok(all.includes("cowriting.pinDiffBaseline"), "pinDiffBaseline (baseline data layer) is kept");
|
||||
void key;
|
||||
});
|
||||
|
||||
test("author-colored track changes: cw-ins-human + cw-ins-claude appear; unchanged blocks are plain (Tasks 1-4)", async () => {
|
||||
// Fresh doc with three blocks: one that stays unchanged, one for Claude to target, one for human typing.
|
||||
const { doc, key } = await freshDoc(
|
||||
"docs/f10authorcolors.md",
|
||||
"# Author Colors\n\nUnchanged paragraph that stays.\n\nClaude target block.\n",
|
||||
);
|
||||
const api = await getApi();
|
||||
await vscode.commands.executeCommand("cowriting.showTrackChangesPreview");
|
||||
await settle();
|
||||
|
||||
// Human types a new paragraph → an "added" block relative to the opened baseline.
|
||||
const edit = new vscode.WorkspaceEdit();
|
||||
edit.insert(doc.uri, doc.positionAt(doc.getText().length), "\n\nHuman typed paragraph.\n");
|
||||
assert.ok(await vscode.workspace.applyEdit(edit), "human edit applied");
|
||||
await settle();
|
||||
|
||||
// Propose a Claude change (stays PENDING — F12 optimistic-apply; NOT accepted).
|
||||
// The proposal block renders with cw-ins-claude.
|
||||
const target = "Claude target block.";
|
||||
const targetStart = doc.getText().indexOf(target);
|
||||
assert.ok(targetStart >= 0, "target text present after human edit");
|
||||
await vscode.commands.executeCommand<string>("cowriting.proposeAgentEdit", {
|
||||
uri: key,
|
||||
start: targetStart,
|
||||
end: targetStart + target.length,
|
||||
newText: "Claude replacement block.",
|
||||
model: "sonnet",
|
||||
sessionId: "e2e-f10-colors",
|
||||
turnId: "turn-colors-1",
|
||||
});
|
||||
await settle();
|
||||
|
||||
const html = api.trackChangesPreviewController.renderHtmlFor(key);
|
||||
|
||||
// The human-typed added block renders with cw-ins-human.
|
||||
assert.ok(html.includes("cw-ins-human"), "human added block is colored cw-ins-human");
|
||||
|
||||
// The pending Claude proposal block renders with cw-ins-claude.
|
||||
assert.ok(html.includes("cw-ins-claude"), "pending Claude proposal block carries cw-ins-claude");
|
||||
|
||||
// The unchanged block renders as cw-unchanged with no cw-ins-/cw-by- inside it
|
||||
// (color = "changed since baseline"; unchanged text is never annotated).
|
||||
const unchangedBlocks = [...html.matchAll(/<div class="cw-blk cw-unchanged"[^>]*>([\s\S]*?)<\/div>/g)];
|
||||
assert.ok(unchangedBlocks.length > 0, "at least one unchanged block exists");
|
||||
assert.ok(
|
||||
unchangedBlocks.some((m) => m[1].includes("Unchanged paragraph that stays")),
|
||||
"the unchanged paragraph is in a cw-unchanged block",
|
||||
);
|
||||
assert.ok(
|
||||
unchangedBlocks.every((m) => !/cw-ins-|cw-by-/.test(m[1])),
|
||||
"unchanged blocks carry no cw-ins- or cw-by- classes",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ---- helpers reused across the order-dependent main-flow tests ----
|
||||
|
||||
@@ -41,15 +41,15 @@ suite("S48 — pin → fully clean review panel (host E2E, no LLM)", () => {
|
||||
edit.insert(doc.uri, doc.positionAt(doc.getText().length), "\n\nA freshly typed human paragraph.\n");
|
||||
assert.ok(await vscode.workspace.applyEdit(edit), "operator edit applied");
|
||||
await settle();
|
||||
assert.match(ctl.renderHtmlFor(key), /cw-ins-human/, "typed text is author-colored cw-ins-human before the pin");
|
||||
assert.match(ctl.renderHtmlFor(key), /cw-by-human/, "typed text is author-colored before the pin");
|
||||
|
||||
// Pin the baseline → zero diff → the panel must be fully clean.
|
||||
ctl.receiveMessage(key, { type: "pinBaseline" });
|
||||
await settle();
|
||||
const pinned = ctl.renderHtmlFor(key);
|
||||
assert.ok(!pinned.includes("cw-ins-human"), "no human insertion marks after pin");
|
||||
assert.ok(!pinned.includes("cw-ins-claude"), "no Claude insertion marks after pin");
|
||||
assert.ok(!pinned.includes("cw-ins-") && !pinned.includes("cw-del-"), "no insertion or deletion marks after pin");
|
||||
assert.ok(!pinned.includes("cw-by-human"), "no human authorship coloring after pin");
|
||||
assert.ok(!pinned.includes("cw-by-claude"), "no Claude authorship coloring after pin");
|
||||
assert.ok(!pinned.includes("cw-add") && !pinned.includes("cw-del"), "no change marks after pin");
|
||||
assert.match(pinned, /data-src-start/, "blocks still carry data-src offsets (INV-36 mapping kept)");
|
||||
assert.ok(pinned.includes("freshly typed human paragraph"), "the body text is still rendered, just plain");
|
||||
|
||||
@@ -58,6 +58,6 @@ suite("S48 — pin → fully clean review panel (host E2E, no LLM)", () => {
|
||||
edit2.insert(doc.uri, doc.positionAt(doc.getText().length), "\n\nA second typed paragraph diverges again.\n");
|
||||
assert.ok(await vscode.workspace.applyEdit(edit2), "second operator edit applied");
|
||||
await settle();
|
||||
assert.match(ctl.renderHtmlFor(key), /cw-ins-human/, "cw-ins-human authorship coloring returns once the doc diverges from the pin");
|
||||
assert.match(ctl.renderHtmlFor(key), /cw-by-human/, "authorship coloring returns once the doc diverges from the pin");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -78,9 +78,8 @@ suite("F10 #38 — undo does not mis-attribute restored text (host E2E, no LLM)"
|
||||
);
|
||||
|
||||
// And the on-state render must not color 'bravo' as human-authored.
|
||||
// Added blocks use cw-ins-human (not cw-by-human) since Task 3/44ef0a2.
|
||||
const html = api.trackChangesPreviewController.renderHtmlFor(key);
|
||||
const bravoColoredHuman = /cw-ins-human[^<]*bravo|<[^>]+class="[^"]*cw-ins-human[^"]*"[^>]*>[^<]*bravo/.test(html);
|
||||
assert.ok(!bravoColoredHuman, "restored 'bravo' is not colored cw-ins-human in the preview");
|
||||
const bravoColoredHuman = /<span class="cw-by-human">[^<]*bravo/.test(html);
|
||||
assert.ok(!bravoColoredHuman, "restored 'bravo' is not colored cw-by-human in the preview");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -52,44 +52,6 @@ describe("extractReplacement", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("runEditTurn macOS automation prompt (#59)", () => {
|
||||
// The claude-code provider spawns the bundled `claude` CLI, which on macOS
|
||||
// performs IDE auto-connect when launched inside VS Code — sending Apple Events
|
||||
// that raise the "control other applications" prompt. The extension only
|
||||
// consumes the text result and never needs that connection, so we disable it.
|
||||
it("spawns the agent with IDE auto-connect + auto-install disabled, preserving the rest of the environment", async () => {
|
||||
vi.resetModules();
|
||||
const cfgs: any[] = [];
|
||||
vi.doMock("@cline/sdk", () => ({
|
||||
Agent: class {
|
||||
constructor(cfg: any) {
|
||||
cfgs.push(cfg);
|
||||
}
|
||||
subscribe() {
|
||||
return () => {};
|
||||
}
|
||||
abort() {}
|
||||
async run() {
|
||||
return { status: "completed", outputText: "X", runId: "r" };
|
||||
}
|
||||
},
|
||||
}));
|
||||
process.env.__WGL_TEST_SENTINEL__ = "keep-me";
|
||||
await runEditTurn("do it", "old");
|
||||
const cfg = cfgs[0];
|
||||
// mK("0") === true in the claude binary → hard-disables IDE auto-connect,
|
||||
// so no osascript / Apple Event fires.
|
||||
expect(cfg.options?.env?.CLAUDE_CODE_AUTO_CONNECT_IDE).toBe("0");
|
||||
// Belt-and-suspenders: skip the IDE-extension auto-install (deep-link path).
|
||||
expect(cfg.options?.env?.CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL).toBe("1");
|
||||
// The full process environment must survive (login under HOME, proxy/CA vars).
|
||||
expect(cfg.options?.env?.__WGL_TEST_SENTINEL__).toBe("keep-me");
|
||||
delete process.env.__WGL_TEST_SENTINEL__;
|
||||
vi.doUnmock("@cline/sdk");
|
||||
vi.resetModules();
|
||||
});
|
||||
});
|
||||
|
||||
describe("runEditTurn progress + cancel", () => {
|
||||
it("emits progress snapshots and returns the replacement unchanged (INV-44)", async () => {
|
||||
vi.resetModules();
|
||||
|
||||
+41
-178
@@ -1,7 +1,5 @@
|
||||
import { describe, it, test, expect } from "vitest";
|
||||
import MarkdownIt from "markdown-it";
|
||||
import { splitBlocks, splitBlocksWithRanges, diffBlocks, diffToHunks, diffToBlockHunks, renderTrackChanges, colorByAuthor, authorAt, wordDiffByAuthor, type AuthorSpan } from "../src/trackChangesModel";
|
||||
const md = new MarkdownIt({ html: true, linkify: false, breaks: false });
|
||||
import { splitBlocks, splitBlocksWithRanges, diffBlocks, diffToHunks, diffToBlockHunks, renderTrackChanges, colorByAuthor, type AuthorSpan } from "../src/trackChangesModel";
|
||||
|
||||
describe("splitBlocks", () => {
|
||||
it("splits prose paragraphs on blank lines, dropping empties", () => {
|
||||
@@ -172,11 +170,12 @@ describe("colorByAuthor", () => {
|
||||
});
|
||||
|
||||
// #33: author-coloring must be sentinel-safe around markdown emphasis. These
|
||||
// exercise colorByAuthor directly with the real markdown-it renderer (unchanged
|
||||
// blocks now render plain in renderReview, so sentinel testing requires a direct call).
|
||||
// exercise the REAL markdown-it renderer (via renderReview on an unchanged doc),
|
||||
// since the failure is in markdown-it's inline parsing / element nesting.
|
||||
// CASE1 — a span boundary strictly inside a delimiter run must not split it.
|
||||
test("#33 CASE1: a span boundary inside ** does not break emphasis parsing", () => {
|
||||
const html = colorByAuthor("a**b**c", 0, [{ start: 0, end: 2, author: "human" }], src => md.render(src));
|
||||
const doc = "a**b**c";
|
||||
const html = renderReview(doc, doc, [{ start: 0, end: 2, author: "human" }], []);
|
||||
expect(html).toContain("<strong>b</strong>"); // emphasis still renders
|
||||
expect(html).not.toContain("**"); // no raw delimiters left
|
||||
expect(html).not.toContain("<em></em>"); // no stray empty emphasis (the parse-break symptom)
|
||||
@@ -185,14 +184,16 @@ describe("colorByAuthor", () => {
|
||||
// CASE3 — a span boundary inside an emphasis run must color the text without
|
||||
// misnesting span/element (the span is split at the element boundary).
|
||||
test("#33 CASE3: a span boundary inside **bold** colors the text without misnesting", () => {
|
||||
const html = colorByAuthor("**bold**", 0, [{ start: 0, end: 4, author: "human" }], src => md.render(src)); // covers "**bo"
|
||||
const doc = "**bold**";
|
||||
const html = renderReview(doc, doc, [{ start: 0, end: 4, author: "human" }], []); // covers "**bo"
|
||||
expect(html).toContain("<strong>");
|
||||
expect(html).toContain('<span class="cw-by-human">bo</span>ld</strong>'); // span INSIDE strong, closed before "ld"
|
||||
expect(html).not.toContain('cw-by-human"><strong>'); // NOT the old misnest (span wrapping the <strong> open)
|
||||
});
|
||||
// CASE2 — a span covering a whole emphasis run stays correct (regression).
|
||||
test("#33 CASE2: a span over the whole **bold** colors it correctly", () => {
|
||||
const html = colorByAuthor("**bold**", 0, [{ start: 0, end: 8, author: "human" }], src => md.render(src));
|
||||
const doc = "**bold**";
|
||||
const html = renderReview(doc, doc, [{ start: 0, end: 8, author: "human" }], []);
|
||||
expect(html).toContain("<strong>");
|
||||
expect((html.match(/cw-by-human/g) ?? []).length).toBe(1);
|
||||
expect(html).toContain("bold");
|
||||
@@ -208,98 +209,7 @@ describe("colorByAuthor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("authorAt", () => {
|
||||
const spans: AuthorSpan[] = [
|
||||
{ start: 0, end: 5, author: "human" },
|
||||
{ start: 5, end: 10, author: "claude" },
|
||||
];
|
||||
test("returns the covering span's author (half-open)", () => {
|
||||
expect(authorAt(0, spans)).toBe("human");
|
||||
expect(authorAt(4, spans)).toBe("human");
|
||||
expect(authorAt(5, spans)).toBe("claude");
|
||||
expect(authorAt(9, spans)).toBe("claude");
|
||||
});
|
||||
test("returns null outside any span", () => {
|
||||
expect(authorAt(10, spans)).toBeNull();
|
||||
expect(authorAt(-1, spans)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("wordDiffByAuthor", () => {
|
||||
test("an inserted run is colored by the author covering its landed offset", () => {
|
||||
// before "hello " ; after "hello brave " ; "brave " inserted at landed offset 6..12
|
||||
const spans: AuthorSpan[] = [{ start: 6, end: 12, author: "claude" }];
|
||||
const html = wordDiffByAuthor("hello ", "hello brave ", 0, spans);
|
||||
expect(html).toContain('<ins class="cw-ins-claude">brave </ins>');
|
||||
expect(html).toContain("hello ");
|
||||
});
|
||||
test("a paired deletion inherits the paired insertion's author (adjacency)", () => {
|
||||
// "light" -> "dark", both in one cluster; "dark" is claude-inserted
|
||||
const spans: AuthorSpan[] = [{ start: 0, end: 4, author: "claude" }];
|
||||
const html = wordDiffByAuthor("light", "dark", 0, spans);
|
||||
expect(html).toContain('<del class="cw-del-claude">light</del>');
|
||||
expect(html).toContain('<ins class="cw-ins-claude">dark</ins>');
|
||||
});
|
||||
test("a standalone deletion (no paired insertion) is neutral", () => {
|
||||
const html = wordDiffByAuthor("keep this word", "keep word", 0, []);
|
||||
expect(html).toContain('<del class="cw-del-none">this </del>');
|
||||
expect(html).not.toContain("cw-del-human");
|
||||
expect(html).not.toContain("cw-del-claude");
|
||||
});
|
||||
test("emits SIBLING ins/del elements, never nested — CSS overlap rule in preview.css is a defensive forward guarantee", () => {
|
||||
// The engine assigns the cluster's insertion author to all deletions in the same
|
||||
// cluster (adjacency heuristic), so <del> and <ins> always carry the SAME author
|
||||
// as siblings. Cross-author nesting (<del class="cw-del-X"><ins class="cw-ins-Y">)
|
||||
// is never produced today. The CSS rule `.cw-del-claude .cw-ins-human { text-decoration: inherit }`
|
||||
// guards against a future regression where such nesting appears.
|
||||
const spans: AuthorSpan[] = [{ start: 0, end: 100, author: "human" }];
|
||||
const html = wordDiffByAuthor("old text", "new text", 0, spans);
|
||||
expect(html).toContain('<del class="cw-del-human">');
|
||||
expect(html).toContain('<ins class="cw-ins-human">');
|
||||
// Structural check: no <del> immediately wraps an <ins> (sibling, not nested).
|
||||
// /<del[^>]*>[^<]*<ins/ would match a nested case but not a sibling case
|
||||
// because [^<]* stops before the closing </del> tag.
|
||||
expect(html).not.toMatch(/<del[^>]*>[^<]*<ins/);
|
||||
});
|
||||
});
|
||||
|
||||
import { renderPlain, wordEditHunks, decorationPlan } from "../src/trackChangesModel";
|
||||
|
||||
test("committed change: wordEditHunks(current, baseline) → start/end index current; replacement is baseline text", () => {
|
||||
const baseline = "the light mode";
|
||||
const current = "the dark mode";
|
||||
const [h] = wordEditHunks(current, baseline);
|
||||
expect(current.slice(h.start, h.end)).toContain("dark"); // applied (current) side
|
||||
expect(h.replacement).toContain("light"); // baseline (deleted) side
|
||||
const plan = decorationPlan(h.start, h.replacement, current.slice(h.start, h.end));
|
||||
expect(plan.insertions.length).toBeGreaterThan(0);
|
||||
expect(plan.deletions.some((d) => d.text.includes("light"))).toBe(true);
|
||||
});
|
||||
|
||||
test("committed change with NO shared prefix: current offsets + deleted text both correct", () => {
|
||||
const baseline = "alpha tail";
|
||||
const current = "beta tail";
|
||||
const [h] = wordEditHunks(current, baseline);
|
||||
expect(h.start).toBe(0);
|
||||
expect(current.slice(h.start, h.end)).toContain("beta"); // applied
|
||||
const plan = decorationPlan(h.start, h.replacement, current.slice(h.start, h.end));
|
||||
expect(plan.deletions.some((d) => d.text.includes("alpha"))).toBe(true); // deletion not lost
|
||||
});
|
||||
|
||||
test("standalone committed deletion → plan has no insertions (controller routes del to neutral)", () => {
|
||||
// current = "keep word" (baseline had "this " between "keep " and "word" — standalone deletion)
|
||||
const [h] = wordEditHunks("keep word", "keep this word");
|
||||
const plan = decorationPlan(h.start, h.replacement, "keep word".slice(h.start, h.end));
|
||||
expect(plan.insertions.length).toBe(0);
|
||||
expect(plan.deletions.some((d) => d.text.includes("this"))).toBe(true);
|
||||
});
|
||||
|
||||
test("paired committed replace → plan has insertions (deletion inherits author, not neutral)", () => {
|
||||
// current = "the dark mode", baseline = "the light mode" — replacement, so paired
|
||||
const [h] = wordEditHunks("the dark mode", "the light mode");
|
||||
const plan = decorationPlan(h.start, h.replacement, "the dark mode".slice(h.start, h.end));
|
||||
expect(plan.insertions.length).toBeGreaterThan(0);
|
||||
});
|
||||
import { renderPlain } from "../src/trackChangesModel";
|
||||
|
||||
describe("renderPlain", () => {
|
||||
test("renderPlain renders current buffer as plain markdown (no marks)", () => {
|
||||
@@ -313,15 +223,13 @@ describe("renderPlain", () => {
|
||||
import { renderReview, type ProposalView } from "../src/trackChangesModel";
|
||||
|
||||
describe("renderReview", () => {
|
||||
test("renderReview: human addition since baseline renders author-colored ins", () => {
|
||||
// " world" is one diff token starting at offset 5 (the space), so the author span
|
||||
// must start at 5 or earlier to cover the token's start offset.
|
||||
const html = renderReview("hello", "hello world", [{ start: 5, end: 11, author: "human" }], []);
|
||||
expect(html).toContain("cw-ins-human");
|
||||
test("renderReview: human addition since baseline renders green ins / cw-by-human", () => {
|
||||
const html = renderReview("hello", "hello world", [{ start: 6, end: 11, author: "human" }], []);
|
||||
expect(html).toMatch(/<ins>[^<]*world[^<]*<\/ins>|cw-by-human/);
|
||||
});
|
||||
test("renderReview: a standalone deletion since baseline renders neutral struck del", () => {
|
||||
test("renderReview: deletion since baseline renders struck del/cw-del", () => {
|
||||
const html = renderReview("hello world", "hello", [], []);
|
||||
expect(html).toMatch(/cw-del-none|cw-removed/);
|
||||
expect(html).toMatch(/<del>|cw-del/);
|
||||
});
|
||||
test("renderReview: a pending proposal renders a blue block with data-proposal-id and Accept/Reject actions", () => {
|
||||
const proposals: ProposalView[] = [{ id: "p1", anchorStart: 0, anchorEnd: 5, replaced: "hello", replacement: "goodbye" }];
|
||||
@@ -353,15 +261,13 @@ describe("renderReview", () => {
|
||||
test("renderReview: author-colors the correct block when two paragraphs are identical", () => {
|
||||
// Two identical paragraphs; baseline has only the first, so the SECOND is an
|
||||
// added block authored by human. Its span must color THAT block, not the first.
|
||||
// (Unchanged first block renders plain; added second block uses wordDiffByAuthor.)
|
||||
const baseline = "Hello world";
|
||||
const current = "Hello world\n\nHello world";
|
||||
// second "Hello world" starts at offset 13 (past the "\n\n"); span covers the block.
|
||||
// wordDiffByAuthor emits the whole block as one added token at offset 13.
|
||||
const spans = [{ start: 13, end: 24, author: "human" as const }];
|
||||
// second "Hello world" starts at offset 13; "world" at 19..24
|
||||
const spans = [{ start: 19, end: 24, author: "human" as const }];
|
||||
const html = renderReview(baseline, current, spans, []);
|
||||
// exactly one cw-ins-human (the added second block), not zero, not on the first.
|
||||
const count = (html.match(/cw-ins-human/g) ?? []).length;
|
||||
// exactly one cw-by-human span (the added second block's "world"), not zero, not on the first.
|
||||
const count = (html.match(/cw-by-human/g) ?? []).length;
|
||||
expect(count).toBe(1);
|
||||
});
|
||||
|
||||
@@ -440,24 +346,22 @@ describe("renderReview", () => {
|
||||
expect(html).toContain('data-proposal-id="p1"'); // proposal still shows (it is an action)
|
||||
expect(html).toContain("Person");
|
||||
});
|
||||
test("renderReview: zero diff (e.g. machine-landing accept) renders unchanged blocks plain (Task 2 behavior)", () => {
|
||||
// Task 2: unchanged blocks always render plain — color means "changed since baseline".
|
||||
// After accepting a Claude edit the text is the new baseline; no diff → no coloring.
|
||||
test("renderReview: zero diff WITHOUT a pin (e.g. machine-landing) keeps authorship coloring (INV-33)", () => {
|
||||
// accepting a Claude edit advances the baseline (zero diff) but is NOT a pin —
|
||||
// the landed author coloring must remain.
|
||||
const doc = "Human wrote this.\n\nClaude wrote that.";
|
||||
const spans: AuthorSpan[] = [{ start: 19, end: doc.length, author: "claude" }];
|
||||
const html = renderReview(doc, doc, spans, []); // no pinned flag
|
||||
expect(html).not.toContain("cw-by-claude");
|
||||
expect(html).toContain("Claude wrote that."); // text still present
|
||||
expect(html).toContain("cw-by-claude");
|
||||
});
|
||||
test("renderReview: with REAL changes since a pin, author coloring returns on added blocks", () => {
|
||||
test("renderReview: with REAL changes since a pin, author coloring returns", () => {
|
||||
// a genuine added block is still author-colored even when pinned (only the
|
||||
// zero-diff-after-pin state is clean). Task 2: coloring is via cw-ins-*.
|
||||
// zero-diff-after-pin state is clean).
|
||||
const baseline = "Hello world";
|
||||
const current = "Hello world\n\nHello world";
|
||||
// span covers the added block from its start (offset 13) so the whole token is colored.
|
||||
const spans: AuthorSpan[] = [{ start: 13, end: 24, author: "human" }];
|
||||
const spans: AuthorSpan[] = [{ start: 19, end: 24, author: "human" }];
|
||||
const html = renderReview(baseline, current, spans, [], { pinned: true });
|
||||
expect((html.match(/cw-ins-human/g) ?? []).length).toBe(1);
|
||||
expect((html.match(/cw-by-human/g) ?? []).length).toBe(1);
|
||||
});
|
||||
|
||||
test("renderReview is deterministic with mixed anchored/unanchored proposals", () => {
|
||||
@@ -489,26 +393,24 @@ describe("renderReview", () => {
|
||||
expect(html).not.toContain("<del>brown</del>"); // no double-render of the change as a baseline diff
|
||||
});
|
||||
|
||||
test("renderReview keeps author coloring aligned on an ADDED block AFTER a length-changing pending proposal (INV-49/50)", () => {
|
||||
// block 1 has a pending proposal (MUCH LONGER than original); block 2 is a NEW
|
||||
// paragraph with a Claude authorship span (in currentText coords). The toLanded
|
||||
// mapping must shift the span's coords so the added block is correctly colored.
|
||||
const baseline = "old.";
|
||||
const current = "LONGER REPLACEMENT.\n\nAdded para.";
|
||||
test("renderReview keeps author coloring aligned on a block AFTER a length-changing pending proposal (INV-49/50)", () => {
|
||||
// block 1 has a pending proposal whose applied text is MUCH LONGER than its
|
||||
// original; block 2 carries a Claude authorship span (in currentText coords).
|
||||
const baseline = "one short.\n\ntwo stable here.\n";
|
||||
const current = "one MUCH LONGER REPLACED TEXT.\n\ntwo stable here.\n";
|
||||
const proposals: ProposalView[] = [{
|
||||
id: "pr_1",
|
||||
anchorStart: 0,
|
||||
anchorEnd: "LONGER REPLACEMENT.".length,
|
||||
replaced: "old.",
|
||||
replacement: "LONGER REPLACEMENT.",
|
||||
original: "old.",
|
||||
anchorStart: current.indexOf("one MUCH LONGER REPLACED TEXT."),
|
||||
anchorEnd: current.indexOf("one MUCH LONGER REPLACED TEXT.") + "one MUCH LONGER REPLACED TEXT.".length,
|
||||
replaced: "one short.",
|
||||
replacement: "one MUCH LONGER REPLACED TEXT.",
|
||||
original: "one short.",
|
||||
}];
|
||||
// "Added" in currentText starts at: "LONGER REPLACEMENT.\n\n".length = 21
|
||||
const aStart = current.indexOf("Added");
|
||||
const authorSpans = [{ start: aStart, end: aStart + "Added".length, author: "claude" as const }];
|
||||
const sStart = current.indexOf("stable");
|
||||
const authorSpans = [{ start: sStart, end: sStart + "stable".length, author: "claude" as const }];
|
||||
const html = renderReview(baseline, current, authorSpans, proposals);
|
||||
// "Added" in the landedText block should be claude-colored despite the coordinate shift.
|
||||
expect(html).toContain("cw-ins-claude");
|
||||
// the Claude coloring wraps "stable" exactly — not shifted by the proposal's length delta.
|
||||
expect(html).toMatch(/<span class="cw-by-claude">stable<\/span>/);
|
||||
});
|
||||
|
||||
test("proposalBlockHtml renders Accept/Reject controls with dropdown carets (#64)", () => {
|
||||
@@ -522,45 +424,6 @@ describe("renderReview", () => {
|
||||
expect(html).toMatch(/Accept/);
|
||||
expect(html).toMatch(/Reject/);
|
||||
});
|
||||
|
||||
test("renderReview: a changed prose block colors ins/del by author (claude replace)", () => {
|
||||
// baseline "light" -> current "dark"; "dark" attributed to claude at 0..4
|
||||
const html = renderReview("light", "dark", [{ start: 0, end: 4, author: "claude" }], []);
|
||||
expect(html).toContain('cw-ins-claude');
|
||||
expect(html).toContain('cw-del-claude'); // adjacency: struck "light" inherits claude
|
||||
});
|
||||
|
||||
test("renderReview: an unchanged block renders plain (no author coloring)", () => {
|
||||
const doc = "Alpha stays.";
|
||||
const html = renderReview(doc, doc, [{ start: 0, end: 12, author: "human" }], []);
|
||||
expect(html).not.toContain("cw-by-");
|
||||
expect(html).not.toContain("cw-ins-");
|
||||
});
|
||||
|
||||
test("renderReview: an added block is author-colored as an insertion", () => {
|
||||
// baseline empty-ish -> add a new paragraph authored by human
|
||||
const html = renderReview("Keep.", "Keep.\n\nFresh line.", [{ start: 6, end: 17, author: "human" }], []);
|
||||
expect(html).toContain("cw-ins-human");
|
||||
});
|
||||
|
||||
test("renderReview: an added heading block renders as a heading AND is author-colored as an insertion", () => {
|
||||
// "Intro.\n\n" = 8 chars; "## New Section" = 14 chars → offset 8..22 in currentText.
|
||||
// Before fix: wordDiffByAuthor wrapped raw in <ins> BEFORE markdown-it parsed it,
|
||||
// so "## New Section" rendered as literal text (structural bug). After fix:
|
||||
// colorByAuthor uses the sentinel technique — markdown-it parses the block first,
|
||||
// so ## becomes a real <h2>, THEN sentinels are replaced with cw-ins-* spans.
|
||||
const html = renderReview("Intro.", "Intro.\n\n## New Section", [{ start: 8, end: 22, author: "human" }], []);
|
||||
expect(html).toMatch(/<h[12][^>]*>/); // real heading element, not literal "## "
|
||||
expect(html).toContain("cw-ins-human"); // author-colored insertion
|
||||
expect(html).not.toContain(">>"); // sanity: markers not escaped as text
|
||||
});
|
||||
|
||||
test("renderReview: a proposal block colors its del/ins by author (claude default)", () => {
|
||||
const proposals: ProposalView[] = [{ id: "p1", anchorStart: 0, anchorEnd: 5, replaced: "hello", replacement: "goodbye" }];
|
||||
const html = renderReview("hello", "hello", [], proposals);
|
||||
expect(html).toContain('cw-del-claude');
|
||||
expect(html).toContain('cw-ins-claude');
|
||||
});
|
||||
});
|
||||
|
||||
import { renderTrackChanges as rtc2 } from "../src/trackChangesModel";
|
||||
|
||||
Reference in New Issue
Block a user