Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(ok): render source-mode diffs through @pierre/diffs (#4067)
shagun-singh-inkeep65afac7603c3
diff --git a/.changeset/pierre-source-diff.md b/.changeset/pierre-source-diff.mdnew file mode 100644index 000000000..83202c3e0--- /dev/null+++ b/.changeset/pierre-source-diff.md@@ -0,0 +1,27 @@+---+'@inkeep/open-knowledge': patch+---++Source-mode diffs now render through Pierre instead of react-diff-view.++The Timeline "Source" toggle and the Agent Activity Panel share one diff+renderer, and on prose it read poorly: at the narrowest pane width it spent+more space on two gutter columns than it left for text, and it broke words+mid-token when wrapping. It also had no intra-line highlighting, so a+one-word edit inside a long paragraph showed up as two near-identical walls+of red and green with nothing marking what actually changed.++The new renderer gives a single gutter, wraps at word boundaries, and tints+the changed words inside the line. Syntax highlighting is deliberately off+for prose, where competing colours drown out the diff signal.++Two defects go with it: the change stepper could show an unreachable+denominator such as `4 / 3` because it measured Pierre's rows once and+latched, and opening a burst diff for one agent could show another agent's+diff on the same document, because the per-document cache key left the agent+out.++Line numbers are now hidden from screen readers on this surface. Pierre+renders the gutter and the content as separate columns, so without this a+screen reader announced every line number in a block before reaching any of+the text.diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 6415a2e7d..b9da3bb06 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -2983,11 +2983,6 @@ Homepage: https://github.com/nodejs/cjs-module-lexer#readmeCopyright (C) 2018-2020 Guy Bedford-### `[email protected]`-Homepage: https://github.com/JedWatson/classnames--Copyright (c) 2018 Jed Watson-### `[email protected]`Homepage: https://github.com/sindresorhus/cli-boxes@@ -3630,11 +3625,6 @@ Homepage: https://github.com/sindresorhus/get-streamCopyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)-### `[email protected]`-Homepage: https://github.com/ecomfe/gitdiff-parser--Copyright (c) 2020 Baidu EFE-### `[email protected]`Homepage: https://github.com/substack/github-from-package@@ -4157,11 +4147,6 @@ Homepage: https://github.com/sindresorhus/locate-pathCopyright (c) Sindre Sorhus <[email protected]> (sindresorhus.com)-### `[email protected]`-Homepage: https://lodash.com/--Copyright OpenJS Foundation and other contributors <https://openjsf.org/>-### `[email protected]`Homepage: https://lodash.com/custom-builds@@ -5129,11 +5114,6 @@ Homepage: https://daypicker.devCopyright (c) 2014-2025 Giampaolo Bellavite <[email protected]> and contributors-### `[email protected]`-Homepage: https://github.com/otakustay/react-diff-view#readme--Copyright (c) 2017 Gray Zhang-### `[email protected]`Homepage: https://react.dev/@@ -5423,11 +5403,6 @@ Homepage: https://github.com/shadcn-ui/uiCopyright (c) 2023 shadcn-### `[email protected]`-Homepage: https://github.com/moroshko/shallow-equal--_(LICENSE file present but no auto-extractable copyright line; refer to the package source for canonical attribution.)_-### `[email protected]`Homepage: https://github.com/kevva/shebang-command@@ -5915,11 +5890,6 @@ Homepage: https://github.com/marijnh/w3c-keyname#readmeCopyright (C) 2016 by Marijn Haverbeke <[email protected]> and others-### `[email protected]`-Homepage: https://github.com/BerkeleyTrue/warning--Copyright (c) 2013-present, Facebook, Inc.-### `[email protected]`Homepage: https://github.com/polygonplanet/weakmap-polyfilldiff --git a/biome-plugins/README.md b/biome-plugins/README.mdindex 6231e0a48..a4cfceee9 100644--- a/biome-plugins/README.md+++ b/biome-plugins/README.md@@ -56,6 +56,25 @@ The rule does NOT catch:Plugin: [`biome-plugins/no-raw-html-interactive-element.grit`](no-raw-html-interactive-element.grit). Fixture: [`biome-plugins/__fixtures__/no-raw-html-interactive-element.fixture.tsx`](__fixtures__/no-raw-html-interactive-element.fixture.tsx). Test: [`packages/app/tests/lint-plugins/no-raw-html-interactive-element.test.ts`](../packages/app/tests/lint-plugins/no-raw-html-interactive-element.test.ts). See [PRECEDENTS.md #42](../PRECEDENTS.md#custom-lint-enforcement-precedent-42) for the GritQL-plugin convention.+### `no-themeless-pierre-diff.grit`++`@pierre/diffs` render contract. Every `<MultiFileDiff>` construction site under `packages/app/src/**/*.tsx` (both the self-closing and the child-bearing JSX form) must pass an explicit `theme` and must set `diffStyle: 'unified'`. `new UnresolvedFile(...)` is covered by the `theme` half only — the constructor surfaces take no `diffStyle`.++The `theme` check reads the `options` object, not the whole prop list, so a `theme` token elsewhere on the element (`data-theme="dark"`, a title string, a variable named `theme` passed to an unrelated prop) cannot suppress the diagnostic. The fixture pins that with a decoy case.++Both halves are load-bearing. Pierre ships its own palette, so a themeless renderer paints in Pierre's colours instead of the app's and stops tracking the user's light/dark selection. And `diffStyle: 'split'` renders the two sides as separate DOM subtrees, so the change-stepper's DOM-order adjacency grouping counts roughly 2x the real groups — the displayed denominator desyncs from the anchors the stepper can actually reach.++This rule replaces a `readFileSync` + regex meta-test that asserted the same invariant over source text. That test violated the AGENTS.md rule against asserting raw source text for props ("Source guards need proof runtime coverage is impossible" — it wasn't), and it carried a tautological self-test that ran a regex over its own string literals. The per-component half of its intent now lives in runtime assertions in `ActivityPanelDiffView.dom.test.tsx` (`pre[data-diff-type="single"]` for unified; the injected `:host` token block for theme). Lint is the right layer for the codebase-wide "no call site omits it" half — [PRECEDENTS.md #42](../PRECEDENTS.md#custom-lint-enforcement-precedent-42).++The rule does NOT catch:+- a `@pierre/diffs` constructor other than `UnresolvedFile` — `new File(...)`, or any aliased import such as `File as PierreFile` in [`ConflictFilePreview.tsx`](../packages/app/src/components/ConflictFilePreview.tsx). GritQL matches the identifier as written, so a rename defeats it+- a renamed `MultiFileDiff` import, for the same reason+- a theme reaching the renderer through a spread or a variable (`options={{ ...baseOptions }}`, `options={opts}`) — the check reads the object literal, and there is no occurrence today++Runtime complement: `packages/app/src/components/ActivityPanelDiffView.dom.test.tsx` asserts the rendered result on the one surface this migration adds — `pre[data-diff-type="single"]` for unified, and the injected `:host` token block for theme.++Plugin: [`biome-plugins/no-themeless-pierre-diff.grit`](no-themeless-pierre-diff.grit). Fixture: [`biome-plugins/__fixtures__/no-themeless-pierre-diff.fixture.tsx`](__fixtures__/no-themeless-pierre-diff.fixture.tsx). Test: [`packages/app/tests/lint-plugins/no-themeless-pierre-diff.test.ts`](../packages/app/tests/lint-plugins/no-themeless-pierre-diff.test.ts).+### `no-resolved-value-theme-source.grit`1-way theme contract. Forbids resolving the user-intent theme value at the `bridge.setThemeSource(...)` call site. The contract is 1-way: pass the unresolved CRDT value (`'system' | 'light' | 'dark'`) verbatim. `'system'` delegates appearance tracking to macOS via `nativeTheme`; resolving at the call site (via `matchMedia` or a `prefersDark ? 'dark' : 'light'` ternary) loses tracking. See [PRECEDENTS.md #40(a)](../PRECEDENTS.md) for the renderer-state↔main-state contract.diff --git a/biome-plugins/__fixtures__/no-themeless-pierre-diff.fixture.tsx b/biome-plugins/__fixtures__/no-themeless-pierre-diff.fixture.tsxnew file mode 100644index 000000000..0c0b13eba--- /dev/null+++ b/biome-plugins/__fixtures__/no-themeless-pierre-diff.fixture.tsx@@ -0,0 +1,109 @@+// FIXTURE — drives `no-themeless-pierre-diff.test.ts` via shell-out to+// `biome check`. Not part of the main lint (lives outside the lint+// command's path list).+//+// Three positive cases (deliberate violations — plugin must fire) + two+// negative cases (clean usage that must NOT fire). Exact-equality in the+// test catches both false-negative regressions and false-positive+// widenings.++// biome-ignore lint/suspicious/noExplicitAny: fixture-only — production types unimportant here+declare const MultiFileDiff: any;+// biome-ignore lint/suspicious/noExplicitAny: fixture-only — production types unimportant here+declare const okPierreTheme: any;+// biome-ignore lint/suspicious/noExplicitAny: fixture-only — production types unimportant here+declare const oldFile: any;+// biome-ignore lint/suspicious/noExplicitAny: fixture-only — production types unimportant here+declare const newFile: any;+// biome-ignore lint/suspicious/noExplicitAny: fixture-only — production types unimportant here+declare const UnresolvedFile: any;+// biome-ignore lint/suspicious/noExplicitAny: fixture-only — production types unimportant here+declare const PierreFile: any;++// === Positive cases — must fire ===++// (1) No theme at all.+export function Positive1() {+ return <MultiFileDiff oldFile={oldFile} newFile={newFile} options={{ diffStyle: 'unified' }} />;+}++// (2) No diffStyle at all.+export function Positive2() {+ return <MultiFileDiff oldFile={oldFile} newFile={newFile} options={{ theme: okPierreTheme() }} />;+}++// (3) diffStyle explicitly split.+export function Positive3() {+ return (+ <MultiFileDiff+ oldFile={oldFile}+ newFile={newFile}+ options={{ diffStyle: 'split', theme: okPierreTheme() }}+ />+ );+}++// (4) A decoy `theme` token outside the options object.+export function Positive4() {+ return (+ <MultiFileDiff+ data-theme="dark"+ oldFile={oldFile}+ newFile={newFile}+ options={{ diffStyle: 'unified' }}+ />+ );+}++// (5) Child-bearing JSX form, no theme.+export function Positive5() {+ return (+ <MultiFileDiff oldFile={oldFile} newFile={newFile} options={{ diffStyle: 'unified' }}>+ {null}+ </MultiFileDiff>+ );+}++// (6) Constructor site, no theme.+export function positive6() {+ return new UnresolvedFile({ overflow: 'wrap' });+}++// === Negative cases — must NOT fire ===++// (1) Both theme and unified present.+export function Negative1() {+ return (+ <MultiFileDiff+ oldFile={oldFile}+ newFile={newFile}+ options={{ diffStyle: 'unified', theme: okPierreTheme() }}+ />+ );+}++// (2) Same, different property order.+export function Negative2() {+ return (+ <MultiFileDiff+ oldFile={oldFile}+ newFile={newFile}+ options={{ theme: okPierreTheme(), diffStyle: 'unified' }}+ />+ );+}++// (3) Constructor site with a theme.+export function negative3() {+ return new UnresolvedFile({ overflow: 'wrap', theme: okPierreTheme() });+}++// (positive) Aliased constructor surface without a theme.+export function PositivePierreFile() {+ return new PierreFile({ overflow: 'wrap' });+}++// (negative) Aliased constructor surface with a theme.+export function NegativePierreFile() {+ return new PierreFile({ overflow: 'wrap', theme: okPierreTheme() });+}diff --git a/biome-plugins/no-themeless-pierre-diff.grit b/biome-plugins/no-themeless-pierre-diff.gritnew file mode 100644index 000000000..a8a19d310--- /dev/null+++ b/biome-plugins/no-themeless-pierre-diff.grit@@ -0,0 +1,88 @@+// no-themeless-pierre-diff — @pierre/diffs render-contract enforcement.+//+// Every `@pierre/diffs` construction site must pass an explicit `theme`+// and must render unified. Both are load-bearing:+//+// theme — Pierre ships its own palette. Without a theme the pane+// renders in Pierre's colours, not the app's, and stops+// tracking the user's light/dark selection.+// diffStyle — 'split' renders the two sides as separate DOM subtrees,+// so the change-stepper's DOM-order adjacency grouping+// counts roughly 2x the real groups and desyncs the+// displayed denominator from the anchors it can reach.+//+// The theme half is scoped to the `options` object (and, for constructor+// sites, to the argument list), so a `theme` token elsewhere in the props+// — `data-theme="dark"`, a title string — cannot suppress it.+//+// This replaces a `readFileSync` + regex meta-test that asserted the same+// invariant over source text. That test violated the AGENTS.md rule+// against asserting raw source text for props, and its per-component+// intent is now covered at runtime in+// `ActivityPanelDiffView.dom.test.tsx` (`pre[data-diff-type="single"]`+// and the injected `:host` token block). Lint is the right layer for the+// codebase-wide "no call site omits it" half — precedent #42.+//+// Coverage gaps are recorded in biome-plugins/README.md.+//+// Suppress a deliberate exception with:+// // biome-ignore lint/plugin/no-themeless-pierre-diff: <reason>++language js++or {+ `<MultiFileDiff $props />` as $el where {+ or {+ $props <: not contains `options={$_ignored}`,+ and {+ $props <: contains `options={$opts}`,+ $opts <: not r"(?s).*\btheme\s*:.*"+ }+ },+ register_diagnostic(+ span = $el,+ message = "@pierre/diffs render contract: this renderer passes no theme — add `theme: okPierreTheme()` to its options so the pane uses app tokens and tracks light/dark. See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-themeless-pierre-diffgrit"+ )+ },+ `<MultiFileDiff $props>$_children</MultiFileDiff>` as $el where {+ or {+ $props <: not contains `options={$_ignored}`,+ and {+ $props <: contains `options={$opts}`,+ $opts <: not r"(?s).*\btheme\s*:.*"+ }+ },+ register_diagnostic(+ span = $el,+ message = "@pierre/diffs render contract: this renderer passes no theme — add `theme: okPierreTheme()` to its options so the pane uses app tokens and tracks light/dark. See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-themeless-pierre-diffgrit"+ )+ },+ `new UnresolvedFile($args)` as $el where {+ $args <: not r"(?s).*\btheme\s*:.*",+ register_diagnostic(+ span = $el,+ message = "@pierre/diffs render contract: this renderer passes no theme — add `theme: okPierreTheme()` to its options so the pane uses app tokens and tracks light/dark. See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-themeless-pierre-diffgrit"+ )+ },+ `new PierreFile($args)` as $el where {+ $args <: not r"(?s).*\btheme\s*:.*",+ register_diagnostic(+ span = $el,+ message = "@pierre/diffs render contract: this renderer passes no theme — add `theme: okPierreTheme()` to its options so the pane uses app tokens and tracks light/dark. See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-themeless-pierre-diffgrit"+ )+ },+ `<MultiFileDiff $props />` as $el where {+ $props <: not r"(?s).*diffStyle:\s*['\"]unified['\"].*",+ register_diagnostic(+ span = $el,+ message = "@pierre/diffs render contract: this renderer does not set diffStyle: 'unified' — add it to its options; 'split' desyncs the change stepper. See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-themeless-pierre-diffgrit"+ )+ },+ `<MultiFileDiff $props>$_children</MultiFileDiff>` as $el where {+ $props <: not r"(?s).*diffStyle:\s*['\"]unified['\"].*",+ register_diagnostic(+ span = $el,+ message = "@pierre/diffs render contract: this renderer does not set diffStyle: 'unified' — add it to its options; 'split' desyncs the change stepper. See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-themeless-pierre-diffgrit"+ )+ }+}diff --git a/biome.jsonc b/biome.jsoncindex 57a66e880..1b0994580 100644--- a/biome.jsonc+++ b/biome.jsonc@@ -256,6 +256,20 @@],"plugins": ["./biome-plugins/no-raw-html-interactive-element.grit"]},+ {+ // @pierre/diffs render contract. Every construction site passes an+ // explicit theme and renders unified. Scoped to production .tsx under+ // packages/app/src; the fixture is opted in so its deliberate+ // violations are what the plugin test counts.+ "includes": [+ "packages/app/src/**/*.tsx",+ "!**/*.test.tsx",+ "!**/*.dom.test.tsx",+ "!**/*.test-helper.tsx",+ "biome-plugins/__fixtures__/no-themeless-pierre-diff.fixture.tsx"+ ],+ "plugins": ["./biome-plugins/no-themeless-pierre-diff.grit"]+ },{// Localization discipline — a shipped hardcoded string is a build-visible// defect, not a convention someone has to remember. Scoped todiff --git a/packages/app/package.json b/packages/app/package.jsonindex d1788a824..f8412b8e3 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -153,7 +153,6 @@"radix-ui": "^1.4.3","react": "^19.2.5","react-day-picker": "^9.14.0",- "react-diff-view": "^3.3.3","react-dom": "^19.2.5","react-error-boundary": "^6.0.0","react-force-graph-2d": "^1.29.1",diff --git a/packages/app/src/components/ActivityPanelDiffView.dom.test.tsx b/packages/app/src/components/ActivityPanelDiffView.dom.test.tsxnew file mode 100644index 000000000..67ca5adc2--- /dev/null+++ b/packages/app/src/components/ActivityPanelDiffView.dom.test.tsx@@ -0,0 +1,203 @@+// @vitest-environment jsdom++import * as actualLinguiMacro from '@lingui/react/macro';+import { act, cleanup, render, waitFor } from '@testing-library/react';+import axe from 'axe-core';+import type { ReactNode } from 'react';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { pierreShadow } from '@/test-utils/pierre-shadow';++vi.doMock('@lingui/react/macro', () => ({+ ...actualLinguiMacro,+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,+}));++const { ActivityPanelDiffView } = await import('./ActivityPanelDiffView');++const SIMPLE_BEFORE = 'line one\nline two\noriginal line\nline four\nline five\n';+const SIMPLE_AFTER = 'line one\nline two\nchanged line\nline four\nline five\n';++const FILL = 'lorem ipsum dolor sit amet consectetur '.repeat(36);+const LONG_LINE_BEFORE = `${FILL}originalword${FILL}\n`;+const LONG_LINE_AFTER = `${FILL}changedword${FILL}\n`;++async function settle() {+ await act(async () => {+ await new Promise<void>((resolve) => setTimeout(resolve, 0));+ });+}++afterEach(() => {+ cleanup();+});++describe('ActivityPanelDiffView — No changes branches', () => {+ test('renders the No changes placeholder when before equals after', async () => {+ const { container } = render(+ <ActivityPanelDiffView before="same content\n" after="same content\n" cacheKey="doc@v1" />,+ );+ await settle();+ expect(container.textContent).toContain('No changes');+ expect(container.querySelector('diffs-container')).toBeNull();+ });++ test('renders the No changes placeholder for empty strings', async () => {+ const { container } = render(<ActivityPanelDiffView before="" after="" cacheKey="doc@v1" />);+ await settle();+ expect(container.textContent).toContain('No changes');+ expect(container.querySelector('diffs-container')).toBeNull();+ });++ test('keeps the activity-panel-diff wrapper on the placeholder', async () => {+ const { container } = render(+ <ActivityPanelDiffView before="x\n" after="x\n" cacheKey="doc@v1" />,+ );+ await settle();+ expect(container.querySelector('.activity-panel-diff')).not.toBeNull();+ });+});++describe('ActivityPanelDiffView — shadow root contract', () => {+ test('mounts a diffs-container with an open shadow root for changed before/after', async () => {+ const { container } = render(+ <ActivityPanelDiffView before={SIMPLE_BEFORE} after={SIMPLE_AFTER} cacheKey="doc@v1" />,+ );+ const shadow = await pierreShadow(container);+ expect(shadow).not.toBeNull();+ expect(shadow.host).toBe(container.querySelector('diffs-container'));+ });++ test('wraps the Pierre renderer in the activity-panel-diff div', async () => {+ const { container } = render(+ <ActivityPanelDiffView before={SIMPLE_BEFORE} after={SIMPLE_AFTER} cacheKey="doc@v1" />,+ );+ await settle();+ await settle();+ expect(container.querySelector('.activity-panel-diff')).not.toBeNull();+ });++ test('mounts Pierre without error on unusual string content', async () => {+ const { container } = render(+ <ActivityPanelDiffView+ before="---\n!!!\n@@@\n"+ after="different content\n"+ cacheKey="doc@v1"+ />,+ );+ await pierreShadow(container);+ });++ test('renders with overflow:wrap — data-overflow attribute present in shadow root', async () => {+ const { container } = render(+ <ActivityPanelDiffView before={SIMPLE_BEFORE} after={SIMPLE_AFTER} cacheKey="doc@v1" />,+ );+ const shadow = await pierreShadow(container);+ expect(shadow.querySelector('pre[data-overflow="wrap"]')).not.toBeNull();+ });+});++describe('ActivityPanelDiffView — data-line-type canary', () => {+ test('a known fixture yields at least one change-addition and change-deletion row', async () => {+ const { container } = render(+ <ActivityPanelDiffView before={SIMPLE_BEFORE} after={SIMPLE_AFTER} cacheKey="doc@v1" />,+ );+ const root = await pierreShadow(container);+ expect(root.querySelector('[data-line-type="change-addition"]')).not.toBeNull();+ expect(root.querySelector('[data-line-type="change-deletion"]')).not.toBeNull();+ });+});++describe('ActivityPanelDiffView — whole-file context (no hunk separator)', () => {+ test('parseDiffOptions.context renders all lines without a separator for a multi-line document', async () => {+ const head = 'changed line\n';+ const middle = Array.from({ length: 18 }, (_, i) => `context line ${i + 1}\n`).join('');+ const tail = 'another changed\n';+ const before = `${head}${middle}unchanged tail\n`;+ const after = `${head.replace('changed', 'modified')}${middle}${tail}`;+ const { container } = render(+ <ActivityPanelDiffView before={before} after={after} cacheKey="doc@v1" />,+ );+ const shadow = await pierreShadow(container);+ expect(shadow.textContent).toContain('context line 18');+ expect(shadow.textContent).not.toContain('unmodified lines');+ });+});++describe('ActivityPanelDiffView — maxLineDiffLength', () => {+ test('a long-line fixture with one changed word produces data-diff-span in [data-content]', async () => {+ const { container } = render(+ <ActivityPanelDiffView before={LONG_LINE_BEFORE} after={LONG_LINE_AFTER} cacheKey="doc@v1" />,+ );+ const shadow = await pierreShadow(container);+ await waitFor(() =>+ expect(shadow.querySelectorAll('[data-content] [data-diff-span]').length).toBeGreaterThan(0),+ );+ });+});++describe('ActivityPanelDiffView — axe accessibility', () => {+ test('mounted Pierre pane has no WCAG violations in jsdom', async () => {+ const { container } = render(+ <ActivityPanelDiffView before={SIMPLE_BEFORE} after={SIMPLE_AFTER} cacheKey="doc@v1" />,+ );+ await pierreShadow(container);+ const results = await axe.run(container, {+ runOnly: { type: 'tag', values: ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'] },+ });+ expect(results.violations).toEqual([]);+ });+});++describe('ActivityPanelDiffView — Pierre option contract', () => {+ test('renders with classic indicators and no Pierre file header', async () => {+ const { container } = render(+ <ActivityPanelDiffView before={SIMPLE_BEFORE} after={SIMPLE_AFTER} cacheKey="doc@v1" />,+ );+ const root = await pierreShadow(container);+ expect(root.querySelector('pre[data-indicators="classic"]')).not.toBeNull();+ expect(root.querySelector('[data-diffs-header]')).toBeNull();+ });++ test('renders unified (single-column), never split', async () => {+ const { container } = render(+ <ActivityPanelDiffView before={SIMPLE_BEFORE} after={SIMPLE_AFTER} cacheKey="doc@v1" />,+ );+ const shadow = await pierreShadow(container);+ expect(shadow.querySelector('pre[data-diff-type="single"]')).not.toBeNull();+ });++ test('applies the OK theme — shadow :host maps Pierre tokens onto app tokens', async () => {+ const { container } = render(+ <ActivityPanelDiffView before={SIMPLE_BEFORE} after={SIMPLE_AFTER} cacheKey="doc@v1" />,+ );+ const shadow = await pierreShadow(container);+ const css = Array.from(shadow.querySelectorAll('style'))+ .map((el) => el.textContent ?? '')+ .join('\n');+ expect(css).toContain('--diffs-fg:var(--foreground)');+ expect(css).toContain('--diffs-bg:var(--background)');+ });+});++describe('ActivityPanelDiffView — gutter aria-hidden injection', () => {+ test('gutter rows carry aria-hidden="true" after Pierre settles', async () => {+ const { container } = render(+ <ActivityPanelDiffView before={SIMPLE_BEFORE} after={SIMPLE_AFTER} cacheKey="doc@v1" />,+ );+ const shadow = await pierreShadow(container);+ const allLineTypeEls = Array.from(shadow.querySelectorAll('[data-line-type]'));+ const gutterRows = allLineTypeEls.filter((el) => !el.closest('[data-content]'));+ expect(gutterRows.length).toBeGreaterThan(0);+ for (const row of gutterRows) {+ expect(row.getAttribute('aria-hidden')).toBe('true');+ }+ });++ test('glyph-override style element is injected into the shadow root', async () => {+ const { container } = render(+ <ActivityPanelDiffView before={SIMPLE_BEFORE} after={SIMPLE_AFTER} cacheKey="doc@v1" />,+ );+ const shadow = await pierreShadow(container);+ expect(shadow.querySelector('[data-ok-glyph-override]')).not.toBeNull();+ });+});diff --git a/packages/app/src/components/ActivityPanelDiffView.error-boundary.dom.test.tsx b/packages/app/src/components/ActivityPanelDiffView.error-boundary.dom.test.tsxnew file mode 100644index 000000000..1da05eac0--- /dev/null+++ b/packages/app/src/components/ActivityPanelDiffView.error-boundary.dom.test.tsx@@ -0,0 +1,45 @@+// @vitest-environment jsdom++import * as actualLinguiMacro from '@lingui/react/macro';+import { cleanup, render } from '@testing-library/react';+import type { ReactNode } from 'react';+import { afterEach, describe, expect, test, vi } from 'vitest';++vi.doMock('@lingui/react/macro', () => ({+ ...actualLinguiMacro,+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,+}));++vi.doMock('@pierre/diffs/react', () => ({+ MultiFileDiff: () => {+ throw new Error('Pierre render blew up');+ },+}));++const { ActivityPanelDiffView } = await import('./ActivityPanelDiffView');++const BEFORE = 'line one\noriginal line\n';+const AFTER = 'line one\nchanged line\n';++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe('ActivityPanelDiffView — Pierre render failure', () => {+ test('falls back to the raw after-text instead of taking the panel down', () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ const { container } = render(+ <ActivityPanelDiffView before={BEFORE} after={AFTER} cacheKey="doc@v1" />,+ );++ expect(container.querySelector('diffs-container')).toBeNull();+ expect(container.querySelector('pre')?.textContent).toBe(AFTER);+ expect(+ consoleError.mock.calls.some(+ (args) => args[0] === '[activity-panel-diff] Pierre render failed',+ ),+ ).toBe(true);+ });+});diff --git a/packages/app/src/components/ActivityPanelDiffView.test.tsx b/packages/app/src/components/ActivityPanelDiffView.test.tsxdeleted file mode 100644index 80e3b0b3b..000000000--- a/packages/app/src/components/ActivityPanelDiffView.test.tsx+++ /dev/null@@ -1,77 +0,0 @@-import { createPatch } from 'diff';-import type { ReactElement, ReactNode } from 'react';-import { describe, expect, test } from 'vitest';-import { ActivityPanelDiffView } from './ActivityPanelDiffView';--type ElementWithProps = ReactElement<{- className?: string;- children?: ReactNode;- diff?: unknown;- hunks?: unknown;-}>;--function childrenArray(node: ReactNode): ReactNode[] {- if (Array.isArray(node)) return node;- return [node];-}--function collectText(node: ReactNode): string {- if (typeof node === 'string' || typeof node === 'number') return String(node);- if (!node || typeof node !== 'object') return '';- if (Array.isArray(node)) return node.map(collectText).join('');- const el = node as ElementWithProps;- return collectText(el.props.children ?? null);-}--function findByClassName(node: ReactNode, className: string): ReactElement | null {- if (!node || typeof node !== 'object') return null;- if (Array.isArray(node)) {- for (const child of node) {- const hit = findByClassName(child, className);- if (hit) return hit;- }- return null;- }- const el = node as ElementWithProps;- if (el.props?.className === className) return el;- const children = childrenArray(el.props?.children ?? null);- for (const child of children) {- const hit = findByClassName(child, className);- if (hit) return hit;- }- return null;-}--describe('ActivityPanelDiffView', () => {- test('renders "No changes" placeholder for empty input', () => {- const el = ActivityPanelDiffView({ diff: '' });- expect(collectText(el)).toContain('No changes');- });-- test('renders "No changes" placeholder for whitespace-only input', () => {- const el = ActivityPanelDiffView({ diff: ' \n \n' });- expect(collectText(el)).toContain('No changes');- });-- test('renders a diff container (not the placeholder) for a valid unified-diff with added line', () => {- const diff = createPatch('notes.md', 'hello\n', 'hello\nworld\n', undefined, undefined, {- context: 3,- });- const el = ActivityPanelDiffView({ diff });- expect(findByClassName(el, 'activity-panel-diff')).not.toBeNull();- expect(collectText(el)).not.toContain('No changes');- });-- test('renders a diff container for a valid unified-diff with deleted line', () => {- const diff = createPatch('notes.md', 'keep\ngone\n', 'keep\n', undefined, undefined, {- context: 3,- });- const el = ActivityPanelDiffView({ diff });- expect(findByClassName(el, 'activity-panel-diff')).not.toBeNull();- expect(collectText(el)).not.toContain('No changes');- });-- test('unparseable input does not crash', () => {- expect(() => ActivityPanelDiffView({ diff: 'not-a-diff' })).not.toThrow();- });-});diff --git a/packages/app/src/components/ActivityPanelDiffView.tsx b/packages/app/src/components/ActivityPanelDiffView.tsxindex f4519933b..941b75ae3 100644--- a/packages/app/src/components/ActivityPanelDiffView.tsx+++ b/packages/app/src/components/ActivityPanelDiffView.tsx@@ -1,43 +1,58 @@import { Trans } from '@lingui/react/macro';+import { MultiFileDiff } from '@pierre/diffs/react';import type * as React from 'react';-import { Diff, Hunk, parseDiff } from 'react-diff-view';-import 'react-diff-view/style/index.css';+import { ErrorBoundary } from 'react-error-boundary';+import { okPierreTheme } from '@/lib/pierre-theme';interface ActivityPanelDiffViewProps {- diff: string;- viewType?: 'split' | 'unified';+ before: string;+ after: string;+ cacheKey: string;}-function stripIndexHeader(diff: string): string {- const idx = diff.indexOf('\n--- ');- if (idx >= 0) return diff.slice(idx + 1);- return diff;-}+const PARSE_DIFF_OPTIONS = { context: 999_999 };-export function ActivityPanelDiffView({- diff,- viewType = 'unified',-}: ActivityPanelDiffViewProps): React.JSX.Element {- if (!diff.trim()) {- return (- <div className="activity-panel-diff px-3 py-2 text-xs text-muted-foreground italic">- <Trans>No changes</Trans>- </div>- );+const MAX_LINE_DIFF_LENGTH = 50_000;++const GLYPH_STYLE_ATTR = 'data-ok-glyph-override';+const GUTTER_ROW_SELECTOR = '[data-gutter] > [data-line-type]';+const CONTENT_ROW_SELECTOR = '[data-content] > [data-line-type]';+function hideGutterFromAssistiveTech(node: HTMLElement): void {+ const root = node.shadowRoot;+ if (!root) return;++ if (!root.querySelector(`[${GLYPH_STYLE_ATTR}]`)) {+ const style = document.createElement('style');+ style.setAttribute(GLYPH_STYLE_ATTR, '');+ style.textContent = '[data-content] [data-line]::before { color: var(--diffs-fg); }';+ root.appendChild(style);}- let files: ReturnType<typeof parseDiff>;- try {- files = parseDiff(stripIndexHeader(diff));- } catch {- return (- <pre className="activity-panel-diff font-mono text-xs whitespace-pre-wrap px-3 py-2">- {diff}- </pre>+ const gutterRows = root.querySelectorAll(GUTTER_ROW_SELECTOR);+ for (const el of gutterRows) {+ if (el.getAttribute('aria-hidden') !== 'true') el.setAttribute('aria-hidden', 'true');+ }+ if (gutterRows.length === 0 && root.querySelector(CONTENT_ROW_SELECTOR) !== null) {+ console.warn(+ '[activity-panel-diff] aria-hidden: content rows rendered but no [data-gutter] > [data-line-type] rows — Pierre DOM contract may have changed',);}+}- if (files.every((f) => f.hunks.length === 0)) {+function RawDiffFallback({ after }: { after: string }): React.JSX.Element {+ return (+ <pre className="whitespace-pre-wrap px-4 py-3 font-mono text-xs text-foreground/90">+ {after}+ </pre>+ );+}++export function ActivityPanelDiffView({+ before,+ after,+ cacheKey,+}: ActivityPanelDiffViewProps): React.JSX.Element {+ if (before === after) {return (<div className="activity-panel-diff px-3 py-2 text-xs text-muted-foreground italic"><Trans>No changes</Trans>@@ -47,16 +62,44 @@ export function ActivityPanelDiffView({return (<div className="activity-panel-diff">- {files.map((file) => (- <Diff- key={`${file.oldPath ?? 'a'}→${file.newPath ?? 'b'}`}- viewType={viewType}- diffType={file.type}- hunks={file.hunks}- >- {(hunks) => hunks.map((hunk) => <Hunk key={hunk.content} hunk={hunk} />)}- </Diff>- ))}+ <ErrorBoundary+ resetKeys={[cacheKey]}+ fallback={<RawDiffFallback after={after} />}+ onError={(error) =>+ console.error('[activity-panel-diff] Pierre render failed', {+ cacheKey,+ beforeLength: before.length,+ afterLength: after.length,+ error,+ })+ }+ >+ <MultiFileDiff+ className="pierre-diff"+ oldFile={{+ name: 'document.md',+ contents: before,+ lang: 'text',+ cacheKey: `${cacheKey}-before`,+ }}+ newFile={{+ name: 'document.md',+ contents: after,+ lang: 'text',+ cacheKey: `${cacheKey}-after`,+ }}+ options={{+ diffStyle: 'unified',+ overflow: 'wrap',+ maxLineDiffLength: MAX_LINE_DIFF_LENGTH,+ theme: okPierreTheme(),+ parseDiffOptions: PARSE_DIFF_OPTIONS,+ disableFileHeader: true,+ diffIndicators: 'classic',+ onPostRender: hideGutterFromAssistiveTech,+ }}+ />+ </ErrorBoundary></div>);}diff --git a/packages/app/src/components/AgentDiffPane.cache-key.dom.test.tsx b/packages/app/src/components/AgentDiffPane.cache-key.dom.test.tsxnew file mode 100644index 000000000..cb3049bfb--- /dev/null+++ b/packages/app/src/components/AgentDiffPane.cache-key.dom.test.tsx@@ -0,0 +1,71 @@+// @vitest-environment jsdom++import * as actualLinguiMacro from '@lingui/react/macro';+import { cleanup, render, waitFor } from '@testing-library/react';+import type { ReactNode } from 'react';+import { afterEach, describe, expect, test, vi } from 'vitest';++const fetchAgentBurstDiff = vi.fn((agentId: string) =>+ Promise.resolve({+ diff: '',+ before: 'base line\n',+ after: `${agentId} line\n`,+ properties: { changes: [], unparseable: null },+ }),+);++vi.doMock('@/lib/use-activity-panel', () => ({ fetchAgentBurstDiff }));++vi.doMock('@/components/RenderedDiffView', async (importOriginal) => {+ const mod = await importOriginal<typeof import('@/components/RenderedDiffView')>();+ return {+ ...mod,+ computeRenderedDiff: () => ({ ok: false as const }),+ RenderedDiffView: () => null,+ };+});++vi.doMock('@lingui/react/macro', () => ({+ ...actualLinguiMacro,+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,+ useLingui: () => ({ t: (s: string) => s }),+}));++const { AgentDiffPane } = await import('@/components/AgentDiffPane');+const { TooltipProvider } = await import('@/components/ui/tooltip');++function viewFor(agentId: string) {+ return {+ agentId,+ agentName: 'Agent',+ agentColor: '#888888',+ docName: 'notes',+ keptCount: 1,+ maxVersions: 3,+ };+}++function paneFor(agentId: string) {+ return (+ <TooltipProvider>+ <AgentDiffPane view={viewFor(agentId)} isPanelCollapsed={false} onTogglePanel={() => {}} />+ </TooltipProvider>+ );+}++afterEach(() => {+ cleanup();+ fetchAgentBurstDiff.mockClear();+});++describe('AgentDiffPane — version-diff cache key', () => {+ test('a second agent on the same document does not read the first agent cached diff', async () => {+ const { rerender } = render(paneFor('agent-1'));+ await waitFor(() => expect(fetchAgentBurstDiff).toHaveBeenCalledTimes(1));++ rerender(paneFor('agent-2'));+ await waitFor(() => expect(fetchAgentBurstDiff).toHaveBeenCalledTimes(2));++ expect(fetchAgentBurstDiff.mock.calls.map((call) => call[0])).toEqual(['agent-1', 'agent-2']);+ });+});diff --git a/packages/app/src/components/AgentDiffPane.tsx b/packages/app/src/components/AgentDiffPane.tsxindex 5f8d9720c..5d17c2a79 100644--- a/packages/app/src/components/AgentDiffPane.tsx+++ b/packages/app/src/components/AgentDiffPane.tsx@@ -11,7 +11,11 @@ import { Spinner } from '@/components/ui/spinner';import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import { type AgentDiffView, closeAgentDiff, setAgentDiffKept } from '@/lib/agent-diff-store';-import { collectChangeAnchors, PROPERTY_CHANGE_ANCHOR_SELECTOR } from '@/lib/diff-change-nav';+import {+ collectChangeAnchors,+ PROPERTY_CHANGE_ANCHOR_SELECTOR,+ watchPierreShadowRoots,+} from '@/lib/diff-change-nav';import { LruStringCache } from '@/lib/lru-string-cache';import { isOverlayLayerOpen } from '@/lib/overlay-layers';import { RENDERED_DIFF_CHANGE_SELECTOR } from '@/lib/rendered-diff/diff-decorations';@@ -51,7 +55,7 @@ export function AgentDiffPane({ view, isPanelCollapsed, onTogglePanel }: AgentDiuseEffect(() => {let cancelled = false;setResult({ status: 'loading', diff: '', before: '', after: '', properties: EMPTY_DELTA });- const key = `${docName}\0${keptCount}`;+ const key = `${agentId}\0${docName}\0${keptCount}`;const cached = cache.get(key);if (cached !== undefined) {const parsed = JSON.parse(cached) as {@@ -100,6 +104,7 @@ export function AgentDiffPane({ view, isPanelCollapsed, onTogglePanel }: AgentDiconst scrollToFirstChange = (): void => {if (done) return;+ shadowWatcher.sync();const el =container.querySelector<HTMLElement>(PROPERTY_CHANGE_ANCHOR_SELECTOR) ??container.querySelector<HTMLElement>(RENDERED_DIFF_CHANGE_SELECTOR) ??@@ -107,6 +112,7 @@ export function AgentDiffPane({ view, isPanelCollapsed, onTogglePanel }: AgentDiif (!el) return;done = true;observer?.disconnect();+ shadowWatcher.disconnect();const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;el.scrollIntoView({ block: 'center', behavior: reduceMotion ? 'auto' : 'smooth' });};@@ -123,13 +129,19 @@ export function AgentDiffPane({ view, isPanelCollapsed, onTogglePanel }: AgentDi}, settleMs);};+ const shadowWatcher = watchPierreShadowRoots(container, scheduleAfterSettle);+observer = new MutationObserver(scheduleAfterSettle);observer.observe(container, { childList: true, subtree: true });scheduleAfterSettle();- const failsafe = setTimeout(() => observer?.disconnect(), 5000);+ const failsafe = setTimeout(() => {+ observer?.disconnect();+ shadowWatcher.disconnect();+ }, 5000);return () => {observer?.disconnect();+ shadowWatcher.disconnect();if (settleTimer !== undefined) clearTimeout(settleTimer);if (rafId !== undefined) cancelAnimationFrame(rafId);clearTimeout(failsafe);@@ -323,7 +335,11 @@ export function AgentDiffPane({ view, isPanelCollapsed, onTogglePanel }: AgentDi</div>}>- <LazyActivityPanelDiffView diff={result.diff} viewType="unified" />+ <LazyActivityPanelDiffView+ before={result.before}+ after={result.after}+ cacheKey={`${agentId}@${docName}@v${keptCount}`}+ /></Suspense>))}</div>diff --git a/packages/app/src/components/SkillForkDialog.tsx b/packages/app/src/components/SkillForkDialog.tsxindex 52b9ce792..4a2515a11 100644--- a/packages/app/src/components/SkillForkDialog.tsx+++ b/packages/app/src/components/SkillForkDialog.tsx@@ -129,7 +129,7 @@ export function SkillForkDialog({<DialogBody className="min-h-0 flex-1 overflow-auto">{canonicalBody !== null && forkBody !== null ? (<MultiFileDiff- className="conflict-view"+ className="pierre-diff"oldFile={{ name: skill.name, contents: canonicalBody }}newFile={{ name: skill.name, contents: forkBody }}options={{ overflow: 'wrap', diffStyle: 'unified', theme: okPierreTheme() }}diff --git a/packages/app/src/components/SkillUpdateConflictDialog.tsx b/packages/app/src/components/SkillUpdateConflictDialog.tsxindex e0aedad64..ede5bd9ff 100644--- a/packages/app/src/components/SkillUpdateConflictDialog.tsx+++ b/packages/app/src/components/SkillUpdateConflictDialog.tsx@@ -47,7 +47,7 @@ export function SkillUpdateConflictDialog({<DialogBody className="min-h-0 flex-1 overflow-auto">{}<MultiFileDiff- className="conflict-view"+ className="pierre-diff"oldFile={{ name: skillName, contents: localBody }}newFile={{ name: skillName, contents: upstreamBody }}options={{ overflow: 'wrap', diffStyle: 'unified', theme: okPierreTheme() }}diff --git a/packages/app/src/components/TimelineDiffPane.source-diff.dom.test.tsx b/packages/app/src/components/TimelineDiffPane.source-diff.dom.test.tsxnew file mode 100644index 000000000..12015d8a0--- /dev/null+++ b/packages/app/src/components/TimelineDiffPane.source-diff.dom.test.tsx@@ -0,0 +1,200 @@+import { cleanup, render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { useEffect, useState } from 'react';+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';++vi.mock('next-themes', () => ({+ useTheme: () => ({ resolvedTheme: 'light' }),+}));+vi.mock('@/editor/DocumentContext', () => ({+ useDocumentContext: () => ({ activeProvider: null, activeDocName: 'notes' }),+}));++import { TooltipProvider } from '@/components/ui/tooltip';+import { openTimelineDiff, type TimelineDiffView } from '@/lib/timeline-diff-store';+import { pierreShadow } from '@/test-utils/pierre-shadow';++vi.doMock('@/components/ActivityPanelDiffView', async (importOriginal) => {+ const { ActivityPanelDiffView: Orig } =+ await importOriginal<typeof import('./ActivityPanelDiffView')>();+ function DelayedDiffView(props: Parameters<typeof Orig>[0]) {+ const [ready, setReady] = useState(false);+ useEffect(() => {+ const id = setTimeout(() => setReady(true), 300);+ return () => clearTimeout(id);+ }, []);+ return ready ? Orig(props) : null;+ }+ return { ActivityPanelDiffView: DelayedDiffView };+});++const { TimelineDiffPane } = await import('./TimelineDiffPane');+const { collectChangeAnchors, PROPERTY_CHANGE_ANCHOR_SELECTOR } = await import(+ '@/lib/diff-change-nav'+);++const VERSION_SHA = 'c'.repeat(40);+const PARENT_SHA = 'p'.repeat(40);++const BEFORE = ['alpha', 'bravo', 'charlie', 'delta', 'echo', 'foxtrot', 'golf'].join('\n');+const AFTER = ['alpha', 'BRAVO', 'charlie', 'delta', 'echo', 'FOXTROT', 'golf'].join('\n');+const EXPECTED_GROUPS = 2;++const BEFORE_WITH_FM = [+ '---',+ 'title: First Draft',+ 'date: 2024-01-01',+ '---',+ 'alpha',+ 'bravo',+ 'charlie',+ 'delta',+ 'echo',+ 'foxtrot',+ 'golf',+].join('\n');+const AFTER_WITH_FM = [+ '---',+ 'title: Final Draft',+ 'date: 2024-06-01',+ '---',+ 'alpha',+ 'BRAVO',+ 'charlie',+ 'delta',+ 'echo',+ 'FOXTROT',+ 'golf',+].join('\n');++const view: TimelineDiffView = {+ docName: 'notes',+ sha: VERSION_SHA,+ parentSha: PARENT_SHA,+ laterEdits: 0,+ authorName: 'Alice',+ relativeTime: '2 hours ago',+ absoluteTime: '2026-04-17 00:00',+};++function mockVersions(parent: string, version: string): void {+ globalThis.fetch = vi.fn((input: RequestInfo | URL) => {+ const url = typeof input === 'string' ? input : input.toString();+ const content = url.includes(`/api/history/${PARENT_SHA}`)+ ? parent+ : url.includes(`/api/history/${VERSION_SHA}`)+ ? version+ : null;+ if (content === null) return Promise.resolve(new Response(null, { status: 404 }));+ return Promise.resolve(+ new Response(JSON.stringify({ content }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' },+ }),+ );+ }) as never;+}++function renderPane() {+ openTimelineDiff(view);+ return render(+ <TooltipProvider>+ <TimelineDiffPane view={view} isPanelCollapsed={false} onTogglePanel={() => {}} />+ </TooltipProvider>,+ );+}++async function readDenominator(expected?: number): Promise<number> {+ await waitFor(() => expect(screen.queryByTestId('timeline-diff-next')).not.toBeNull(), {+ timeout: 5_000,+ });+ if (expected !== undefined) {+ await waitFor(+ () => {+ const readout = screen.queryByText(/\d+\s*\/\s*\d+/);+ const d = Number(readout?.textContent?.split('/')[1]?.trim());+ expect(d).toBe(expected);+ },+ { timeout: 6_000 },+ );+ }+ const readout = screen.getByText(/\d+\s*\/\s*\d+/);+ const denominator = readout.textContent?.split('/')[1]?.trim();+ expect(denominator).toBeTruthy();+ return Number(denominator);+}++let originalFetch: typeof globalThis.fetch;++beforeEach(() => {+ originalFetch = globalThis.fetch;+});++afterEach(() => {+ globalThis.fetch = originalFetch;+ cleanup();+ vi.restoreAllMocks();+});++describe('TimelineDiffPane — source-mode stepper', () => {+ test('the displayed denominator equals the anchors the stepper can reach', async () => {+ mockVersions(BEFORE, AFTER);+ const { container } = renderPane();+ await waitFor(() => expect(screen.queryByText('Loading diff')).toBeNull());+ await userEvent.click(screen.getByTestId('timeline-diff-render-source'));+ await pierreShadow(container as HTMLElement);++ const denominator = await readDenominator();+ const anchors = collectChangeAnchors(container as HTMLElement);+ expect(anchors).toHaveLength(EXPECTED_GROUPS);+ expect(denominator).toBe(anchors.length);+ });++ test('every step lands on a Pierre change row', async () => {+ mockVersions(BEFORE, AFTER);+ const { container } = renderPane();+ await waitFor(() => expect(screen.queryByText('Loading diff')).toBeNull());+ await userEvent.click(screen.getByTestId('timeline-diff-render-source'));+ await pierreShadow(container as HTMLElement);++ await waitFor(() => expect(screen.queryByTestId('timeline-diff-next')).not.toBeNull(), {+ timeout: 5_000,+ });++ const scrolled: Element[] = [];+ vi.spyOn(HTMLElement.prototype, 'scrollIntoView').mockImplementation(function (+ this: HTMLElement,+ ) {+ scrolled.push(this);+ });++ const next = screen.getByTestId('timeline-diff-next');+ await userEvent.click(next);+ await userEvent.click(next);++ expect(scrolled.length).toBeGreaterThan(0);+ for (const el of scrolled) {+ expect(+ el.matches('[data-line-type="change-addition"], [data-line-type="change-deletion"]'),+ ).toBe(true);+ }+ });+});++describe('TimelineDiffPane — source-mode stepper with property changes', () => {+ test('denominator accounts for both property anchors and Pierre body change rows', async () => {+ mockVersions(BEFORE_WITH_FM, AFTER_WITH_FM);+ const { container } = renderPane();+ await waitFor(() => expect(screen.queryByText('Loading diff')).toBeNull());+ await userEvent.click(screen.getByTestId('timeline-diff-render-source'));+ await pierreShadow(container as HTMLElement);++ const EXPECTED_TOTAL = EXPECTED_GROUPS + 2;+ const denominator = await readDenominator(EXPECTED_TOTAL);+ const pierreAnchors = collectChangeAnchors(container as HTMLElement);+ const propertyRows = container.querySelectorAll(PROPERTY_CHANGE_ANCHOR_SELECTOR);+ expect(propertyRows).toHaveLength(2);+ expect(pierreAnchors).toHaveLength(EXPECTED_GROUPS);+ expect(denominator).toBe(EXPECTED_TOTAL);+ });+});diff --git a/packages/app/src/components/TimelineDiffPane.tsx b/packages/app/src/components/TimelineDiffPane.tsxindex eff4936c6..b2738c6e2 100644--- a/packages/app/src/components/TimelineDiffPane.tsx+++ b/packages/app/src/components/TimelineDiffPane.tsx@@ -21,8 +21,8 @@ import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';import {collectChangeAnchors,- countChangeGroups,PROPERTY_CHANGE_ANCHOR_SELECTOR,+ watchPierreShadowRoots,} from '@/lib/diff-change-nav';import { LruStringCache } from '@/lib/lru-string-cache';import { isOverlayLayerOpen } from '@/lib/overlay-layers';@@ -57,6 +57,8 @@ export function TimelineDiffPane({ view, isPanelCollapsed, onTogglePanel }: Timeconst abortRef = useRef<AbortController | null>(null);const diffBodyRef = useRef<HTMLDivElement>(null);const [currentChange, setCurrentChange] = useState(0);+ const [pierreChangeCount, setPierreChangeCount] = useState(0);+ const [pierreSettled, setPierreSettled] = useState(false);const [propertiesOpen, setPropertiesOpen] = useState(true);const result = useTimelineEntryDiff(sha, docName, cache, 'vs-parent', parentSha);@@ -74,7 +76,9 @@ export function TimelineDiffPane({ view, isPanelCollapsed, onTogglePanel }: Time? 0: usingRendered && rendered?.ok? countRenderedDiffAnchors(rendered)- : countChangeGroups(result.diff);+ : pierreSettled+ ? pierreChangeCount+ : 0;const propertyAnchorCount =properties === null? 0@@ -92,7 +96,9 @@ export function TimelineDiffPane({ view, isPanelCollapsed, onTogglePanel }: Time...container.querySelectorAll<HTMLElement>(PROPERTY_CHANGE_ANCHOR_SELECTOR),...(usingRendered? Array.from(container.querySelectorAll<HTMLElement>(RENDERED_DIFF_CHANGE_SELECTOR))- : collectChangeAnchors(container)),+ : pierreSettled+ ? collectChangeAnchors(container)+ : []),];if (anchors.length === 0) return;const clamped = (next + anchors.length) % anchors.length;@@ -109,44 +115,60 @@ export function TimelineDiffPane({ view, isPanelCollapsed, onTogglePanel }: Timeconst container = diffBodyRef.current;if (diffKey === '' || !container) return;setCurrentChange(0);+ setPierreChangeCount(0);+ setPierreSettled(false);- let done = false;+ let hasScrolled = false;let observer: MutationObserver | null = null;let settleTimer: ReturnType<typeof setTimeout> | undefined;let rafId: number | undefined;- const scrollToFirstChange = (): void => {- if (done) return;+ const measureChanges = (): Element[] => {+ shadowWatcher.sync();+ const pierreAnchors = collectChangeAnchors(container);+ setPierreChangeCount(pierreAnchors.length);+ setPierreSettled(true);+ return pierreAnchors;+ };++ const measureAndMaybeScroll = (): void => {+ const pierreAnchors = measureChanges();+ if (hasScrolled) return;const el =container.querySelector<HTMLElement>(PROPERTY_CHANGE_ANCHOR_SELECTOR) ??container.querySelector<HTMLElement>(RENDERED_DIFF_CHANGE_SELECTOR) ??- collectChangeAnchors(container)[0];+ pierreAnchors[0];if (!el) return;- done = true;- observer?.disconnect();+ hasScrolled = true;const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;el.scrollIntoView({ block: 'center', behavior: reduceMotion ? 'auto' : 'smooth' });};const settleMs = 120;const scheduleAfterSettle = (): void => {- if (done) return;if (settleTimer !== undefined) clearTimeout(settleTimer);settleTimer = setTimeout(() => {if (rafId !== undefined) cancelAnimationFrame(rafId);rafId = requestAnimationFrame(() => {- rafId = requestAnimationFrame(scrollToFirstChange);+ rafId = requestAnimationFrame(measureAndMaybeScroll);});}, settleMs);};+ const shadowWatcher = watchPierreShadowRoots(container, scheduleAfterSettle);+observer = new MutationObserver(scheduleAfterSettle);observer.observe(container, { childList: true, subtree: true });scheduleAfterSettle();- const failsafe = setTimeout(() => observer?.disconnect(), 5000);+ const failsafe = setTimeout(() => {+ measureChanges();+ observer?.disconnect();+ shadowWatcher.disconnect();+ }, 5000);return () => {observer?.disconnect();+ shadowWatcher.disconnect();if (settleTimer !== undefined) clearTimeout(settleTimer);if (rafId !== undefined) cancelAnimationFrame(rafId);clearTimeout(failsafe);@@ -418,7 +440,11 @@ export function TimelineDiffPane({ view, isPanelCollapsed, onTogglePanel }: Time</div>}>- <LazyActivityPanelDiffView diff={result.diff} viewType="unified" />+ <LazyActivityPanelDiffView+ before={result.before}+ after={result.after}+ cacheKey={`${docName}@${sha}`}+ /></Suspense>))}</div>diff --git a/packages/app/src/globals.css b/packages/app/src/globals.cssindex 7d946c194..5dfbb252b 100644--- a/packages/app/src/globals.css+++ b/packages/app/src/globals.css@@ -8,80 +8,6 @@@import "./color-themes.generated.css";@plugin "tailwind-scrollbar";-/* --- Activity Panel unified-diff styling (react-diff-view) ---- The library renders diff hunks with `.diff-code-insert`, `.diff-code-delete`,- `.diff-gutter-insert`, `.diff-gutter-delete` class roots. Scoping under- `.activity-panel-diff` keeps the tokens from leaking into the main conflict- surface (a different DOM entirely). */-.activity-panel-diff .diff {- width: 100%;- table-layout: fixed;-}--.activity-panel-diff .diff-line,-.activity-panel-diff .diff-decoration-content {- font-family: var(--font-mono);- line-height: 1.25rem;-}--.activity-panel-diff .diff-gutter {- color: var(--muted-foreground);- font-size: 10px;-}--.activity-panel-diff .diff-code {- font-family: var(--font-mono);- font-size: 0.75rem;- line-height: 1.25rem;-}--.activity-panel-diff .diff-code-insert {- background-color: color-mix(in oklab, var(--color-green-100) 60%, transparent);- color: var(--color-green-900);-}--.activity-panel-diff .diff-code-delete {- background-color: color-mix(in oklab, var(--color-red-100) 60%, transparent);- color: var(--color-red-900);-}--.dark .activity-panel-diff .diff-code-insert {- background-color: color-mix(in oklab, var(--color-green-900) 40%, transparent);- color: var(--color-green-200);-}--.dark .activity-panel-diff .diff-code-delete {- background-color: color-mix(in oklab, var(--color-red-900) 40%, transparent);- color: var(--color-red-200);-}--.activity-panel-diff .diff-gutter-insert {- background-color: color-mix(in oklab, var(--color-green-100) 40%, transparent);- color: var(--color-green-800);-}--.activity-panel-diff .diff-gutter-delete {- background-color: color-mix(in oklab, var(--color-red-100) 40%, transparent);- color: var(--color-red-800);-}--.dark .activity-panel-diff .diff-gutter-insert {- background-color: color-mix(in oklab, var(--color-green-900) 30%, transparent);- color: var(--color-green-300);-}--.dark .activity-panel-diff .diff-gutter-delete {- background-color: color-mix(in oklab, var(--color-red-900) 30%, transparent);- color: var(--color-red-300);-}--.activity-panel-diff .diff-hunk-header {- background-color: var(--muted);- color: var(--muted-foreground);- font-size: 10px;- line-height: 1.25rem;-}-/* react-medium-image-zoom hardcodes rgba(255,255,255,1) for the visibleoverlay — the lightbox flashes white in dark mode without this override.The unprefixed library rule remains correct for light mode (white ≈ the@@ -1163,9 +1089,33 @@is the `<diffs-container>` host it renders into — the CodeMirror rule thisreplaces (`.diff-view .cm-content`) went away with the merge view and had nosuccessor until now. The var is 0 when the composer is collapsed or hidden,- so the space is reclaimed on its own. */+ so the space is reclaimed on its own.++ Scoped to `.conflict-view` deliberately: the inset exists for surfaces that+ sit under the floating ask composer. A Pierre diff inside a dialog has no+ composer to clear. */+/* Pierre renders into a `<diffs-container>` custom element. Undefined/custom+ elements get no UA display styling and default to `display: inline`, and+ @pierre/[email protected] never sets `display` on `:host` (its `:host` block is+ custom properties only; every `display: block` in its shadow stylesheet+ targets inner nodes -- `pre, code, [data-error-wrapper]`,+ `[data-unmodified-lines]`, `&:before`). An inline host ignores width,+ padding and block layout, which is what the `padding-bottom` rule below+ depends on.++ Both selectors are needed because the class lands in different places.+ `MultiFileDiff` forwards `className` ONTO the host, so for the panel and+ dialog surfaces `.pierre-diff` IS the `<diffs-container>`. `ConflictView`+ and `ConflictFilePreview` instead put `conflict-view` on a wrapper and+ render the host inside it, so there it is a descendant. A single+ `.pierre-diff diffs-container` descendant rule matches NEITHER group's+ host for the first three surfaces and was silently dead. */+.pierre-diff,.conflict-view diffs-container {display: block;+}++.conflict-view diffs-container {padding-bottom: var(--ask-composer-height, 0px);}@@ -6489,7 +6439,7 @@ html.electron-mode [data-slot="sidebar-inner"] {background-color: var(--comment-reveal-fill);}-/* Pierre conflict view CHROME — maps Pierre's --diffs-* custom properties to+/* Pierre diff surface CHROME — maps Pierre's --diffs-* custom properties tothe app's existing design tokens. These properties inherit through the openshadow root of <diffs-container>, so no unsafeCSS injection is needed forcolour theming. The underlying --diff-added / --diff-removed tokens already@@ -6500,7 +6450,10 @@ html.electron-mode [data-slot="sidebar-inner"] {below (--diffs-fg, --diffs-bg, --diffs-addition-color,--diffs-deletion-color) are also written by Pierre at :host from thattheme's colors, and :host wins over this rule — the two are kept resolving- to the same tokens deliberately, so neither can silently take over. */+ to the same tokens deliberately, so neither can silently take over.++ Both surfaces use Pierre as their renderer and share this custom-property block. */+.pierre-diff,.conflict-view {--diffs-bg: var(--background);--diffs-fg: var(--foreground);@@ -6548,7 +6501,36 @@ html.electron-mode [data-slot="sidebar-inner"] {--diffs-fg-conflict-marker: var(--muted-foreground);--diffs-marker-bg: var(--muted);+ /* Separator background and foreground (--diffs-fg-number above) match the+ muted palette so the "N unmodified lines" widget blends with the gutters. */--diffs-bg-separator: var(--muted);++ /* Changed-row gutter numbers use --diffs-fg (= --foreground, WCAG-vetted on+ every registered palette) so the line-number contrast meets 4.5:1. Context+ numbers stay muted via --diffs-fg-number. The background hooks tint the+ gutter column lighter than the body row (10% vs 15%); opaque var(--background)+ as mix base avoids premultiplied-alpha collapse on Pierre's second mix pass. */+ --diffs-fg-number-addition-override: var(--diffs-fg);+ --diffs-fg-number-deletion-override: var(--diffs-fg);+ --diffs-bg-addition-number-override: color-mix(+ in oklab,+ var(--diff-added) 10%,+ var(--background)+ );+ --diffs-bg-deletion-number-override: color-mix(+ in oklab,+ var(--diff-removed) 10%,+ var(--background)+ );+}++/* Activity-panel typography: Pierre defaults to 13px sans-serif; the panel uses+ 12px mono throughout to match the text-xs treatment of the rest of the panel.+ Setting on the outer wrapper lets the vars inherit through the open shadow root+ of <diffs-container>. */+.activity-panel-diff {+ --diffs-font-size: 0.75rem;+ --diffs-font-family: var(--font-mono);}/* Pointer marker drawn into the frame a bug-report screenshot is taken on.diff --git a/packages/app/src/lib/diff-change-nav.dom.test.tsx b/packages/app/src/lib/diff-change-nav.dom.test.tsxnew file mode 100644index 000000000..29ceeaa54--- /dev/null+++ b/packages/app/src/lib/diff-change-nav.dom.test.tsx@@ -0,0 +1,226 @@+// @vitest-environment jsdom++import * as actualLinguiMacro from '@lingui/react/macro';+import { act, cleanup, render, waitFor } from '@testing-library/react';+import type { ReactNode } from 'react';+import { afterEach, describe, expect, test, vi } from 'vitest';+import { pierreShadow } from '@/test-utils/pierre-shadow';++vi.mock('@/components/RenderedDiffView', async (importOriginal) => {+ const mod = await importOriginal<typeof import('@/components/RenderedDiffView')>();+ return {+ ...mod,+ computeRenderedDiff: () => ({ ok: false as const }),+ RenderedDiffView: () => null,+ };+});++vi.mock('@/lib/use-activity-panel', () => ({+ fetchAgentBurstDiff: () =>+ Promise.resolve({+ diff: '--- a\n+++ b\n@@ -1,3 +1,3 @@\n line one\n-original line\n+changed line\n line three\n',+ before: 'line one\noriginal line\nline three\n',+ after: 'line one\nchanged line\nline three\n',+ properties: { changes: [], unparseable: null },+ }),+}));++vi.doMock('@lingui/react/macro', () => ({+ ...actualLinguiMacro,+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,+ useLingui: () => ({ t: (s: string) => s }),+}));++const { collectChangeAnchors, watchPierreShadowRoots } = await import('./diff-change-nav');+const { ActivityPanelDiffView } = await import('@/components/ActivityPanelDiffView');+const { AgentDiffPane } = await import('@/components/AgentDiffPane');+const { TooltipProvider } = await import('@/components/ui/tooltip');++const SIMPLE_BEFORE = 'line one\nline two\noriginal line\nline four\nline five\n';+const SIMPLE_AFTER = 'line one\nline two\nchanged line\nline four\nline five\n';++const TWO_GROUP_BEFORE = 'line 1\noriginal A\nline 3\nline 4\noriginal B\nline 6\n';+const TWO_GROUP_AFTER = 'line 1\nchanged A\nline 3\nline 4\nchanged B\nline 6\n';++const ADJACENT_BEFORE = 'line 1\noriginal A\noriginal B\nline 4\n';+const ADJACENT_AFTER = 'line 1\nchanged A\nchanged B\nline 4\n';++async function settle(n = 2) {+ for (let i = 0; i < n; i++) {+ await act(async () => {+ await new Promise<void>((resolve) => setTimeout(resolve, 0));+ });+ }+}++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+});++describe('watchPierreShadowRoots — mutations Pierre makes inside the shadow root', () => {+ test('fires for a shadow-root mutation that a light-DOM observer cannot see', async () => {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const host = document.createElement('diffs-container');+ container.appendChild(host);+ const shadow = host.shadowRoot ?? host.attachShadow({ mode: 'open' });++ let lightHits = 0;+ const lightObserver = new MutationObserver(() => {+ lightHits += 1;+ });+ lightObserver.observe(container, { childList: true, subtree: true });++ let watcherHits = 0;+ const watcher = watchPierreShadowRoots(container, () => {+ watcherHits += 1;+ });+ watcher.sync();++ shadow.appendChild(document.createElement('span'));+ await waitFor(() => expect(watcherHits).toBeGreaterThan(0));+ expect(lightHits).toBe(0);++ watcher.disconnect();+ const hitsAtDisconnect = watcherHits;+ shadow.appendChild(document.createElement('span'));+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(watcherHits).toBe(hitsAtDisconnect);++ lightObserver.disconnect();+ container.remove();+ });++ test('sync is idempotent — a second call does not double-observe a shadow root', async () => {+ const container = document.createElement('div');+ document.body.appendChild(container);+ const host = document.createElement('diffs-container');+ container.appendChild(host);+ const shadow = host.shadowRoot ?? host.attachShadow({ mode: 'open' });++ let hits = 0;+ const watcher = watchPierreShadowRoots(container, () => {+ hits += 1;+ });+ watcher.sync();+ watcher.sync();++ shadow.appendChild(document.createElement('span'));+ await waitFor(() => expect(hits).toBe(1));++ watcher.disconnect();+ container.remove();+ });+});++describe('collectChangeAnchors — shadow root piercing', () => {+ test('returns empty for unchanged before/after (no Pierre rows)', async () => {+ const { container } = render(+ <ActivityPanelDiffView before="same\n" after="same\n" cacheKey="doc@v1" />,+ );+ await settle();+ expect(collectChangeAnchors(container)).toHaveLength(0);+ });++ test('finds change rows inside the Pierre shadow root for a changed diff', async () => {+ const { container } = render(+ <ActivityPanelDiffView before={SIMPLE_BEFORE} after={SIMPLE_AFTER} cacheKey="doc@v1" />,+ );+ await pierreShadow(container);+ const anchors = collectChangeAnchors(container);+ expect(anchors.length).toBeGreaterThan(0);+ for (const anchor of anchors) {+ expect(anchor.getRootNode()).toBeInstanceOf(ShadowRoot);+ }+ });++ test('each anchor is the first row of a consecutive changed-row run', async () => {+ const { container } = render(+ <ActivityPanelDiffView before={TWO_GROUP_BEFORE} after={TWO_GROUP_AFTER} cacheKey="doc@v1" />,+ );+ await pierreShadow(container);+ const anchors = collectChangeAnchors(container);+ expect(anchors.length).toBeGreaterThanOrEqual(2);+ });++ test('adjacent changed rows are grouped into a single anchor', async () => {+ const { container } = render(+ <ActivityPanelDiffView before={ADJACENT_BEFORE} after={ADJACENT_AFTER} cacheKey="doc@v1" />,+ );+ await pierreShadow(container);+ const anchors = collectChangeAnchors(container);+ expect(anchors).toHaveLength(1);+ });+});++describe('child combinator selector — 2× vs N rows', () => {+ test('naive [data-line-type] selector returns 2× what the scoped selector returns', async () => {+ const { container } = render(+ <ActivityPanelDiffView before={SIMPLE_BEFORE} after={SIMPLE_AFTER} cacheKey="doc@v1" />,+ );+ const root = await pierreShadow(container);++ const naiveAdditions = root.querySelectorAll('[data-line-type="change-addition"]').length;+ const scopedAdditions = root.querySelectorAll(+ '[data-content] > [data-line-type="change-addition"]',+ ).length;++ expect(naiveAdditions).toBeGreaterThan(0);+ expect(scopedAdditions).toBeGreaterThan(0);+ expect(naiveAdditions).toBe(scopedAdditions * 2);++ expect(collectChangeAnchors(container)).toHaveLength(scopedAdditions);+ });+});++describe('data-line-type canary', () => {+ test('a known fixture yields at least one change-addition and change-deletion in the shadow root', async () => {+ const { container } = render(+ <ActivityPanelDiffView before={SIMPLE_BEFORE} after={SIMPLE_AFTER} cacheKey="doc@v1" />,+ );+ const root = await pierreShadow(container);+ expect(+ root.querySelector('[data-content] > [data-line-type="change-addition"]'),+ ).not.toBeNull();+ expect(+ root.querySelector('[data-content] > [data-line-type="change-deletion"]'),+ ).not.toBeNull();+ });+});++describe('AgentDiffPane scroll-to-first-change via Pierre', () => {+ const view = {+ agentId: 'agent-1',+ agentName: 'Agent',+ agentColor: '#888888',+ docName: 'notes',+ keptCount: 1,+ maxVersions: 3,+ };++ test('scrollIntoView is called on a Pierre change row after the settle sequence', async () => {+ const scrolled: HTMLElement[] = [];+ vi.spyOn(HTMLElement.prototype, 'scrollIntoView').mockImplementation(function (+ this: HTMLElement,+ ) {+ scrolled.push(this);+ });++ render(+ <TooltipProvider>+ <AgentDiffPane view={view} isPanelCollapsed={false} onTogglePanel={() => {}} />+ </TooltipProvider>,+ );++ await waitFor(+ () => {+ const pierreRow = scrolled.find((el) =>+ el.matches('[data-line-type="change-addition"], [data-line-type="change-deletion"]'),+ );+ expect(pierreRow).toBeDefined();+ },+ { timeout: 5000 },+ );+ });+});diff --git a/packages/app/src/lib/diff-change-nav.ts b/packages/app/src/lib/diff-change-nav.tsindex 43c499e8f..8506721d7 100644--- a/packages/app/src/lib/diff-change-nav.ts+++ b/packages/app/src/lib/diff-change-nav.ts@@ -1,26 +1,51 @@export const PROPERTY_CHANGE_ANCHOR_SELECTOR = '[data-property-change]';-export function countChangeGroups(diff: string): number {- let count = 0;- let inChange = false;- for (const line of diff.split('\n')) {- const isChange =- (line.startsWith('+') && !line.startsWith('+++')) ||- (line.startsWith('-') && !line.startsWith('---'));- if (isChange && !inChange) count += 1;- inChange = isChange;+const PIERRE_CHANGE_ROW_SELECTOR =+ '[data-content] > [data-line-type="change-addition"], [data-content] > [data-line-type="change-deletion"]';++function collectPierreChangeRows(container: HTMLElement): HTMLElement[] {+ const rows: HTMLElement[] = [];+ for (const host of container.querySelectorAll('diffs-container')) {+ const root = (host as HTMLElement).shadowRoot;+ if (!root) continue;+ rows.push(...root.querySelectorAll<HTMLElement>(PIERRE_CHANGE_ROW_SELECTOR));}- return count;+ return rows;+}++export interface PierreShadowWatcher {+ sync(): void;+ disconnect(): void;+}++export function watchPierreShadowRoots(+ container: HTMLElement,+ onMutation: () => void,+): PierreShadowWatcher {+ const observers = new Map<ShadowRoot, MutationObserver>();+ return {+ sync(): void {+ for (const host of container.querySelectorAll('diffs-container')) {+ const root = (host as HTMLElement).shadowRoot;+ if (root === null || observers.has(root)) continue;+ const observer = new MutationObserver(onMutation);+ observer.observe(root, { childList: true, subtree: true });+ observers.set(root, observer);+ }+ },+ disconnect(): void {+ for (const observer of observers.values()) observer.disconnect();+ observers.clear();+ },+ };}export function collectChangeAnchors(container: HTMLElement): Element[] {- const cells = Array.from(container.querySelectorAll('.diff-code-insert, .diff-code-delete'));+ const rows = collectPierreChangeRows(container);const anchors: Element[] = [];let prevRow: Element | null = null;- for (const cell of cells) {- const row = cell.closest('tr');- if (!row) continue;- if (prevRow === null || row.previousElementSibling !== prevRow) anchors.push(cell);+ for (const row of rows) {+ if (prevRow === null || row.previousElementSibling !== prevRow) anchors.push(row);prevRow = row;}return anchors;diff --git a/packages/app/src/test-utils/pierre-shadow.ts b/packages/app/src/test-utils/pierre-shadow.tsnew file mode 100644index 000000000..e7d745d8f--- /dev/null+++ b/packages/app/src/test-utils/pierre-shadow.ts@@ -0,0 +1,16 @@+import { waitFor } from '@testing-library/react';++const PIERRE_CONTENT_ROW_SELECTOR = '[data-content] [data-line]';++export async function pierreShadow(container: HTMLElement): Promise<ShadowRoot> {+ await waitFor(+ () => {+ const root = container.querySelector('diffs-container')?.shadowRoot;+ if (root?.querySelector(PIERRE_CONTENT_ROW_SELECTOR) == null) {+ throw new Error('Pierre has not painted any content rows into the shadow root yet');+ }+ },+ { timeout: 5_000 },+ );+ return container.querySelector('diffs-container')?.shadowRoot as ShadowRoot;+}diff --git a/packages/app/tests/lint-plugins/no-themeless-pierre-diff.test.ts b/packages/app/tests/lint-plugins/no-themeless-pierre-diff.test.tsnew file mode 100644index 000000000..bdc642f2c--- /dev/null+++ b/packages/app/tests/lint-plugins/no-themeless-pierre-diff.test.ts@@ -0,0 +1,45 @@+import { spawnSync } from 'node:child_process';+import { join } from 'node:path';+import { describe, expect, test } from 'vitest';+import { readBiomeConfig } from '../../../../test-support/read-biome-config.test-helper';++const REPO_ROOT = join(__dirname, '..', '..', '..', '..');+const FIXTURE_REL = 'biome-plugins/__fixtures__/no-themeless-pierre-diff.fixture.tsx';++describe('no-themeless-pierre-diff GritQL plugin', () => {+ test('fires on exactly 7 positive cases (and on no negative case)', () => {+ const result = spawnSync('pnpm', ['exec', 'biome', 'check', FIXTURE_REL], {+ cwd: REPO_ROOT,+ encoding: 'utf-8',+ });+ expect(result.status).not.toBe(0);+ const output = `${result.stdout}\n${result.stderr}`;+ const fires = (output.match(/@pierre\/diffs render contract/g) ?? []).length;+ expect(fires).toBe(7);+ const themeFires = (output.match(/add `theme: okPierreTheme\(\)`/g) ?? []).length;+ const styleFires = (output.match(/does not set diffStyle: 'unified'/g) ?? []).length;+ expect(themeFires).toBe(5);+ expect(styleFires).toBe(2);+ expect(output).toMatch(/https?:\/\/[^\s]+/);+ expect(output).toContain('biome-plugins/README.md#no-themeless-pierre-diffgrit');+ });++ test('plugin is registered in biome.jsonc via overrides (not root plugins)', () => {+ const config = readBiomeConfig(REPO_ROOT);++ const rootPlugins = config.plugins ?? [];+ expect(rootPlugins).not.toContain('./biome-plugins/no-themeless-pierre-diff.grit');++ const overrides = config.overrides ?? [];+ const matchingOverride = overrides.find((entry) =>+ (entry.plugins ?? []).includes('./biome-plugins/no-themeless-pierre-diff.grit'),+ );+ expect(matchingOverride).toBeDefined();++ const includes = matchingOverride?.includes ?? [];+ expect(includes).toContain('packages/app/src/**/*.tsx');+ expect(includes).toContain('!**/*.test.tsx');+ expect(includes).toContain('!**/*.dom.test.tsx');+ expect(includes).toContain('biome-plugins/__fixtures__/no-themeless-pierre-diff.fixture.tsx');+ });+});diff --git a/packages/app/tests/stress/agent-activity-panel.e2e.ts b/packages/app/tests/stress/agent-activity-panel.e2e.tsindex 3b36a9300..774402021 100644--- a/packages/app/tests/stress/agent-activity-panel.e2e.ts+++ b/packages/app/tests/stress/agent-activity-panel.e2e.ts@@ -1,3 +1,4 @@+import AxeBuilder from '@axe-core/playwright';import { expect, test, waitForActiveProviderSynced as waitForProvider } from './_helpers';function agentId(label: string): string {@@ -224,4 +225,85 @@ test.describe('Activity mode (DocPanel) — avatar drill-in, back-arrow exit', (const backButton = page.locator('[data-testid="docpanel-exit-agent-mode"]');await expect(backButton).toBeVisible();});++ test('axe scan of the Source diff surface in a real browser', async ({ page, api }) => {+ const docView = 'panel-a11y-view';+ const docAgent = 'panel-a11y-agent';+ await api.seedDocs([+ { name: docView, markdown: '# View\n\nSome content here.' },+ {+ name: docAgent,+ markdown:+ '# Agent Doc\n\nOriginal paragraph with initial text content that will be changed.',+ },+ ]);+ await page.goto(`/#/${docView}`);+ await waitForProvider(page);++ const claude = agentId('claude-a11y');+ await api.writeAsAgent(+ docAgent,+ '# Agent Doc\n\nOriginal paragraph with modified text content that was changed.',+ { agentId: claude, agentName: 'Claude A11Y', clientName: 'claude-code' },+ );++ const claudeAvatar = page+ .locator(+ '[data-slot="presence-bar"] [data-presence-badge="agent"][aria-label*="Claude A11Y"]',+ )+ .first();+ await expect(claudeAvatar).toBeVisible({ timeout: 10_000 });+ await claudeAvatar.click();++ const panel = page.locator('[data-testid="activity-panel"]');+ await expect(panel).toBeVisible({ timeout: 5_000 });++ const row = panel.locator('[data-testid="activity-panel-file-row"]').first();+ const burst = row.locator('[data-testid="activity-panel-burst-open"]').first();+ await expect(burst).toBeVisible({ timeout: 5_000 });+ await burst.click();++ const diffPane = page.locator('[data-testid="agent-diff-pane"]');+ await expect(diffPane).toBeVisible({ timeout: 5_000 });++ const sourceToggle = diffPane.locator('[data-testid="agent-diff-render-source"]');+ await expect(sourceToggle).toBeVisible({ timeout: 3_000 });+ await sourceToggle.click();++ const pierreHost = diffPane.locator('.activity-panel-diff diffs-container');+ await expect(pierreHost).toBeVisible({ timeout: 10_000 });+ expect(await pierreHost.evaluate((el) => getComputedStyle(el).display)).toBe('block');++ const hostDisplay = await diffPane+ .locator('.activity-panel-diff diffs-container')+ .evaluate((el) => getComputedStyle(el).display);+ expect(+ hostDisplay,+ 'Pierre host must be display:block. @pierre/diffs sets no display on :host, so a custom element defaults to inline and drops width/padding/block layout. If this fails after a Pierre bump, check whether upstream started setting it before deleting the app rule.',+ ).toBe('block');++ const axeResults = await new AxeBuilder({ page })+ .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])+ .include('[data-testid="agent-diff-pane"]')+ .analyze();++ await test.info().attach('axe.json', {+ body: JSON.stringify(axeResults, null, 2),+ contentType: 'application/json',+ });++ const MEASURED_NODE_BUDGET: Record<string, number> = {+ 'color-contrast': 2,+ 'scrollable-region-focusable': 0,+ };++ for (const v of axeResults.violations) {+ const ceiling = MEASURED_NODE_BUDGET[v.id];+ expect(ceiling, `unexpected axe rule '${v.id}': ${v.help}`).toBeDefined();+ expect(+ v.nodes.length,+ `'${v.id}' node count ${v.nodes.length} exceeds the measured baseline of ${ceiling}`,+ ).toBeLessThanOrEqual(ceiling);+ }+ });});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 7fd349f66..ea7b5c257 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -627,9 +627,6 @@ importers:react-day-picker:specifier: ^9.14.0version: 9.14.0([email protected])- react-diff-view:- specifier: ^3.3.3- version: 3.3.3([email protected])react-dom:specifier: 19.2.5version: 19.2.5([email protected])@@ -6760,9 +6757,6 @@ packages:resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==}- resolution: {integrity: sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==}-resolution: {integrity: sha512-5IOn+jcCEHEraYolBPs/sT4BxYCe2nHg374OPiItB1O96KZFseS2gthU4twyYzeDcFew4DaUM/xwc5BQf08JJw==}engines: {node: '>=18.20 <19 || >=20.10'}@@ -8053,9 +8047,6 @@ packages:resolution: {integrity: sha512-b1O07XYq8eRuVzBNgJLstU6FYc1tS6wnMtF1I1D9lE8LxZSOGZ7LhxN54yPP6mGw5f2CkXY2BQUL9Fx41qvcIg==}engines: {node: '>= 14'}- resolution: {integrity: sha512-YQJnY8aew65id8okGxKCksH3efDCJ9HzV7M9rsvd65habf39Pkh4cgYJ27AaoDMqo1X98pgNJhNMrm/kpV7UVQ==}-resolution: {integrity: sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==}@@ -10070,11 +10061,6 @@ packages:peerDependencies:react: 19.2.5- resolution: {integrity: sha512-CPveApk6n7ZbkW7T6PoptR7LWAvD9hohTHZ7WnKnu3GZkTfUB5rvg486apPo94iYVi4fZd3Nt+rtBZ5877exoQ==}- peerDependencies:- react: 19.2.5-resolution: {integrity: sha512-J5bAZz+DXMMwW/wV3xzKke59Af6CHY7G4uYLN1OvBcKEsWOs4pQExj86BBKamxl/Ik5bx9whOrvBlSDfWzgSag==}peerDependencies:@@ -10565,9 +10551,6 @@ packages:engines: {node: '>=20.18.1'}hasBin: true- resolution: {integrity: sha512-pfVOw8QZIXpMbhBWvzBISicvToTiM5WBF1EeAUZDDSb5Dt29yl4AYbyywbJFSEsRUMr7gJaxqCdr4L3tQf9wVg==}-resolution: {integrity: sha512-ej0zVHuZGHCiABXcNxeYhpRnPNPAcvbG8RMdBAhDAxLKkCRVSpK3Iyu7qbqw3JMzoj0REeM6f3tJLtVwl0023Q==}engines: {node: '>=20.9.0'}@@ -11447,9 +11430,6 @@ packages:resolution: {integrity: sha512-3hu+tD8YzSLGuFYtPRb48vdhKMi0KQV5sn+uWr8+7dMEq/2G/dtLrdDinkLjqq5TIbIBjYJ4Ax/n3YiaW7QM8A==}engines: {node: 20 || >=22}- resolution: {integrity: sha512-rpJyN222KWIvHJ/F53XSZv0Zl/accqHR8et1kpaMTD/fLCRxtV8iX8czMzY7sVZupTI3zcUTg8eycS2kNF9l6w==}-resolution: {integrity: sha512-ZzxBf288iALJseijWelmECm/1x7ZwQn3sMYIkDr2VvZp7r6SEKuT8D0O9Wiq6L9Nl5mazrOMcmiZE/2NCenaxw==}engines: {node: '>=8.10.0'}@@ -17144,8 +17124,6 @@ snapshots:dependencies:clsx: 2.1.1- [email protected]: {}-@@ -18663,8 +18641,6 @@ snapshots:transitivePeerDependencies:- supports-color- [email protected]: {}-optional: true@@ -21334,16 +21310,6 @@ snapshots:date-fns-jalali: 4.1.0-0react: 19.2.5- dependencies:- classnames: 2.5.1- diff-match-patch: 1.0.5- gitdiff-parser: 0.3.1- lodash: 4.18.1- react: 19.2.5- shallow-equal: 3.1.0- warning: 4.0.3-dependencies:react: 19.2.5@@ -22061,8 +22027,6 @@ snapshots:- supports-color- typescript- [email protected]: {}-[email protected](@types/[email protected]):dependencies:'@img/colour': 1.1.0@@ -23004,10 +22968,6 @@ snapshots:- dependencies:- loose-envify: 1.4.0-