Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Timeline version and agent activity diffs improvement (#2607)

shagun-singh-inkeep09a5ff9d7586
diff --git a/.changeset/rendered-timeline-diff.md b/.changeset/rendered-timeline-diff.md
new file mode 100644
index 000000000..bec91d587
--- /dev/null
+++ b/.changeset/rendered-timeline-diff.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Timeline version and agent activity diffs now render as formatted WYSIWYG documents with changes marked inline. A Source toggle keeps the raw markdown diff as well.
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 168d07c52..5b797cf08 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -599,6 +599,17 @@ Homepage: https://chevrotain.io/documentation/
_(LICENSE template present but no copyright line filled in; refer to the package source for canonical attribution.)_
+### `@fellow/[email protected]`
+
+_(LICENSE template present but no copyright line filled in; refer to the package source for canonical attribution.)_
+
+NOTICE:
+
+```
+prosemirror-recreate-steps
+Copyright 2018 Atypon Systems, LLC.
+```
+
### `@mongodb-js/[email protected]`
Homepage: https://github.com/mongodb-js/zstd
@@ -4921,6 +4932,11 @@ Homepage: https://github.com/mcollina/reusify#readme
Copyright (c) 2015-2024 Matteo Collina
+Homepage: https://github.com/chbrown/rfc6902
+
+_(No LICENSE file in package; SPDX identifier in `package.json` is the sole declared grant.)_
+
Homepage: https://github.com/marijnh/rope-sequence
@@ -5969,6 +5985,11 @@ Homepage: https://github.com/kpdecker/jsdiff
Copyright (c) 2009-2015, Kevin Decker <[email protected]>
+Homepage: https://github.com/kpdecker/jsdiff
+
+Copyright (c) 2009-2015, Kevin Decker <[email protected]>
+
Homepage: https://github.com/fastify/fast-uri
diff --git a/packages/app/package.json b/packages/app/package.json
index b1feded27..10f4855e2 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -45,7 +45,7 @@
{
"name": "main app bundle (gzipped)",
"path": "dist/assets/index-*.js",
- "limit": "480 kB",
+ "limit": "482 kB",
"gzip": true,
"running": false
},
@@ -85,6 +85,7 @@
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
+ "@fellow/prosemirror-recreate-transform": "^1.2.3",
"@floating-ui/dom": "^1.7.6",
"@fontsource-variable/inter": "^5.2.8",
"@fontsource-variable/jetbrains-mono": "^5.2.8",
diff --git a/packages/app/src/components/ActivityModeContent.tsx b/packages/app/src/components/ActivityModeContent.tsx
index 9bb62fe0c..d758138af 100644
--- a/packages/app/src/components/ActivityModeContent.tsx
+++ b/packages/app/src/components/ActivityModeContent.tsx
@@ -22,11 +22,14 @@
import { t } from '@lingui/core/macro';
import { Plural, Trans, useLingui } from '@lingui/react/macro';
import { AlertCircle, ArrowLeft, Loader2 } from 'lucide-react';
-import { useState } from 'react';
+import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { withLargeFileOpenGuard } from '@/components/navigation-targets';
import { usePageList } from '@/components/PageListContext';
import { useDocumentContext, useDocumentTransition } from '@/editor/DocumentContext';
+import { openAgentDiff, setAgentDiffMax } from '@/lib/agent-diff-store';
+import { closeTimelineDiff } from '@/lib/timeline-diff-store';
+import type { FileData } from '@/lib/use-activity-panel';
import { useActivityPanel } from '@/lib/use-activity-panel';
import { ActivityPanelFileRow } from './ActivityPanelFileRow';
import { AgentIcon } from './icons/AgentIcon';
@@ -40,7 +43,9 @@ import { Tooltip, TooltipContent, TooltipTrigger } from './ui/tooltip';
async function postAgentUndo(body: {
connectionId: string;
docName: string;
- scope: 'last' | 'file';
+ scope: 'last' | 'file' | 'count';
+ /** Required when scope is `'count'` — the number of newest edits to drop. */
+ count?: number;
agentName?: string;
}): Promise<void> {
const res = await fetch('/api/agent-undo', {
@@ -247,11 +252,10 @@ interface ActivityModeBodyProps {
status: ReturnType<typeof useActivityPanel>['status'];
error: ReturnType<typeof useActivityPanel>['error'];
reload: () => void;
- fetchBurstDiff: (docName: string, stackIndex: number) => Promise<string>;
onExit: () => void;
onNavigate: (docName: string) => void;
- onUndoLast: (docName: string) => Promise<void>;
- onUndoAll: (docName: string) => Promise<void>;
+ onUndoDrop: (docName: string, dropCount: number) => Promise<void>;
+ onSetVersion: (file: FileData, keptCount: number) => void;
showBackButton: boolean;
}
@@ -260,11 +264,10 @@ function ActivityModeBody({
status,
error,
reload,
- fetchBurstDiff,
onExit,
onNavigate,
- onUndoLast,
- onUndoAll,
+ onUndoDrop,
+ onSetVersion,
showBackButton,
}: ActivityModeBodyProps): React.JSX.Element {
const { t } = useLingui();
@@ -337,9 +340,8 @@ function ActivityModeBody({
sessionAlive={data.sessionAlive}
isWriting={data.writingDocs.has(file.docName)}
onNavigate={onNavigate}
- onUndoLast={onUndoLast}
- onUndoAll={onUndoAll}
- fetchBurstDiff={fetchBurstDiff}
+ onUndoDrop={onUndoDrop}
+ onSetVersion={(keptCount) => onSetVersion(file, keptCount)}
/>
))
)}
@@ -363,7 +365,19 @@ export function ActivityModeContent({
const { docPanelAgentId, closeActivityPanel } = useDocumentContext();
const { openTargetTransition } = useDocumentTransition();
const { pageMeta } = usePageList();
- const { data, status, error, reload, fetchBurstDiff } = useActivityPanel(docPanelAgentId);
+ const { data, status, error, reload } = useActivityPanel(docPanelAgentId);
+
+ // Keep an open diff pane's version ceiling in sync with live activity — the
+ // panel re-fetches on the CC1 `session-activity` signal, so pushing the fresh
+ // edit count into the store lets a new burst extend the pane's version range
+ // (and follow "now") without reopening. Placed before the early return below
+ // so hook order stays stable. No-op unless a diff for the open file is up.
+ useEffect(() => {
+ if (!data || docPanelAgentId === null) return;
+ for (const file of data.files) {
+ setAgentDiffMax(docPanelAgentId, file.docName, file.bursts.length);
+ }
+ }, [data, docPanelAgentId]);
// When mode is `'agent'` but no agent is scoped (edge case: user flipped
// mode without ever clicking an avatar), render a discoverable hint rather
@@ -380,40 +394,50 @@ export function ActivityModeContent({
navigateToDoc(docName);
};
- const onUndoLast = async (docName: string): Promise<void> => {
- try {
- await postAgentUndo({
- connectionId: docPanelAgentId,
- docName,
- scope: 'last',
- agentName: data?.agent?.displayName,
- });
- reload();
- } catch (err) {
- // Surface the failure — `Undo all` has a confirmation dialog, but
- // `Undo last` is inline. Either silently failing is user-hostile.
- const message = err instanceof Error ? err.message : String(err);
- toast.error(t`Undo failed: ${message}`);
- // Non-fatal — re-fetch to recover ground truth.
- reload();
- }
+ // Show a file version in the main pane. `keptCount` selects the version
+ // (0 = original, file.bursts.length = now). Drives the pane from the file
+ // row's undo slider, its header icons, and burst-row clicks. EditorArea
+ // navigates the editor to the file's doc and paints the pane once nav settles.
+ const onSetVersion = (file: FileData, keptCount: number): void => {
+ if (!data?.agent || docPanelAgentId === null) return;
+ // The two full-pane diffs share one overlay slot — close the timeline diff
+ // so they can't both paint.
+ closeTimelineDiff();
+ const max = file.bursts.length;
+ openAgentDiff({
+ agentId: docPanelAgentId,
+ agentName: data.agent.displayName,
+ agentColor: data.agent.color,
+ agentIcon: data.agent.icon,
+ docName: file.docName,
+ keptCount: Math.max(0, Math.min(keptCount, max)),
+ maxVersions: max,
+ });
};
- const onUndoAll = async (docName: string): Promise<void> => {
+ // Scoped undo from the file-row timeline: drop the `dropCount` newest edits.
+ // The timeline already surfaced the range (and the doomed-edit preview), so
+ // this just commits it and re-fetches ground truth.
+ const onUndoDrop = async (docName: string, dropCount: number): Promise<void> => {
+ if (dropCount <= 0) return;
try {
await postAgentUndo({
connectionId: docPanelAgentId,
docName,
- scope: 'file',
+ scope: 'count',
+ count: dropCount,
agentName: data?.agent?.displayName,
});
- // `Undo all` has a confirmation dialog — the blast-radius asymmetry
- // applies to feedback too.
- toast.success(t`Undone all edits on ${docName}`);
+ toast.success(
+ dropCount === 1
+ ? t`Undid the last edit on ${docName}`
+ : t`Undid ${dropCount} edits on ${docName}`,
+ );
reload();
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
- toast.error(t`Undo all failed: ${message}`);
+ toast.error(t`Undo failed: ${message}`);
+ // Non-fatal — re-fetch to recover ground truth.
reload();
}
};
@@ -424,11 +448,10 @@ export function ActivityModeContent({
status={status}
error={error}
reload={reload}
- fetchBurstDiff={fetchBurstDiff}
onExit={closeActivityPanel}
onNavigate={onNavigate}
- onUndoLast={onUndoLast}
- onUndoAll={onUndoAll}
+ onUndoDrop={onUndoDrop}
+ onSetVersion={onSetVersion}
showBackButton={showBackButton}
/>
);
diff --git a/packages/app/src/components/ActivityPanelBurstRow.test.tsx b/packages/app/src/components/ActivityPanelBurstRow.test.tsx
index c65ca539e..dc7c81bb1 100644
--- a/packages/app/src/components/ActivityPanelBurstRow.test.tsx
+++ b/packages/app/src/components/ActivityPanelBurstRow.test.tsx
@@ -1,31 +1,41 @@
/**
* ActivityPanelBurstRow unit tests — static HTML shape via renderToString.
- * Lazy-diff-load behavior (click → fetch → render) is exercised in Playwright.
+ * Click-to-open (row → full-pane AgentDiffPane) and the Restore confirm flow
+ * are exercised in Playwright.
*/
import { describe, expect, test } from 'bun:test';
import { renderToString } from 'react-dom/server';
+import { TooltipProvider } from '@/components/ui/tooltip';
import { ActivityPanelBurstRow } from './ActivityPanelBurstRow';
+function render(ui: React.ReactElement): string {
+ return renderToString(<TooltipProvider>{ui}</TooltipProvider>);
+}
+
describe('ActivityPanelBurstRow (static render)', () => {
- test('renders diff stats + relative timestamp; no diff visible until expanded', () => {
- const html = renderToString(
+ test('renders diff stats + relative timestamp; diff is not rendered inline', () => {
+ const html = render(
<ActivityPanelBurstRow
burst={{ stackIndex: 3, ts: Date.now() - 15_000, additions: 7, deletions: 3 }}
docName="notes.md"
- fetchBurstDiff={async () => ''}
+ editCount={5}
+ sessionAlive={true}
+ inFlight={false}
+ onOpenDiff={() => {}}
+ onRestore={() => {}}
/>,
);
const stripped = html.replaceAll('<!-- -->', '');
expect(stripped).toContain('+7');
expect(stripped).toContain('−3');
expect(html).toContain('s ago');
- // Collapsed by default — diff body should NOT be present yet.
+ // The diff opens in the main pane, not inline in this narrow panel.
expect(html).not.toContain('Loading diff');
expect(html).not.toContain('activity-panel-diff');
});
test('absolute HH:MM format shows for bursts older than one hour', () => {
- const html = renderToString(
+ const html = render(
<ActivityPanelBurstRow
burst={{
stackIndex: 0,
@@ -34,7 +44,11 @@ describe('ActivityPanelBurstRow (static render)', () => {
deletions: 0,
}}
docName="x.md"
- fetchBurstDiff={async () => ''}
+ editCount={3}
+ sessionAlive={true}
+ inFlight={false}
+ onOpenDiff={() => {}}
+ onRestore={() => {}}
/>,
);
// 3h ago → relative "m ago" / "h ago" logic. We accept either the hour
@@ -42,14 +56,73 @@ describe('ActivityPanelBurstRow (static render)', () => {
expect(html.includes('h ago') || /\d\d:\d\d/.test(html)).toBe(true);
});
- test('aria-expanded reflects collapsed state', () => {
- const html = renderToString(
+ test('row exposes aria-pressed for the active-diff highlight', () => {
+ const html = render(
<ActivityPanelBurstRow
burst={{ stackIndex: 1, ts: Date.now(), additions: 0, deletions: 0 }}
docName="y.md"
- fetchBurstDiff={async () => ''}
+ editCount={3}
+ sessionAlive={true}
+ inFlight={false}
+ onOpenDiff={() => {}}
+ onRestore={() => {}}
+ />,
+ );
+ // No diff open in the store during SSR → not pressed.
+ expect(html).toContain('aria-pressed="false"');
+ });
+
+ test('exposes a per-row Restore control, enabled when newer edits exist and the session is alive', () => {
+ // burstNumber = stackIndex + 1 = 2; editCount 5 → 3 newer edits to undo.
+ const html = render(
+ <ActivityPanelBurstRow
+ burst={{ stackIndex: 1, ts: Date.now(), additions: 2, deletions: 0 }}
+ docName="notes.md"
+ editCount={5}
+ sessionAlive={true}
+ inFlight={false}
+ onOpenDiff={() => {}}
+ onRestore={() => {}}
+ />,
+ );
+ const idx = html.indexOf('data-testid="activity-panel-burst-restore"');
+ expect(idx).toBeGreaterThan(-1);
+ expect(html).toContain('aria-label="Restore to edit 2 of notes.md"');
+ expect(html.slice(idx, idx + 300)).not.toContain('disabled');
+ });
+
+ test('Restore is disabled on the newest burst (nothing newer to undo)', () => {
+ // stackIndex 4 → burstNumber 5 === editCount 5 → 0 newer edits.
+ const html = render(
+ <ActivityPanelBurstRow
+ burst={{ stackIndex: 4, ts: Date.now(), additions: 1, deletions: 0 }}
+ docName="notes.md"
+ editCount={5}
+ sessionAlive={true}
+ inFlight={false}
+ onOpenDiff={() => {}}
+ onRestore={() => {}}
+ />,
+ );
+ const idx = html.indexOf('data-testid="activity-panel-burst-restore"');
+ expect(idx).toBeGreaterThan(-1);
+ expect(html.slice(idx, idx + 300)).toContain('disabled');
+ });
+
+ test('Restore is disabled when the session has ended', () => {
+ const html = render(
+ <ActivityPanelBurstRow
+ burst={{ stackIndex: 0, ts: Date.now(), additions: 1, deletions: 0 }}
+ docName="notes.md"
+ editCount={5}
+ sessionAlive={false}
+ inFlight={false}
+ onOpenDiff={() => {}}
+ onRestore={() => {}}
/>,
);
- expect(html).toContain('aria-expanded="false"');
+ const idx = html.indexOf('data-testid="activity-panel-burst-restore"');
+ expect(idx).toBeGreaterThan(-1);
+ expect(html.slice(idx, idx + 300)).toContain('disabled');
});
});
diff --git a/packages/app/src/components/ActivityPanelBurstRow.tsx b/packages/app/src/components/ActivityPanelBurstRow.tsx
index e5e51baee..a2f13dfdf 100644
--- a/packages/app/src/components/ActivityPanelBurstRow.tsx
+++ b/packages/app/src/components/ActivityPanelBurstRow.tsx
@@ -1,27 +1,45 @@
-// biome-ignore-all lint/plugin/no-raw-html-interactive-element: pre-rule backlog — file uses raw <button> awaiting shadcn Button migration; tracked at https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-raw-html-interactive-elementgrit
+// biome-ignore-all lint/plugin/no-raw-html-interactive-element: pre-rule backlog — the diff-open row target is a raw <button> awaiting shadcn migration; the Restore action already uses shadcn Button. Tracked at https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-raw-html-interactive-elementgrit
/**
- * ActivityPanelBurstRow — one burst (StackItem) inside an expanded file
- * row. Shows {relative timestamp, `+N −M` diff stat, optional summary},
- * and lazy-loads the unified-diff mini hunk on click.
+ * ActivityPanelBurstRow — one burst (StackItem) inside a file's always-expanded
+ * edit list. Shows {relative timestamp, `+N −M` diff stat} and a per-row
+ * Restore (↩) action, mirroring the document Timeline's per-row restore.
*
- * Bursts are display-only — no undo action button here; undo lives on the
- * file-row action area.
+ * Clicking the row opens the burst's diff in the main editor pane (full-pane
+ * overlay, `AgentDiffPane`). The Restore action undoes every edit newer than
+ * this burst on this file (i.e. restores the file to this version); it is
+ * disabled on the newest burst (nothing newer to undo) and when the session has
+ * ended. The row is highlighted while its diff is the one open in the pane.
*/
import { t } from '@lingui/core/macro';
-import { Trans, useLingui } from '@lingui/react/macro';
-import { ChevronDown, ChevronRight } from 'lucide-react';
-import { lazy, Suspense, useEffect, useState } from 'react';
+import { Plural, Trans, useLingui } from '@lingui/react/macro';
+import { Loader2, Undo2 } from 'lucide-react';
+import { useEffect, useState } from 'react';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { useAgentDiffView } from '@/lib/agent-diff-store';
import type { BurstData } from '@/lib/use-activity-panel';
-const LazyActivityPanelDiffView = lazy(async () => {
- const mod = await import('./ActivityPanelDiffView');
- return { default: mod.ActivityPanelDiffView };
-});
-
interface ActivityPanelBurstRowProps {
burst: BurstData;
docName: string;
- fetchBurstDiff: (docName: string, stackIndex: number) => Promise<string>;
+ /** Total applied edits on this file — used to count how many are newer. */
+ editCount: number;
+ /** Undo unavailable (session ended). */
+ sessionAlive: boolean;
+ /** An undo is currently committing on this file — freezes the Restore control. */
+ inFlight: boolean;
+ /** Open this burst's diff in the main editor pane. */
+ onOpenDiff: (burst: BurstData) => void;
+ /** Restore to this burst: drop the `laterEdits` newer edits on this file. */
+ onRestore: (laterEdits: number) => void;
}
function formatRelative(ms: number, now: number): string {
@@ -42,13 +60,13 @@ function formatRelative(ms: number, now: number): string {
export function ActivityPanelBurstRow({
burst,
docName,
- fetchBurstDiff,
+ editCount,
+ sessionAlive,
+ inFlight,
+ onOpenDiff,
+ onRestore,
}: ActivityPanelBurstRowProps): React.JSX.Element {
const { t } = useLingui();
- const [expanded, setExpanded] = useState(false);
- const [diff, setDiff] = useState<string | null>(null);
- const [loadError, setLoadError] = useState<string | null>(null);
- const [loading, setLoading] = useState(false);
// React Compiler: `Date.now()` is impure — hoist behind useState + tick
// every 30 s so relative-timestamp labels stay fresh without violating
// render purity.
@@ -57,76 +75,116 @@ export function ActivityPanelBurstRow({
const id = setInterval(() => setNow(Date.now()), 30_000);
return () => clearInterval(id);
}, []);
+ const [dialogOpen, setDialogOpen] = useState(false);
- const toggle = (): void => {
- const next = !expanded;
- setExpanded(next);
- if (next && diff === null && !loading) {
- setLoading(true);
- setLoadError(null);
- fetchBurstDiff(docName, burst.stackIndex)
- .then((text) => {
- setDiff(text);
- setLoading(false);
- })
- .catch((err: unknown) => {
- setLoadError(err instanceof Error ? err.message : String(err));
- setLoading(false);
- });
- }
- };
-
+ // Highlight the burst whose diff is currently open in the main pane. The
+ // Activity panel is scoped to a single agent, so matching on doc + burst
+ // coordinate is sufficient to disambiguate. This burst's version is
+ // `stackIndex + 1` (edits applied up to and including it).
+ const activeDiff = useAgentDiffView();
const burstNumber = burst.stackIndex + 1;
+ const isActive = activeDiff?.docName === docName && activeDiff.keptCount === burstNumber;
+
+ // Edits newer than this burst — exactly what restoring to this version undoes.
+ const laterEdits = editCount - burstNumber;
+ const restoreDisabled = !sessionAlive || inFlight || laterEdits <= 0;
+
+ function commitRestore(): void {
+ setDialogOpen(false);
+ onRestore(laterEdits);
+ }
return (
- <div className="border-t border-border/50">
- <button
- type="button"
- onClick={toggle}
- className="flex w-full items-center gap-2 px-4 py-1.5 text-xs text-muted-foreground hover:bg-muted/40"
- aria-expanded={expanded}
- aria-label={
- expanded ? t`Collapse burst ${burstNumber} diff` : t`Expand burst ${burstNumber} diff`
- }
+ <>
+ <div className="flex items-center border-t border-border/50 pr-3">
+ <button
+ type="button"
+ onClick={() => onOpenDiff(burst)}
+ aria-pressed={isActive}
+ aria-label={t`View diff for edit ${burstNumber} of ${docName}`}
+ data-testid="activity-panel-burst-open"
+ className={[
+ 'flex min-w-0 flex-1 items-center gap-2 px-4 py-1.5 text-xs text-muted-foreground transition-colors',
+ isActive ? 'bg-muted' : 'hover:bg-muted/40',
+ ].join(' ')}
+ >
+ <span className="font-mono">{formatRelative(burst.ts, now)}</span>
+ <span className="ml-auto font-mono">
+ <span className="text-green-600 dark:text-green-400">+{burst.additions}</span>{' '}
+ <span className="text-red-600 dark:text-red-400">−{burst.deletions}</span>
+ </span>
+ </button>
+ {/* Visual separator anchors the destructive Restore action as its own region. */}
+ <span aria-hidden="true" className="mx-1.5 h-3 w-px shrink-0 bg-border" />
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="size-6 shrink-0 text-muted-foreground hover:text-destructive"
+ data-testid="activity-panel-burst-restore"
+ aria-label={t`Restore to edit ${burstNumber} of ${docName}`}
+ disabled={restoreDisabled}
+ onClick={() => setDialogOpen(true)}
+ >
+ {inFlight ? (
+ <Loader2 className="size-3 animate-spin" aria-hidden="true" />
+ ) : (
+ <Undo2 className="size-3" aria-hidden="true" />
+ )}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="left">
+ {!sessionAlive
+ ? t`Session ended — undo unavailable`
+ : laterEdits > 0
+ ? t`Restore to this edit`
+ : t`Latest edit`}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+
+ <Dialog
+ open={dialogOpen}
+ onOpenChange={(next) => {
+ if (!next && !inFlight) setDialogOpen(false);
+ else if (next) setDialogOpen(true);
+ }}
>
- {expanded ? (
- <ChevronDown className="size-3 shrink-0" aria-hidden="true" />
- ) : (
- <ChevronRight className="size-3 shrink-0" aria-hidden="true" />
- )}
- <span className="font-mono">{formatRelative(burst.ts, now)}</span>
- <span className="ml-auto font-mono">
- <span className="text-green-600 dark:text-green-400">+{burst.additions}</span>{' '}
- <span className="text-red-600 dark:text-red-400">−{burst.deletions}</span>
- </span>
- </button>
- {expanded ? (
- <div className="bg-muted/20">
- {loading ? (
- <div className="px-4 py-2 text-xs text-muted-foreground italic">
- <Trans>Loading diff</Trans>
- </div>
- ) : loadError ? (
- <div className="px-4 py-2 text-xs text-destructive">
- <Trans>Failed: {loadError}</Trans>
- </div>
- ) : diff !== null ? (
- <Suspense
- fallback={
- <div className="px-4 py-2 text-xs text-muted-foreground italic">
- <Trans>Loading diff</Trans>
- </div>
- }
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t`Undo to this edit?`}</DialogTitle>
+ <DialogDescription>
+ <Plural
+ value={laterEdits}
+ one="Removes # newer edit on this file."
+ other="Removes # newer edits on this file."
+ />
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button
+ variant="outline"
+ data-testid="activity-panel-burst-restore-cancel"
+ onClick={() => setDialogOpen(false)}
+ >
+ <Trans>Cancel</Trans>
+ </Button>
+ <Button
+ variant="destructive"
+ data-testid="activity-panel-burst-restore-confirm"
+ disabled={inFlight}
+ onClick={commitRestore}
>
- <LazyActivityPanelDiffView diff={diff} />
- </Suspense>
- ) : (
- <div className="px-4 py-2 text-xs text-muted-foreground italic">
- <Trans>No diff.</Trans>
- </div>
- )}
- </div>
- ) : null}
- </div>
+ {inFlight ? (
+ <Loader2 className="mr-2 size-4 animate-spin" aria-hidden="true" />
+ ) : null}
+ <Trans>Undo</Trans>
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </>
);
}
diff --git a/packages/app/src/components/ActivityPanelDiffView.tsx b/packages/app/src/components/ActivityPanelDiffView.tsx
index 7be5f5443..2ea4f2946 100644
--- a/packages/app/src/components/ActivityPanelDiffView.tsx
+++ b/packages/app/src/components/ActivityPanelDiffView.tsx
@@ -1,9 +1,9 @@
/**
* ActivityPanelDiffView — the single inline-diff renderer for the document
* panel side pane. Built on `react-diff-view` and used by both:
- * - the Agent Activity Panel — per-burst diffs lazy-fetched from
- * `GET /api/agent-burst-diff?agentId=<>&docName=<>&stackIndex=<>`
- * (server synthesizes via `synthesizeStackItemDiffText`).
+ * - the Agent Activity Panel — per-version diffs lazy-fetched from
+ * `GET /api/agent-burst-diff?agentId=<>&docName=<>&keptCount=<>`
+ * (server synthesizes via `synthesizeVersionDiff`).
* - the Timeline tab — per-entry diffs computed client-side in
* `useTimelineEntryDiff` via `diff.createPatch` against the live
* Y.Text, so the user's unsaved WIP is part of the comparison.
diff --git a/packages/app/src/components/ActivityPanelFileRow.test.tsx b/packages/app/src/components/ActivityPanelFileRow.test.tsx
index ddd76b451..17878e0be 100644
--- a/packages/app/src/components/ActivityPanelFileRow.test.tsx
+++ b/packages/app/src/components/ActivityPanelFileRow.test.tsx
@@ -1,8 +1,7 @@
/**
- * ActivityPanelFileRow unit tests — render via `renderToString` (same
- * pattern as jsx-component-prop-panel.test.tsx) and inspect the static HTML
- * shape. Interactive behavior (carrot toggle, undo dialog flow, onNavigate
- * firing) is exercised in Playwright E2E.
+ * ActivityPanelFileRow unit tests — render via `renderToString` and inspect the
+ * static HTML shape. Interactive behavior (row click → diff, per-edit Restore
+ * confirm, onNavigate firing) is exercised in Playwright E2E.
*/
import { describe, expect, test } from 'bun:test';
import { renderToString } from 'react-dom/server';
@@ -10,10 +9,6 @@ import { TooltipProvider } from '@/components/ui/tooltip';
import type { FileData } from '@/lib/use-activity-panel';
import { ActivityPanelFileRow } from './ActivityPanelFileRow';
-// The header-row undo buttons are wrapped in Radix `Tooltip`, which requires
-// a `TooltipProvider` ancestor. Production wires this at the app root
-// (`main.tsx`); tests wrap here so `renderToString` does not throw
-// "`Tooltip` must be used within `TooltipProvider`".
function render(ui: React.ReactElement): string {
return renderToString(<TooltipProvider>{ui}</TooltipProvider>);
}
@@ -32,142 +27,118 @@ function sampleFile(overrides?: Partial<FileData>): FileData {
};
}
-const noopFetch = async (_d: string, _i: number): Promise<string> => '';
-const noopAsync = async (_d: string): Promise<void> => {};
+const noopDrop = async (_d: string, _n: number): Promise<void> => {};
describe('ActivityPanelFileRow (static render)', () => {
- test('returns null when file has no bursts (D-P18 defensive guard)', () => {
+ test('returns null when file has no bursts (defensive guard)', () => {
const html = render(
<ActivityPanelFileRow
file={sampleFile({ bursts: [] })}
sessionAlive={true}
isWriting={false}
onNavigate={() => {}}
- onUndoLast={noopAsync}
- onUndoAll={noopAsync}
- fetchBurstDiff={noopFetch}
+ onUndoDrop={noopDrop}
+ onSetVersion={() => {}}
/>,
);
expect(html).toBe('');
});
- test('collapsed state: shows filename, stat, relative timestamp', () => {
+ test('header shows filename, stat, relative timestamp', () => {
const html = render(
<ActivityPanelFileRow
file={sampleFile()}
sessionAlive={true}
isWriting={false}
onNavigate={() => {}}
- onUndoLast={noopAsync}
- onUndoAll={noopAsync}
- fetchBurstDiff={noopFetch}
+ onUndoDrop={noopDrop}
+ onSetVersion={() => {}}
/>,
);
expect(html).toContain('notes.md');
- // React's server renderer inserts `<!-- -->` comment markers between
- // adjacent text/expression nodes — strip them before asserting content.
const stripped = html.replaceAll('<!-- -->', '');
- // Diff stats use unicode '−' minus for deletions (distinct from ASCII '-').
expect(stripped).toContain('+10');
expect(stripped).toContain('−2');
- // 15s ago ⇒ 's ago' pattern should appear.
expect(html).toContain('s ago');
});
- test('writing indicator renders only when isWriting=true', () => {
- const off = render(
+ test('renders every edit as an always-expanded clickable burst row — no slider, no carrot, no header undo icons', () => {
+ const html = render(
<ActivityPanelFileRow
file={sampleFile()}
sessionAlive={true}
isWriting={false}
onNavigate={() => {}}
- onUndoLast={noopAsync}
- onUndoAll={noopAsync}
- fetchBurstDiff={noopFetch}
+ onUndoDrop={noopDrop}
+ onSetVersion={() => {}}
/>,
);
- expect(off).not.toContain('>writing<');
+ // Both edits render up-front (no expand toggle gating them).
+ const openMatches = html.match(/data-testid="activity-panel-burst-open"/g) ?? [];
+ expect(openMatches).toHaveLength(2);
+ // The old slider + header quick-undo affordances are gone.
+ expect(html).not.toContain('data-testid="agent-undo-timeline"');
+ expect(html).not.toContain('data-testid="activity-panel-file-row-carrot"');
+ expect(html).not.toContain('data-testid="activity-panel-undo-last"');
+ expect(html).not.toContain('data-testid="activity-panel-undo-all"');
+ });
- const on = render(
+ test('each edit exposes a per-row Restore control', () => {
+ const html = render(
<ActivityPanelFileRow
file={sampleFile()}
sessionAlive={true}
- isWriting={true}
+ isWriting={false}
onNavigate={() => {}}
- onUndoLast={noopAsync}
- onUndoAll={noopAsync}
- fetchBurstDiff={noopFetch}
+ onUndoDrop={noopDrop}
+ onSetVersion={() => {}}
/>,
);
- expect(on).toContain('>writing<');
+ const restoreMatches = html.match(/data-testid="activity-panel-burst-restore"/g) ?? [];
+ expect(restoreMatches).toHaveLength(2);
});
- test('collapsed row renders both undo buttons in the header, confirm dialog not shown', () => {
+ test('Restore controls are disabled when the session has ended', () => {
const html = render(
<ActivityPanelFileRow
file={sampleFile()}
- sessionAlive={true}
+ sessionAlive={false}
isWriting={false}
onNavigate={() => {}}
- onUndoLast={noopAsync}
- onUndoAll={noopAsync}
- fetchBurstDiff={noopFetch}
+ onUndoDrop={noopDrop}
+ onSetVersion={() => {}}
/>,
);
- // Both undo buttons are now always in the header row (not gated on
- // expansion) — verified via data-testids that are stable across layout
- // shifts. aria-label carries the docName for screen-reader context.
- expect(html).toContain('data-testid="activity-panel-undo-last"');
- expect(html).toContain('data-testid="activity-panel-undo-all"');
- expect(html).toContain('aria-label="Undo last edit on notes.md"');
- expect(html).toContain('aria-label="Undo all edits on notes.md"');
- // Radix Dialog uses a Portal which emits nothing in SSR when `open=false`,
- // so the dialog title text never appears on the collapsed row.
- expect(html).not.toContain('Undo all edits on this file?');
+ const idx = html.indexOf('data-testid="activity-panel-burst-restore"');
+ expect(idx).toBeGreaterThan(-1);
+ // React serializes a bare `disabled` on the button tag, near the testid.
+ expect(html.slice(idx, idx + 300)).toContain('disabled');
});
- test('undo buttons are disabled when sessionAlive=false', () => {
- const html = render(
+ test('writing indicator renders only when isWriting=true', () => {
+ const off = render(
<ActivityPanelFileRow
file={sampleFile()}
- sessionAlive={false}
+ sessionAlive={true}
isWriting={false}
onNavigate={() => {}}
- onUndoLast={noopAsync}
- onUndoAll={noopAsync}
- fetchBurstDiff={noopFetch}
+ onUndoDrop={noopDrop}
+ onSetVersion={() => {}}
/>,
);
- // Both buttons carry the disabled attribute so click events won't fire
- // and screen readers announce the unavailable state.
- const undoLastIdx = html.indexOf('data-testid="activity-panel-undo-last"');
- const undoAllIdx = html.indexOf('data-testid="activity-panel-undo-all"');
- expect(undoLastIdx).toBeGreaterThan(-1);
- expect(undoAllIdx).toBeGreaterThan(-1);
- // Scan the surrounding button tag for `disabled` — React serializes the
- // attribute with no value (just the bare word).
- const windowBefore = 400;
- const undoLastSlice = html.slice(Math.max(0, undoLastIdx - windowBefore), undoLastIdx);
- const undoAllSlice = html.slice(Math.max(0, undoAllIdx - windowBefore), undoAllIdx);
- expect(undoLastSlice).toContain('disabled');
- expect(undoAllSlice).toContain('disabled');
- });
+ expect(off).not.toContain('>writing<');
- test('collapsed row carrot uses right-pointing chevron (▸), not down (▾)', () => {
- const html = render(
+ const on = render(
<ActivityPanelFileRow
file={sampleFile()}
sessionAlive={true}
- isWriting={false}
+ isWriting={true}
onNavigate={() => {}}
- onUndoLast={noopAsync}
- onUndoAll={noopAsync}
- fetchBurstDiff={noopFetch}
+ onUndoDrop={noopDrop}
+ onSetVersion={() => {}}
/>,
);
- // The collapsed carrot uses lucide-react's ChevronRight — verify
- // aria-expanded is false (the semantic signal consumers rely on).
- expect(html).toContain('aria-expanded="false"');
+ expect(on).toContain('>writing<');
});
test('filename click target has correct aria-label and data-testid', () => {
@@ -177,9 +148,8 @@ describe('ActivityPanelFileRow (static render)', () => {
sessionAlive={true}
isWriting={false}
onNavigate={() => {}}
- onUndoLast={noopAsync}
- onUndoAll={noopAsync}
- fetchBurstDiff={noopFetch}
+ onUndoDrop={noopDrop}
+ onSetVersion={() => {}}
/>,
);
expect(html).toContain('aria-label="Navigate to notes.md"');
diff --git a/packages/app/src/components/ActivityPanelFileRow.tsx b/packages/app/src/components/ActivityPanelFileRow.tsx
index 5b0ec2881..2ec6cc506 100644
--- a/packages/app/src/components/ActivityPanelFileRow.tsx
+++ b/packages/app/src/components/ActivityPanelFileRow.tsx
@@ -1,41 +1,21 @@
-// biome-ignore-all lint/plugin/no-raw-html-interactive-element: pre-rule backlog — file uses raw <button>/<input>/<textarea> awaiting shadcn migration; tracked at https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-raw-html-interactive-elementgrit
+// biome-ignore-all lint/plugin/no-raw-html-interactive-element: pre-rule backlog — the filename navigate target is a raw <button> awaiting shadcn migration; tracked at https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-raw-html-interactive-elementgrit
/**
* ActivityPanelFileRow — one file entry in the Activity Panel's scrollable
- * body. The header row is:
- * {carrot, filename link, [↶] Undo last, [⏪] Undo all, +N −M, timestamp,
- * optional writing indicator}.
+ * body. The header row is {filename link, +N −M, timestamp, optional writing
+ * indicator}. Beneath it, the file's edits render as an always-expanded,
+ * clickable list (`ActivityPanelBurstRow`) — mirroring the document Timeline:
+ * click an edit to open its whole-page diff in the main pane, or use an edit's
+ * Restore (↩) to undo every newer edit on this file.
*
- * The two undo buttons are icon-only (`Undo2` + `Rewind` from lucide) with
- * tooltips; they live on the header row rather than the expanded-section
- * footer so per-file actions are discoverable without first expanding the
- * burst list. Carrot click toggles expand/collapse; filename click navigates
- * the main editor without closing the panel. The undo buttons
- * `stopPropagation` so clicking them doesn't also toggle the carrot.
- *
- * Expanded state renders each burst via <ActivityPanelBurstRow>.
- *
- * Undo semantics:
- * - `[↶]` Undo last — fires immediately, no confirm (matches today).
- * - `[⏪]` Undo all — opens a shadcn Dialog; confirm dispatches onUndoAll.
- * Blast-radius asymmetry is intentional.
- *
- * Both buttons disabled when `sessionAlive === false` OR `bursts.length === 0`.
- * The row itself also disappears when `bursts.length === 0`.
+ * Scoped undo lives on the per-edit rows now (there's no file-level slider or
+ * header undo shortcut): "restore to edit K" drops `editCount - K` newest
+ * edits via `POST /api/agent-undo` scope `'count'`, threaded here as
+ * `commitDrop`.
*/
import { t } from '@lingui/core/macro';
-import { Plural, Trans, useLingui } from '@lingui/react/macro';
-import { ChevronDown, ChevronRight, Rewind, Undo2 } from 'lucide-react';
+import { Trans, useLingui } from '@lingui/react/macro';
import { useEffect, useState } from 'react';
-import { Button } from '@/components/ui/button';
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from '@/components/ui/dialog';
-import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { closeAgentDiff } from '@/lib/agent-diff-store';
import type { FileData } from '@/lib/use-activity-panel';
import { ActivityPanelBurstRow } from './ActivityPanelBurstRow';
@@ -44,9 +24,10 @@ interface ActivityPanelFileRowProps {
sessionAlive: boolean;
isWriting: boolean;
onNavigate: (docName: string) => void;
- onUndoLast: (docName: string) => void | Promise<void>;
- onUndoAll: (docName: string) => void | Promise<void>;
- fetchBurstDiff: (docName: string, stackIndex: number) => Promise<string>;
+ /** Drop the `dropCount` newest edits on this file (scoped undo). */
+ onUndoDrop: (docName: string, dropCount: number) => void | Promise<void>;
+ /** Show version `keptCount` of this file in the main pane (0 = original). */
+ onSetVersion: (keptCount: number) => void;
}
function formatRelative(ms: number, now: number): string {
@@ -68,76 +49,43 @@ export function ActivityPanelFileRow({
sessionAlive,
isWriting,
onNavigate,
- onUndoLast,
- onUndoAll,
- fetchBurstDiff,
+ onUndoDrop,
+ onSetVersion,
}: ActivityPanelFileRowProps): React.JSX.Element | null {
const { t } = useLingui();
const { docName } = file;
- const [expanded, setExpanded] = useState(false);
- const [confirmOpen, setConfirmOpen] = useState(false);
const [undoInFlight, setUndoInFlight] = useState(false);
// `Date.now()` is an impure function — calling it directly in render
// violates React Compiler's purity contract. Seed `now` once at mount + tick
- // it every ~30 s so the relative timestamp ("15s ago") stays reasonably
- // fresh without re-rendering every frame.
+ // it every ~30 s so the relative timestamp ("15s ago") stays reasonably fresh.
const [now, setNow] = useState<number>(() => Date.now());
useEffect(() => {
const id = setInterval(() => setNow(Date.now()), 30_000);
return () => clearInterval(id);
}, []);
- // Empty rows disappear. Defensive guard in the component itself in case
- // the parent hasn't filtered yet (should be rare since the hook's
- // data.files is the source of truth and typically pre-filters).
- if (file.bursts.length === 0) return null;
+ const editCount = file.bursts.length;
- const disabled = !sessionAlive || file.bursts.length === 0 || undoInFlight;
- const burstCount = file.bursts.length;
- const disabledReason = !sessionAlive
- ? t`Session ended — undo unavailable`
- : file.bursts.length === 0
- ? t`Nothing to undo on this file`
- : null;
-
- const handleUndoLast = (e: React.MouseEvent): void => {
- e.stopPropagation();
- if (disabled) return;
+ // Commit a scoped undo (drop the `dropCount` newest edits), then close the
+ // pane — the doc is now that version; the panel re-fetches on the undo's CC1
+ // signal. Passed to each burst row's Restore action.
+ const commitDrop = (dropCount: number): void => {
+ if (dropCount <= 0 || !sessionAlive || undoInFlight) return;
setUndoInFlight(true);
- Promise.resolve(onUndoLast(file.docName)).finally(() => setUndoInFlight(false));
- };
-
- const handleUndoAllClick = (e: React.MouseEvent): void => {
- e.stopPropagation();
- if (disabled) return;
- setConfirmOpen(true);
+ Promise.resolve(onUndoDrop(file.docName, dropCount)).finally(() => {
+ setUndoInFlight(false);
+ closeAgentDiff();
+ });
};
- const handleUndoAllConfirm = (): void => {
- setConfirmOpen(false);
- if (disabled) return;
- setUndoInFlight(true);
- Promise.resolve(onUndoAll(file.docName)).finally(() => setUndoInFlight(false));
- };
+ // Empty rows disappear. Defensive guard in the component itself in case
+ // the parent hasn't filtered yet.
+ if (file.bursts.length === 0) return null;
return (
<div className="border-b border-border" data-testid="activity-panel-file-row">
- {/* Header row: carrot | filename | undo-last | undo-all | stat | ts | writing. */}
+ {/* Header row: filename | stat | ts | writing. */}
<div className="flex items-center gap-2 px-3 py-2 text-sm">
- <button
- type="button"
- onClick={() => setExpanded((v) => !v)}
- className="flex size-5 shrink-0 items-center justify-center rounded hover:bg-muted"
- aria-expanded={expanded}
- aria-label={expanded ? t`Collapse ${docName}` : t`Expand ${docName}`}
- data-testid="activity-panel-file-row-carrot"
- >
- {expanded ? (
- <ChevronDown className="size-4" aria-hidden="true" />
- ) : (
- <ChevronRight className="size-4" aria-hidden="true" />
- )}
- </button>
<button
type="button"
onClick={() => onNavigate(file.docName)}
@@ -148,40 +96,6 @@ export function ActivityPanelFileRow({
>
{file.docName}
</button>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- type="button"
- variant="ghost"
- size="icon"
- className="size-6 shrink-0"
- onClick={handleUndoLast}
- disabled={disabled}
- aria-label={t`Undo last edit on ${docName}`}
- data-testid="activity-panel-undo-last"
- >
- <Undo2 className="size-3.5" aria-hidden="true" />
- </Button>
- </TooltipTrigger>
- <TooltipContent side="bottom">{disabledReason ?? t`Undo last edit`}</TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- type="button"
- variant="ghost"
- size="icon"
- className="size-6 shrink-0"
- onClick={handleUndoAllClick}
- disabled={disabled}
- aria-label={t`Undo all edits on ${docName}`}
- data-testid="activity-panel-undo-all"
- >
- <Rewind className="size-3.5" aria-hidden="true" />
- </Button>
- </TooltipTrigger>
- <TooltipContent side="bottom">{disabledReason ?? t`Undo all edits`}</TooltipContent>
- </Tooltip>
<span className="shrink-0 font-mono text-xs">
<span className="text-green-600 dark:text-green-400">+{file.additionsTotal}</span>{' '}
<span className="text-red-600 dark:text-red-400">−{file.deletionsTotal}</span>
@@ -196,54 +110,22 @@ export function ActivityPanelFileRow({
) : null}
</div>
- {expanded ? (
- <div>
- {file.bursts.map((burst) => (
- <ActivityPanelBurstRow
- key={`${file.docName}:${burst.stackIndex}`}
- burst={burst}
- docName={file.docName}
- fetchBurstDiff={fetchBurstDiff}
- />
- ))}
- </div>
- ) : null}
-
- <Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>
- <DialogContent className="sm:max-w-md">
- <DialogHeader>
- <DialogTitle>
- <Trans>Undo all edits on this file?</Trans>
- </DialogTitle>
- <DialogDescription>
- <Trans>
- Reverts every change this agent made to{' '}
- <span className="font-mono text-foreground">{docName}</span> this session (
- <Plural value={burstCount} one="# burst" other="# bursts" />
- ). Other files and writers are unaffected.
- </Trans>
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <Button
- type="button"
- variant="outline"
- onClick={() => setConfirmOpen(false)}
- data-testid="activity-panel-undo-all-cancel"
- >
- <Trans>Cancel</Trans>
- </Button>
- <Button
- type="button"
- variant="destructive"
- onClick={handleUndoAllConfirm}
- data-testid="activity-panel-undo-all-confirm"
- >
- <Trans>Undo all</Trans>
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
+ {/* Always-expanded edit list — click an edit to open its diff, or use its
+ Restore action to undo every newer edit on this file. */}
+ <div>
+ {file.bursts.map((burst) => (
+ <ActivityPanelBurstRow
+ key={`${file.docName}:${burst.stackIndex}`}
+ burst={burst}
+ docName={file.docName}
+ editCount={editCount}
+ sessionAlive={sessionAlive}
+ inFlight={undoInFlight}
+ onOpenDiff={(b) => onSetVersion(b.stackIndex + 1)}
+ onRestore={commitDrop}
+ />
+ ))}
+ </div>
</div>
);
}
diff --git a/packages/app/src/components/AgentDiffPane.tsx b/packages/app/src/components/AgentDiffPane.tsx
new file mode 100644
index 000000000..2b647a5e2
--- /dev/null
+++ b/packages/app/src/components/AgentDiffPane.tsx
@@ -0,0 +1,338 @@
+/**
+ * AgentDiffPane — the full-pane Agent edit diff, painted by EditorArea as an
+ * absolute overlay over the editor (the same slot + rationale as
+ * `TimelineDiffPane`: unmounting the EditorActivityPool would recycle the doc's
+ * provider). Driven by `agent-diff-store`.
+ *
+ * Shows one file *version*: the whole document with the first `keptCount` edits
+ * applied, diffed against the pre-agent original. Version 0 is the empty/original
+ * file; version N (all edits) is the current document. J/K / ←/→ walk versions;
+ * the panel's undo slider drives the same store, so the two stay in lockstep. The
+ * diff is whole-file, so the pane scrolls to the first change once it renders.
+ *
+ * Undo is committed from the Activity panel's timeline, not here.
+ */
+import { Trans, useLingui } from '@lingui/react/macro';
+import { Loader2, PanelRightClose, PanelRightOpen, X } from 'lucide-react';
+import { lazy, Suspense, useEffect, useRef, useState } from 'react';
+import { computeRenderedDiff, RenderedDiffView } from '@/components/RenderedDiffView';
+import { Button } from '@/components/ui/button';
+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 } from '@/lib/diff-change-nav';
+import { LruStringCache } from '@/lib/lru-string-cache';
+import { RENDERED_DIFF_CHANGE_SELECTOR } from '@/lib/rendered-diff/diff-decorations';
+import { fetchAgentBurstDiff } from '@/lib/use-activity-panel';
+import { countDiffStat } from '@/lib/use-timeline-entry-diff';
+import { AgentIcon } from './icons/AgentIcon';
+
+const LazyActivityPanelDiffView = lazy(async () => {
+ const mod = await import('@/components/ActivityPanelDiffView');
+ return { default: mod.ActivityPanelDiffView };
+});
+
+// Bound the per-version diff cache so scrubbing a long session can't grow
+// renderer memory unboundedly. Mirrors the panel hook's BURST_DIFF_CACHE_LIMIT.
+const VERSION_DIFF_CACHE_LIMIT = 64;
+
+interface AgentDiffPaneProps {
+ view: AgentDiffView;
+ /** DocPanel collapsed state + toggle — the pane overlays the editor toolbar
+ * that normally owns this control, so it surfaces its own. */
+ isPanelCollapsed: boolean;
+ onTogglePanel: () => void;
+}
+
+export function AgentDiffPane({ view, isPanelCollapsed, onTogglePanel }: AgentDiffPaneProps) {
+ const { t } = useLingui();
+ const { agentId, agentName, agentColor, agentIcon, docName, keptCount } = view;
+ const [cache] = useState(() => new LruStringCache(VERSION_DIFF_CACHE_LIMIT));
+ const diffBodyRef = useRef<HTMLDivElement>(null);
+ // Rendered (WYSIWYG) is the default; Source is the raw unified diff and the
+ // engine-failure fallback — parity with `TimelineDiffPane`.
+ const [renderMode, setRenderMode] = useState<'rendered' | 'source'>('rendered');
+ const [result, setResult] = useState<{
+ status: 'loading' | 'ready' | 'error';
+ diff: string;
+ before: string;
+ after: string;
+ }>({ status: 'loading', diff: '', before: '', after: '' });
+
+ // Fetch the current version's whole-page diff + before/after bodies (cached
+ // across steps within this pane's lifetime as one JSON blob). Keyed on the
+ // primitive coordinates so it doesn't re-fetch when `view` identity changes.
+ useEffect(() => {
+ let cancelled = false;
+ setResult({ status: 'loading', diff: '', before: '', after: '' });
+ const key = `${docName}\0${keptCount}`;
+ const cached = cache.get(key);
+ if (cached !== undefined) {
+ const parsed = JSON.parse(cached) as { diff: string; before: string; after: string };
+ setResult({ status: 'ready', ...parsed });
+ return;
+ }
+ fetchAgentBurstDiff(agentId, docName, keptCount)
+ .then((data) => {
+ if (cancelled) return;
+ cache.set(key, JSON.stringify(data));
+ setResult({ status: 'ready', ...data });
+ })
+ .catch((err) => {
+ if (!cancelled) {
+ console.error('[agent-diff] failed to load burst diff', {
+ agentId,
+ docName,
+ keptCount,
+ err,
+ });
+ setResult({ status: 'error', diff: '', before: '', after: '' });
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [agentId, docName, keptCount, cache]);
+
+ // Rendered-diff engine result (plain compute, not a hook). `ok === false`
+ // (parse/recreate failure or over the size ceiling) → fall back to Source.
+ const rendered =
+ result.status === 'ready' ? computeRenderedDiff(result.before, result.after) : null;
+
+ // Whole-file diff → scroll to the first changed line once it renders.
+ // Re-keyed on the diff string (re-runs per version step) and on mode (so
+ // toggling Rendered/Source re-scrolls). Mirrors `TimelineDiffPane`'s
+ // settle-debounced scroll: the rendered (ProseMirror) diff mounts its change
+ // decorations a beat after the React commit, so scrolling on the first anchor
+ // we see races a stale anchor from the previous version. Instead we wait until
+ // the diff DOM has stopped mutating for `settleMs`, then double-rAF so the
+ // final batch paints before we measure.
+ const diffKey =
+ result.status === 'ready' && result.diff !== '' ? `${renderMode}:${result.diff}` : '';
+ useEffect(() => {
+ const container = diffBodyRef.current;
+ if (diffKey === '' || !container) return;
+
+ let done = false;
+ let observer: MutationObserver | null = null;
+ let settleTimer: ReturnType<typeof setTimeout> | undefined;
+ let rafId: number | undefined;
+
+ const scrollToFirstChange = (): void => {
+ if (done) return;
+ // First rendered-diff decoration, else first source-diff change row.
+ const el =
+ container.querySelector<HTMLElement>(RENDERED_DIFF_CHANGE_SELECTOR) ??
+ collectChangeAnchors(container)[0];
+ if (!el) return;
+ done = true;
+ observer?.disconnect();
+ 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);
+ });
+ }, settleMs);
+ };
+
+ observer = new MutationObserver(scheduleAfterSettle);
+ observer.observe(container, { childList: true, subtree: true });
+ // Kick once for the case where the anchor is already present and no further
+ // mutations arrive to trigger the observer.
+ scheduleAfterSettle();
+
+ const failsafe = setTimeout(() => observer?.disconnect(), 5000);
+ return () => {
+ observer?.disconnect();
+ if (settleTimer !== undefined) clearTimeout(settleTimer);
+ if (rafId !== undefined) cancelAnimationFrame(rafId);
+ clearTimeout(failsafe);
+ };
+ }, [diffKey]);
+
+ // Keyboard: Esc closes; J/K (or ←/→) step through versions.
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent): void => {
+ const target = e.target as HTMLElement | null;
+ if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA')) return;
+ if (e.key === 'Escape') {
+ closeAgentDiff();
+ } else if (e.key === 'j' || e.key === 'ArrowRight') {
+ e.preventDefault();
+ setAgentDiffKept(keptCount + 1);
+ } else if (e.key === 'k' || e.key === 'ArrowLeft') {
+ e.preventDefault();
+ setAgentDiffKept(keptCount - 1);
+ }
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [keptCount]);
+
+ const stat =
+ result.status === 'ready' ? countDiffStat(result.diff) : { additions: 0, deletions: 0 };
+ const showStat = stat.additions > 0 || stat.deletions > 0;
+
+ return (
+ <div
+ className="absolute inset-0 z-20 flex flex-col bg-background"
+ data-testid="agent-diff-pane"
+ >
+ {/* Header: close · agent + file · [stat · render · panel]. */}
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1.5 border-b border-border px-3 py-2">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-7 shrink-0"
+ data-testid="agent-diff-close"
+ aria-label={t`Close diff`}
+ onClick={() => closeAgentDiff()}
+ >
+ <X className="size-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">{t`Close diff`}</TooltipContent>
+ </Tooltip>
+
+ <span
+ className="flex size-6 shrink-0 items-center justify-center rounded-full text-white"
+ style={{ backgroundColor: agentColor }}
+ >
+ <AgentIcon icon={agentIcon} width={13} height={13} />
+ </span>
+
+ <div className="min-w-0 max-w-[14rem] shrink">
+ <div className="truncate text-sm font-medium text-foreground">{docName}</div>
+ <div className="truncate text-xs text-muted-foreground">{agentName}</div>
+ </div>
+
+ <div className="ml-auto flex flex-wrap items-center justify-end gap-2">
+ {showStat && (
+ <span
+ role="img"
+ className="shrink-0 text-xs tabular-nums"
+ data-testid="agent-diff-stat"
+ aria-label={t`${stat.additions} added, ${stat.deletions} removed`}
+ >
+ <span aria-hidden="true" className="text-emerald-600 dark:text-emerald-500">
+ +{stat.additions}
+ </span>{' '}
+ <span aria-hidden="true" className="text-red-600 dark:text-red-500">
+ −{stat.deletions}
+ </span>
+ </span>
+ )}
+
+ <ToggleGroup
+ type="single"
+ value={renderMode}
+ onValueChange={(v) => {
+ if (v === 'rendered' || v === 'source') setRenderMode(v);
+ }}
+ aria-label={t`Diff render mode`}
+ variant="segmented"
+ size="sm"
+ spacing={1}
+ className="shrink-0 rounded-md bg-muted p-0.5 dark:bg-background"
+ >
+ <ToggleGroupItem
+ value="rendered"
+ className="h-6 px-2 text-xs"
+ data-testid="agent-diff-render-rendered"
+ >
+ <Trans>Rendered</Trans>
+ </ToggleGroupItem>
+ <ToggleGroupItem
+ value="source"
+ className="h-6 px-2 text-xs"
+ data-testid="agent-diff-render-source"
+ >
+ <Trans>Source</Trans>
+ </ToggleGroupItem>
+ </ToggleGroup>
+
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-7 shrink-0"
+ data-testid="agent-diff-toggle-panel"
+ aria-label={isPanelCollapsed ? t`Show panel` : t`Hide panel`}
+ aria-expanded={!isPanelCollapsed}
+ onClick={onTogglePanel}
+ >
+ {isPanelCollapsed ? (
+ <PanelRightOpen className="size-4" />
+ ) : (
+ <PanelRightClose className="size-4" />
+ )}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ {isPanelCollapsed ? t`Show panel` : t`Hide panel`}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+
+ {/* Diff body — scrolls independently of the header. */}
+ <div ref={diffBodyRef} className="min-h-0 flex-1 overflow-auto subtle-scrollbar">
+ {result.status === 'loading' && (
+ <div className="flex items-center gap-2 px-4 py-3 text-xs text-muted-foreground">
+ <Loader2 className="size-3 animate-spin" />
+ <Trans>Loading diff</Trans>
+ </div>
+ )}
+ {result.status === 'error' && (
+ <p className="px-4 py-3 text-xs text-destructive">
+ <Trans>Diff unavailable</Trans>
+ </p>
+ )}
+ {result.status === 'ready' &&
+ (renderMode === 'rendered' && rendered?.ok ? (
+ // Rendered (WYSIWYG) inline diff. Also the no-change path: with zero
+ // changes it renders the document (e.g. version 0 = the original).
+ <RenderedDiffView diff={rendered} />
+ ) : result.diff === '' ? (
+ // Source mode, no diff (version 0 original, or a no-op edit): show the
+ // note, then the whole document source — so the original's content is
+ // visible in Source too, mirroring what Rendered shows (and Timeline).
+ <>
+ <p className="border-b border-border px-4 py-2 text-xs text-muted-foreground italic">
+ {keptCount === 0 ? (
+ <Trans>Original file — before this agent's edits.</Trans>
+ ) : (
+ <Trans>No content changes at this version.</Trans>
+ )}
+ </p>
+ <pre className="whitespace-pre-wrap px-4 py-3 font-mono text-xs text-foreground/90">
+ {result.after}
+ </pre>
+ </>
+ ) : (
+ <Suspense
+ fallback={
+ <div className="flex items-center gap-2 px-4 py-3 text-xs text-muted-foreground">
+ <Loader2 className="size-3 animate-spin" />
+ <Trans>Loading diff renderer</Trans>
+ </div>
+ }
+ >
+ <LazyActivityPanelDiffView diff={result.diff} viewType="unified" />
+ </Suspense>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/app/src/components/DiffView.tsx b/packages/app/src/components/DiffView.tsx
index fad3c31c8..f3761cdd3 100644
--- a/packages/app/src/components/DiffView.tsx
+++ b/packages/app/src/components/DiffView.tsx
@@ -43,7 +43,7 @@ const conflictMergeControlTheme = EditorView.theme({
},
});
-export type DiffLayout = 'unified' | 'split';
+type DiffLayout = 'unified' | 'split';
interface MergeControlPortal {
id: number;
diff --git a/packages/app/src/components/DocPanel.tsx b/packages/app/src/components/DocPanel.tsx
index 5e2e2bde9..0e57d437d 100644
--- a/packages/app/src/components/DocPanel.tsx
+++ b/packages/app/src/components/DocPanel.tsx
@@ -1,8 +1,7 @@
import { t } from '@lingui/core/macro';
import { Trans, useLingui } from '@lingui/react/macro';
import { AlertTriangle, Clock, Link2, ListTree, Network } from 'lucide-react';
-import { lazy, Suspense, useState } from 'react';
-import type { DiffLayout } from '@/components/DiffView';
+import { lazy, Suspense } from 'react';
import { composeLintFixTerminalPaste } from '@/components/handoff/compose-lint-fix-prompt';
import { useTerminalLaunch } from '@/components/handoff/TerminalLaunchContext';
import { requestActiveTerminalInput } from '@/components/handoff/terminal-input-events';
@@ -79,10 +78,7 @@ export function DocPanel({
onActiveTabChange,
mode,
}: DocPanelProps) {
- // Lifted from TimelineContent so the choice survives sub-tab switches —
- // TimelineContent unmounts when activeTab leaves 'timeline'.
const { t } = useLingui();
- const [diffLayout, setDiffLayout] = useState<DiffLayout>('unified');
// Live, mode-agnostic lint diagnostics for the active doc — drives both the
// Problems tab badge and the panel itself. Reads `Y.Text('source')`, so it
// works in WYSIWYG mode too. Gated to the matching provider during nav.
@@ -205,13 +201,7 @@ export function DocPanel({
<LazyGraphPanel activeDocName={docName} />
</Suspense>
)}
- {effectiveTab === 'timeline' && (
- <TimelineContent
- docName={docName}
- diffLayout={diffLayout}
- onDiffLayoutChange={setDiffLayout}
- />
- )}
+ {effectiveTab === 'timeline' && <TimelineContent docName={docName} />}
{effectiveTab === 'problems' && (
<ProblemsPanel
docName={docName}
diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsx
index 5d693a700..6c03748b8 100644
--- a/packages/app/src/components/EditorArea.tsx
+++ b/packages/app/src/components/EditorArea.tsx
@@ -36,6 +36,7 @@ import { syncPromiseHasResolved } from '@/editor/sync-promise';
import { useDocumentStats } from '@/hooks/use-document-stats';
import { useLifecycleStatus } from '@/hooks/use-lifecycle-status';
import { useSelectionStats } from '@/hooks/use-selection-stats';
+import { closeAgentDiff, useAgentDiffView } from '@/lib/agent-diff-store';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { docNameFromHash, hashFromDocName } from '@/lib/doc-hash';
import { getInitialDocPanelWidth, writeDocPanelWidth } from '@/lib/doc-panel-width-store';
@@ -54,6 +55,7 @@ import {
MIN_TERMINAL_WIDTH,
writeTerminalWidth,
} from '@/lib/terminal-width-store';
+import { closeTimelineDiff, useTimelineDiffView } from '@/lib/timeline-diff-store';
import { useSettingsRoute } from '@/lib/use-settings-route';
import { cn } from '@/lib/utils';
import { setViewMenuState } from '@/lib/view-menu-state-store';
@@ -75,6 +77,20 @@ const LazyActivityModeContent = lazy(async () => {
return { default: mod.ActivityModeContent };
});
+// The full-pane version diffs are overlays that only paint on user action (open
+// a Timeline/agent diff), so they're code-split off the eager editor bundle —
+// this keeps the rendered-diff engine + `prosemirror-recreate-transform` out of
+// the main chunk (size-limit budget). Their sync `computeRenderedDiff` stays
+// intact inside the lazily-loaded pane.
+const LazyTimelineDiffPane = lazy(async () => {
+ const mod = await import('@/components/TimelineDiffPane');
+ return { default: mod.TimelineDiffPane };
+});
+const LazyAgentDiffPane = lazy(async () => {
+ const mod = await import('@/components/AgentDiffPane');
+ return { default: mod.AgentDiffPane };
+});
+
// Shared doc-panel sizing — referenced by both the live `id="doc-panel"` and the
// hash-load placeholder that mirrors it, so the two stay structurally linked and
// their min/max can't drift apart.
@@ -247,6 +263,55 @@ function EditorAreaInner({
const isNewDoc = activeTarget?.kind === 'missing';
const showStats = !!activeDocName && activeTarget?.kind !== 'folder';
const editorPlaceholder = isNewDoc ? t`Start writing to create this page` : undefined;
+ // Full-pane version diff (opened from the Timeline panel). Painted as an
+ // overlay over the editor below; closed when the open doc changes since a
+ // version belongs to one doc and must never paint over an unrelated one.
+ const timelineDiff = useTimelineDiffView();
+ useEffect(() => {
+ if (timelineDiff && timelineDiff.docName !== activeDocName) closeTimelineDiff();
+ }, [activeDocName, timelineDiff]);
+ // Full-pane agent-edit diff (opened from the Agent Activity panel). Same
+ // overlay slot as the timeline diff. Unlike the timeline (always the open
+ // doc), the agent's edits can span other files and the pane steps through
+ // them, so EditorArea drives navigation: whenever the current edit's doc
+ // changes (open or step), navigate the editor to it. `agentDiffNavTargetRef`
+ // holds that in-flight target so the close-on-nav-away effect keeps the pane
+ // through the transition, then closes it only on a genuine navigation away.
+ const agentDiff = useAgentDiffView();
+ const agentDiffDoc = agentDiff?.docName ?? null;
+ const agentDiffNavTargetRef = useRef<string | null>(null);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: intentionally keyed only on the target doc; activeDocName/openDocumentTransition are read fresh, not tracked, so this fires only when the current edit's doc changes and never fights a manual nav-away
+ useEffect(() => {
+ if (agentDiffDoc == null) {
+ agentDiffNavTargetRef.current = null;
+ return;
+ }
+ agentDiffNavTargetRef.current = agentDiffDoc;
+ if (agentDiffDoc !== activeDocName) {
+ const nextHash = hashFromDocName(agentDiffDoc);
+ if (window.location.hash === nextHash) openDocumentTransition(agentDiffDoc);
+ else window.location.hash = nextHash;
+ }
+ }, [agentDiffDoc]);
+ useEffect(() => {
+ if (agentDiffDoc == null) return;
+ if (agentDiffDoc === activeDocName) {
+ agentDiffNavTargetRef.current = null; // arrived — nav settled
+ return;
+ }
+ // Still navigating toward the current edit's doc — keep the pane mounted.
+ if (agentDiffNavTargetRef.current === agentDiffDoc) return;
+ closeAgentDiff();
+ }, [activeDocName, agentDiffDoc]);
+ // The full-pane agent diff only makes sense while the Agent Activity panel is
+ // open. When the panel is exited — "Back to document view" flips docPanelMode
+ // to 'doc', or the agent is deselected — dismiss the overlay so the editor
+ // returns to the plain document instead of stranding the reader in the diff.
+ // Covers every exit path, not just the back button (mode toggle, deselect).
+ useEffect(() => {
+ const agentPanelOpen = docPanelMode === 'agent' && docPanelAgentId !== null;
+ if (!agentPanelOpen) closeAgentDiff();
+ }, [docPanelMode, docPanelAgentId]);
// A share-receive navigation that resolved to a missing target renders an
// honest verdict panel instead of the create-mode editor, so a receiver can't
// silently fork the doc at the shared path. A plain missing target — an
@@ -929,11 +994,17 @@ function EditorAreaInner({
// own instance under shouldShowFolderComposer. Positioning and the
// --ask-composer-height scroll inset are documented at the render site
// below.
- const showBottomComposer = shouldShowBottomComposer({
- terminalVisible,
- isEmbedded,
- activeDocName,
- });
+ const showBottomComposer =
+ shouldShowBottomComposer({
+ terminalVisible,
+ isEmbedded,
+ activeDocName,
+ }) &&
+ // Hide the "Ask AI" composer while a full-pane diff is open (timeline or
+ // agent edit) — it would float over the diff's bottom, and it's a
+ // live-edit affordance that doesn't apply to a read-only diff.
+ !(timelineDiff && timelineDiff.docName === activeDocName) &&
+ !(agentDiff && agentDiffDoc === activeDocName);
const editorContent = (
<div className="relative flex h-full flex-col">
<div className="relative min-h-0 flex-1">
@@ -1008,6 +1079,29 @@ function EditorAreaInner({
{activeDocName !== null ? <MountStalledAffordance docName={activeDocName} /> : null}
</div>
) : null}
+ {/* Full-pane version diff overlay — paints over the pool (like the
+ skeleton above) without unmounting it, so the provider stays live
+ for the vs-live comparison and closing returns instantly. */}
+ {timelineDiff && timelineDiff.docName === activeDocName ? (
+ <Suspense fallback={null}>
+ <LazyTimelineDiffPane
+ view={timelineDiff}
+ isPanelCollapsed={isCollapsed}
+ onTogglePanel={togglePanel}
+ />
+ </Suspense>
+ ) : null}
+ {/* Agent-edit diff overlay — same slot + rationale as the timeline
+ pane above. Painted only for the current edit's own doc. */}
+ {agentDiff && agentDiffDoc === activeDocName ? (
+ <Suspense fallback={null}>
+ <LazyAgentDiffPane
+ view={agentDiff}
+ isPanelCollapsed={isCollapsed}
+ onTogglePanel={togglePanel}
+ />
+ </Suspense>
+ ) : null}
</div>
{!isConflict && (
<EditorToolbar
diff --git a/packages/app/src/components/RenderedDiffView.dom.test.tsx b/packages/app/src/components/RenderedDiffView.dom.test.tsx
new file mode 100644
index 000000000..e0b3de964
--- /dev/null
+++ b/packages/app/src/components/RenderedDiffView.dom.test.tsx
@@ -0,0 +1,122 @@
+/**
+ * RTL mount tests for the rendered (WYSIWYG) Timeline diff. The engine ranges
+ * are unit-tested in `lib/rendered-diff/build-rendered-diff.test.ts`; this file
+ * locks the parts that only exist once the decorations are painted into a real
+ * read-only editor — which is where three real bugs hid:
+ *
+ * - decorations must anchor to a real `.ProseMirror` DOM (editor fidelity),
+ * - a pure INSERTION must still produce a scroll/stepper anchor
+ * (`.ok-diff-ins-block`) — a missing selector once left additions unscrolled,
+ * - editing one list item must NOT highlight its siblings — the `list` vs
+ * `bulletList` node-name bug once flagged the whole list.
+ *
+ * Invocation: `bun run test:dom src/components/RenderedDiffView.dom.test.tsx`.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { cleanup, render, waitFor } from '@testing-library/react';
+import {
+ countRenderedDiffAnchors,
+ RENDERED_DIFF_CHANGE_SELECTOR,
+} from '@/lib/rendered-diff/diff-decorations';
+import { computeRenderedDiff, RenderedDiffView } from './RenderedDiffView';
+
+afterEach(() => {
+ cleanup();
+});
+
+/** Compute + mount a rendered diff; resolve once the ProseMirror DOM exists. */
+async function mountDiff(before: string, after: string): Promise<HTMLElement> {
+ const diff = computeRenderedDiff(before, after);
+ if (!diff.ok) throw new Error(`engine returned not-ok: ${diff.reason}`);
+ render(<RenderedDiffView diff={diff} />);
+ const pane = await waitFor(() => {
+ const el = document.querySelector<HTMLElement>('[data-testid="rendered-diff-view"]');
+ if (!el?.querySelector('.ProseMirror')) throw new Error('editor not mounted yet');
+ return el;
+ });
+ return pane;
+}
+
+describe('RenderedDiffView', () => {
+ test('renders the diff as real .ProseMirror editor DOM', async () => {
+ const pane = await mountDiff('Alpha paragraph.', 'Alpha paragraph, extended.');
+ expect(pane.querySelector('.ProseMirror')).toBeTruthy();
+ });
+
+ test('an ordered list renders as one <ol> with all its items (not per-line lists)', async () => {
+ const body = '1. first\n2. second\n3. third';
+ const pane = await mountDiff(body, body);
+ const lists = pane.querySelectorAll('.ProseMirror ol');
+ // One ordered list containing all three items — the pre-fix per-line renderer
+ // produced three separate <ol>s (each restarting at "1.").
+ expect(lists.length).toBe(1);
+ expect(pane.querySelectorAll('.ProseMirror ol > li').length).toBe(3);
+ });
+
+ test('a pure insertion produces a scroll/stepper anchor', async () => {
+ const pane = await mountDiff('Kept paragraph.', 'Kept paragraph.\n\nA newly added paragraph.');
+ // The added block must be findable by the EXACT selector the pane uses to
+ // scroll-to-first-change and drive the stepper — shared const, so a class
+ // rename can't desync the two (the original "additions don't scroll" bug).
+ const anchor = pane.querySelector(RENDERED_DIFF_CHANGE_SELECTOR);
+ expect(anchor).toBeTruthy();
+ expect(pane.querySelector('.ok-diff-ins-block')?.textContent).toContain('newly added');
+ });
+
+ test('a deletion produces a struck [data-diff-deleted] widget', async () => {
+ const pane = await mountDiff('Keep this.\n\nDrop this one.', 'Keep this.');
+ const deleted = pane.querySelector('[data-diff-deleted]');
+ expect(deleted).toBeTruthy();
+ expect(deleted?.textContent).toContain('Drop this one');
+ });
+
+ test('editing one list item leaves sibling items un-highlighted', async () => {
+ const before =
+ '- [[proposals/0001|Proposal 0001]] vision.\n- [[specs/x/spec|Spec A]] tasks.\n- Old third item.';
+ const after =
+ '- [[proposals/0001|Proposal 0001]] vision.\n- [[specs/x/spec|Spec A]] tasks.\n- Reworded third item.';
+ const pane = await mountDiff(before, after);
+
+ // Only the third item may carry a change decoration; the untouched siblings
+ // must not appear inside any highlighted/struck element (the list-node bug).
+ const marked = Array.from(pane.querySelectorAll(RENDERED_DIFF_CHANGE_SELECTOR))
+ .map((el) => el.textContent ?? '')
+ .join(' ');
+ expect(marked).toContain('third item');
+ expect(marked).not.toContain('Proposal');
+ expect(marked).not.toContain('Spec');
+ });
+
+ test('a formatting-only change (bold removed) renders without content churn', async () => {
+ // Text is byte-identical; only a mark toggles. Must mount cleanly and mark
+ // the phrase (via the mark-change replacement path), not the whole block.
+ const pane = await mountDiff('one **two three** four', 'one two three four');
+ expect(pane.querySelector('.ProseMirror')).toBeTruthy();
+ // No whole-block insertion highlight — the block text did not change.
+ expect(pane.querySelector('.ok-diff-ins-block')).toBeNull();
+ });
+
+ // The stepper's "N / M" must equal the real number of navigable anchors, or
+ // navigation wraps past the displayed M. A mark change paints TWO anchors
+ // (struck before + highlighted after), which the naive `changes.length +
+ // markChanges.length` undercounts.
+ test('countRenderedDiffAnchors matches the real DOM anchor count (incl. mark changes)', async () => {
+ for (const [before, after] of [
+ ['one **two three** four', 'one two three four'], // mark-only → 2 anchors
+ ['Kept paragraph.', 'Kept paragraph.\n\nAdded paragraph.'], // insertion → 1
+ ['Old bullet only.', 'Reworded bullet only.'], // reworded → del + ins = 2
+ ] as const) {
+ const diff = computeRenderedDiff(before, after);
+ if (!diff.ok) throw new Error(`engine not-ok: ${diff.reason}`);
+ cleanup();
+ render(<RenderedDiffView diff={diff} />);
+ const pane = await waitFor(() => {
+ const el = document.querySelector<HTMLElement>('[data-testid="rendered-diff-view"]');
+ if (!el?.querySelector('.ProseMirror')) throw new Error('not mounted');
+ return el;
+ });
+ const domAnchors = pane.querySelectorAll(RENDERED_DIFF_CHANGE_SELECTOR).length;
+ expect(countRenderedDiffAnchors(diff)).toBe(domAnchors);
+ }
+ });
+});
diff --git a/packages/app/src/components/RenderedDiffView.tsx b/packages/app/src/components/RenderedDiffView.tsx
new file mode 100644
index 000000000..77bee8277
--- /dev/null
+++ b/packages/app/src/components/RenderedDiffView.tsx
@@ -0,0 +1,117 @@
+/**
+ * RenderedDiffView — the WYSIWYG (unified inline track-changes) Timeline diff.
+ *
+ * Renders the "after" version through a read-only static TipTap editor (the
+ * `SkillMarkdownViewer` pattern — real `.ProseMirror` DOM, whole-document parse,
+ * NO Y.Doc / provider / awareness), and overlays a static `DecorationSet`:
+ * inserted words highlighted inline (`ok-diff-ins`), removed content struck
+ * through in place (`ok-diff-del`) as widget decorations that re-render the
+ * before-doc slice through the real schema.
+ *
+ * The diff itself is computed by the pure engine (`buildRenderedDiff`); this
+ * component is the render half. `useRenderedDiff` is exported so the pane can
+ * decide rendered-vs-Source before mounting an editor (a `false` engine result
+ * → the pane falls back to the raw Source diff).
+ *
+ * STOP: do not add Collaboration / CollaborationCursor here — this is a static
+ * editor and those require a Y.Doc (same contract `SkillMarkdownViewer` documents).
+ */
+import { Extension, getSchema } from '@tiptap/core';
+import { Plugin, PluginKey } from '@tiptap/pm/state';
+import { DecorationSet } from '@tiptap/pm/view';
+import { EditorContent, useEditor } from '@tiptap/react';
+import { useLayoutEffect, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { getSharedMarkdownManager } from '@/editor/utils/md-singleton';
+import {
+ buildRenderedDiff,
+ type RenderedDiff,
+ type RenderedDiffResult,
+} from '@/lib/rendered-diff/build-rendered-diff';
+import { buildDiffDecorations } from '@/lib/rendered-diff/diff-decorations';
+import { diffExtensions } from '@/lib/rendered-diff/diff-extensions';
+
+// Stable schema for the diff editor — `diffExtensions` is module-const, so the
+// schema is built once. The engine materializes docs against it; decorations
+// are position-based, so they apply to the editor's (structurally identical)
+// doc regardless of schema-instance identity.
+const diffSchema = getSchema(diffExtensions);
+
+/**
+ * Compute the rendered diff between two markdown bodies. Plain function (NOT a
+ * React hook, despite being called in render) — named `compute*` so hook-lint
+ * doesn't treat it as one; safe to call conditionally. The pane branches on `ok`.
+ */
+export function computeRenderedDiff(before: string, after: string): RenderedDiffResult {
+ return buildRenderedDiff(before, after, diffSchema, getSharedMarkdownManager());
+}
+
+const DiffDecorations = Extension.create<{ decorations: DecorationSet }>({
+ name: 'renderedDiffDecorations',
+ addOptions() {
+ return { decorations: DecorationSet.empty };
+ },
+ addProseMirrorPlugins() {
+ const decorations = this.options.decorations;
+ return [
+ new Plugin({
+ key: new PluginKey('renderedDiffDecorations'),
+ props: { decorations: () => decorations },
+ }),
+ ];
+ },
+});
+
+export function RenderedDiffView({ diff }: { diff: RenderedDiff }) {
+ const decorations = buildDiffDecorations(
+ diff.afterDoc,
+ diff.beforeDoc,
+ diff.changes,
+ diff.markChanges,
+ diffSchema,
+ );
+
+ const editor = useEditor(
+ {
+ editable: false,
+ extensions: [...diffExtensions, DiffDecorations.configure({ decorations })],
+ content: diff.afterDoc.toJSON(),
+ editorProps: {
+ // Same content-surface padding as the real editor so spacing matches.
+ attributes: { class: 'pt-4 pb-4' },
+ },
+ },
+ [diff],
+ );
+
+ // Portal the EditorContent into a privately-owned target so TipTap's
+ // DOM-vacuum can't pull in sibling nodes (the `no-unportaled-editor-content`
+ // GritQL rule + H6 contract, precedent #44). Mirrors `SkillMarkdownViewer`.
+ const [portalTarget] = useState(() => {
+ const el = document.createElement('div');
+ el.style.display = 'contents';
+ return el;
+ });
+ const portalSlotRef = useRef<HTMLDivElement | null>(null);
+ useLayoutEffect(() => {
+ const slot = portalSlotRef.current;
+ if (!slot) return;
+ slot.appendChild(portalTarget);
+ return () => {
+ if (portalTarget.parentNode === slot) slot.removeChild(portalTarget);
+ };
+ }, [portalTarget]);
+
+ return (
+ <div className="editor-doc-scroll min-h-0 flex-1" data-testid="rendered-diff-view">
+ <div className="tiptap-editor">
+ <div ref={portalSlotRef} style={{ display: 'contents' }} />
+ </div>
+ {createPortal(
+ // biome-ignore lint/plugin/no-unportaled-editor-content: portaled site — view.dom parent is the exclusively-owned portalTarget per the H6 contract (PRECEDENTS.md #44)
+ <EditorContent editor={editor} className="tiptap-editor-portal-content" />,
+ portalTarget,
+ )}
+ </div>
+ );
+}
diff --git a/packages/app/src/components/TimelineDiffPane.tsx b/packages/app/src/components/TimelineDiffPane.tsx
new file mode 100644
index 000000000..3bcd94c5d
--- /dev/null
+++ b/packages/app/src/components/TimelineDiffPane.tsx
@@ -0,0 +1,466 @@
+/**
+ * TimelineDiffPane — the full-pane version diff, painted by EditorArea as an
+ * absolute overlay over the editor (not a viewContent branch: unmounting the
+ * EditorActivityPool would recycle the doc's provider and break the vs-live
+ * diff, which reads live Y.Text). Driven by `timeline-diff-store`; a Timeline
+ * row opens it, this pane owns the mode toggle, the `+N −M` stat, the diff
+ * layout, and Restore.
+ *
+ * The provider stays mounted underneath, so closing the pane returns to the
+ * editor instantly with no remount flash.
+ */
+import { ProblemDetailsSchema } from '@inkeep/open-knowledge-core';
+import { Plural, Trans, useLingui } from '@lingui/react/macro';
+import {
+ ChevronDown,
+ ChevronUp,
+ Loader2,
+ PanelRightClose,
+ PanelRightOpen,
+ Undo2,
+ X,
+} from 'lucide-react';
+import { lazy, Suspense, useEffect, useRef, useState } from 'react';
+import { toast } from 'sonner';
+import { computeRenderedDiff, RenderedDiffView } from '@/components/RenderedDiffView';
+import { Button } from '@/components/ui/button';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
+import { collectChangeAnchors, countChangeGroups } from '@/lib/diff-change-nav';
+import { LruStringCache } from '@/lib/lru-string-cache';
+import {
+ countRenderedDiffAnchors,
+ RENDERED_DIFF_CHANGE_SELECTOR,
+} from '@/lib/rendered-diff/diff-decorations';
+import { closeTimelineDiff, type TimelineDiffView } from '@/lib/timeline-diff-store';
+import {
+ HISTORICAL_CONTENT_CACHE_LIMIT,
+ useTimelineEntryDiff,
+} from '@/lib/use-timeline-entry-diff';
+
+const LazyActivityPanelDiffView = lazy(async () => {
+ const mod = await import('@/components/ActivityPanelDiffView');
+ return { default: mod.ActivityPanelDiffView };
+});
+
+interface TimelineDiffPaneProps {
+ view: TimelineDiffView;
+ /** DocPanel collapsed state + toggle — the pane overlays the editor toolbar
+ * that normally owns this control, so it surfaces its own. */
+ isPanelCollapsed: boolean;
+ onTogglePanel: () => void;
+}
+
+export function TimelineDiffPane({ view, isPanelCollapsed, onTogglePanel }: TimelineDiffPaneProps) {
+ const { t } = useLingui();
+ const { docName, sha, parentSha, laterEdits, authorName, relativeTime } = view;
+ const [cache] = useState(() => new LruStringCache(HISTORICAL_CONTENT_CACHE_LIMIT));
+ // Rendered (WYSIWYG inline track-changes) is the default; Source is the raw
+ // unified-diff view and the engine-failure fallback.
+ const [renderMode, setRenderMode] = useState<'rendered' | 'source'>('rendered');
+ const [dialogOpen, setDialogOpen] = useState(false);
+ const [restoring, setRestoring] = useState(false);
+ const abortRef = useRef<AbortController | null>(null);
+ const diffBodyRef = useRef<HTMLDivElement>(null);
+ const [currentChange, setCurrentChange] = useState(0);
+ // The pane always shows "what changed in this version" (diff vs the previous
+ // version). There is no vs-live mode — the only thing it told you (what a
+ // restore would undo) lives in the Restore confirm as a plain count.
+ const result = useTimelineEntryDiff(sha, docName, cache, 'vs-parent', parentSha);
+
+ // Rendered-diff engine result (plain compute, not a hook). `ok === false`
+ // (parse/recreate failure or over the size ceiling) → fall back to Source.
+ const rendered =
+ result.status === 'ready' ? computeRenderedDiff(result.before, result.after) : null;
+ const usingRendered = renderMode === 'rendered' && rendered?.ok === true;
+
+ // Header stepper count: rendered mode counts the engine's change regions;
+ // source mode counts unified-diff hunks.
+ const changeCount =
+ result.status !== 'ready'
+ ? 0
+ : usingRendered && rendered?.ok
+ ? countRenderedDiffAnchors(rendered)
+ : countChangeGroups(result.diff);
+
+ // Scroll to the Nth change (wraps). Anchors are re-read from the live DOM each
+ // call so they stay valid across re-renders — rendered mode marks changes with
+ // `.ok-diff-*` decoration DOM; source mode with react-diff-view change rows.
+ function goToChange(next: number): void {
+ const container = diffBodyRef.current;
+ if (!container) return;
+ const anchors = usingRendered
+ ? Array.from(container.querySelectorAll<HTMLElement>(RENDERED_DIFF_CHANGE_SELECTOR))
+ : collectChangeAnchors(container);
+ if (anchors.length === 0) return;
+ const clamped = (next + anchors.length) % anchors.length;
+ setCurrentChange(clamped);
+ anchors[clamped]?.scrollIntoView({ block: 'center', behavior: 'smooth' });
+ }
+
+ // Abort an in-flight restore if the pane unmounts (close / doc nav).
+ useEffect(() => {
+ return () => abortRef.current?.abort();
+ }, []);
+
+ // The diff is whole-file, so jump to the first changed line once it renders.
+ const diffKey = result.status === 'ready' ? `${renderMode}:${result.diff}` : '';
+ useEffect(() => {
+ const container = diffBodyRef.current;
+ if (diffKey === '' || !container) return;
+ setCurrentChange(0);
+
+ let done = false;
+ let observer: MutationObserver | null = null;
+ let settleTimer: ReturnType<typeof setTimeout> | undefined;
+ let rafId: number | undefined;
+
+ const scrollToFirstChange = (): void => {
+ if (done) return;
+ // First rendered-diff decoration, else first source-diff change row.
+ const el =
+ container.querySelector<HTMLElement>(RENDERED_DIFF_CHANGE_SELECTOR) ??
+ collectChangeAnchors(container)[0];
+ if (!el) return;
+ done = true;
+ observer?.disconnect();
+ const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
+ el.scrollIntoView({ block: 'center', behavior: reduceMotion ? 'auto' : 'smooth' });
+ };
+
+ // Debounce: reset on every mutation so we only fire once the diff DOM has
+ // stopped changing for `settleMs`. The double rAF lets that final batch
+ // paint before we measure.
+ 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);
+ });
+ }, settleMs);
+ };
+
+ observer = new MutationObserver(scheduleAfterSettle);
+ observer.observe(container, { childList: true, subtree: true });
+ // Kick once for the case where the anchor is already present and no further
+ // mutations arrive to trigger the observer.
+ scheduleAfterSettle();
+
+ const failsafe = setTimeout(() => observer?.disconnect(), 5000);
+ return () => {
+ observer?.disconnect();
+ if (settleTimer !== undefined) clearTimeout(settleTimer);
+ if (rafId !== undefined) cancelAnimationFrame(rafId);
+ clearTimeout(failsafe);
+ };
+ }, [diffKey]);
+
+ // Esc closes the pane — parity with a full-screen overlay's expected dismiss.
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent): void => {
+ if (e.key === 'Escape' && !dialogOpen) closeTimelineDiff();
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [dialogOpen]);
+
+ // No try/finally: the React Compiler cannot lower a `finally` clause in a
+ // component-nested function (same constraint that hoisted pollHistoryOnce in
+ // TimelinePanel). `cleanup()` is called explicitly at each exit instead.
+ async function handleRestore(): Promise<void> {
+ setRestoring(true);
+ const controller = new AbortController();
+ abortRef.current = controller;
+
+ function cleanup(): void {
+ if (!controller.signal.aborted) setRestoring(false);
+ if (abortRef.current === controller) abortRef.current = null;
+ }
+
+ let res: Response;
+ try {
+ res = await fetch('/api/rollback', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ docName, commitSha: sha }),
+ signal: controller.signal,
+ });
+ } catch (err) {
+ if (
+ !controller.signal.aborted &&
+ !(err instanceof DOMException && err.name === 'AbortError')
+ ) {
+ toast.error(t`Restore failed — document unchanged`, { duration: 4000 });
+ }
+ cleanup();
+ return;
+ }
+
+ if (controller.signal.aborted) {
+ cleanup();
+ return;
+ }
+ if (res.ok) {
+ cleanup();
+ setDialogOpen(false);
+ closeTimelineDiff();
+ return;
+ }
+ let detail = `HTTP ${res.status}`;
+ try {
+ const problem = ProblemDetailsSchema.safeParse(await res.json());
+ if (problem.success) detail = problem.data.title;
+ } catch {
+ // non-JSON body; keep status detail
+ }
+ toast.error(t`Restore failed`, { description: detail, duration: 6000 });
+ cleanup();
+ }
+
+ const showStat = result.status === 'ready' && (result.additions > 0 || result.deletions > 0);
+
+ return (
+ <div
+ className="absolute inset-0 z-20 flex flex-col bg-background"
+ data-testid="timeline-diff-pane"
+ >
+ {/* Header spans the pane: close · title · [stat · mode · render · restore].
+ The control cluster wraps to a second row on a narrow pane instead of
+ clipping off the right edge. */}
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1.5 border-b border-border px-3 py-2">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-7 shrink-0"
+ data-testid="timeline-diff-close"
+ aria-label={t`Close diff`}
+ onClick={() => closeTimelineDiff()}
+ >
+ <X className="size-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">{t`Close diff`}</TooltipContent>
+ </Tooltip>
+
+ <div className="min-w-[8rem] flex-1">
+ <div className="truncate text-sm font-medium text-foreground">{docName}</div>
+ <div className="truncate text-xs text-muted-foreground">
+ {authorName} · {relativeTime}
+ </div>
+ </div>
+
+ <div className="ml-auto flex flex-wrap items-center justify-end gap-2">
+ {showStat && result.status === 'ready' && (
+ <span
+ role="img"
+ className="shrink-0 text-xs tabular-nums"
+ data-testid="timeline-diff-stat"
+ aria-label={t`${result.additions} added, ${result.deletions} removed`}
+ >
+ <span aria-hidden="true" className="text-emerald-600 dark:text-emerald-500">
+ +{result.additions}
+ </span>{' '}
+ <span aria-hidden="true" className="text-red-600 dark:text-red-500">
+ −{result.deletions}
+ </span>
+ </span>
+ )}
+
+ <ToggleGroup
+ type="single"
+ value={renderMode}
+ onValueChange={(v) => {
+ if (v === 'rendered' || v === 'source') setRenderMode(v);
+ }}
+ aria-label={t`Diff render mode`}
+ variant="segmented"
+ size="sm"
+ spacing={1}
+ className="shrink-0 rounded-md bg-muted p-0.5 dark:bg-background"
+ >
+ <ToggleGroupItem
+ value="rendered"
+ className="h-6 px-2 text-xs"
+ data-testid="timeline-diff-render-rendered"
+ >
+ <Trans>Rendered</Trans>
+ </ToggleGroupItem>
+ <ToggleGroupItem
+ value="source"
+ className="h-6 px-2 text-xs"
+ data-testid="timeline-diff-render-source"
+ >
+ <Trans>Source</Trans>
+ </ToggleGroupItem>
+ </ToggleGroup>
+
+ {changeCount > 1 && (
+ <div className="flex shrink-0 items-center gap-0.5 rounded-md border border-border bg-muted/40 p-0.5 dark:bg-background">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-6"
+ aria-label={t`Previous change`}
+ data-testid="timeline-diff-prev"
+ onClick={() => goToChange(currentChange - 1)}
+ >
+ <ChevronUp className="size-3.5" />
+ </Button>
+ <span
+ className="px-0.5 text-xs tabular-nums text-muted-foreground"
+ aria-live="polite"
+ >
+ {currentChange + 1} / {changeCount}
+ </span>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-6"
+ aria-label={t`Next change`}
+ data-testid="timeline-diff-next"
+ onClick={() => goToChange(currentChange + 1)}
+ >
+ <ChevronDown className="size-3.5" />
+ </Button>
+ </div>
+ )}
+
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 shrink-0"
+ data-testid="timeline-diff-restore"
+ disabled={restoring}
+ onClick={() => (laterEdits > 0 ? setDialogOpen(true) : handleRestore())}
+ >
+ {restoring ? (
+ <Loader2 className="mr-1.5 size-3.5 animate-spin" />
+ ) : (
+ <Undo2 className="mr-1.5 size-3.5" />
+ )}
+ <Trans>Restore</Trans>
+ </Button>
+
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-7 shrink-0"
+ data-testid="timeline-diff-toggle-panel"
+ aria-label={isPanelCollapsed ? t`Show panel` : t`Hide panel`}
+ aria-expanded={!isPanelCollapsed}
+ onClick={onTogglePanel}
+ >
+ {isPanelCollapsed ? (
+ <PanelRightOpen className="size-4" />
+ ) : (
+ <PanelRightClose className="size-4" />
+ )}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ {isPanelCollapsed ? t`Show panel` : t`Hide panel`}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+
+ {/* Diff body — scrolls independently of the header. */}
+ <div ref={diffBodyRef} className="min-h-0 flex-1 overflow-auto subtle-scrollbar">
+ {result.status === 'loading' && (
+ <div className="flex items-center gap-2 px-4 py-3 text-xs text-muted-foreground">
+ <Loader2 className="size-3 animate-spin" />
+ <Trans>Loading diff</Trans>
+ </div>
+ )}
+ {result.status === 'error' && (
+ <p className="px-4 py-3 text-xs text-destructive">
+ <Trans>Diff unavailable</Trans>
+ </p>
+ )}
+ {result.status === 'ready' &&
+ (renderMode === 'rendered' && rendered?.ok ? (
+ // Rendered (WYSIWYG) inline track-changes. Also the no-change path:
+ // with zero changes it renders the document plain.
+ <RenderedDiffView diff={rendered} />
+ ) : result.diff === '' ? (
+ // Source mode, no net content change (frontmatter- or whitespace-
+ // only edit) — say so, then show the document unchanged.
+ <>
+ <p className="border-b border-border px-4 py-2 text-xs text-muted-foreground italic">
+ <Trans>No content changes in this version</Trans>
+ </p>
+ <pre className="whitespace-pre-wrap px-4 py-3 font-mono text-xs text-foreground/90">
+ {result.after}
+ </pre>
+ </>
+ ) : (
+ <Suspense
+ fallback={
+ <div className="flex items-center gap-2 px-4 py-3 text-xs text-muted-foreground">
+ <Loader2 className="size-3 animate-spin" />
+ <Trans>Loading diff renderer</Trans>
+ </div>
+ }
+ >
+ <LazyActivityPanelDiffView diff={result.diff} viewType="unified" />
+ </Suspense>
+ ))}
+ </div>
+
+ <Dialog
+ open={dialogOpen}
+ onOpenChange={(next) => {
+ if (!next && !restoring) setDialogOpen(false);
+ else if (next) setDialogOpen(true);
+ }}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t`Restore to this version?`}</DialogTitle>
+ <DialogDescription>
+ <Plural
+ value={laterEdits}
+ one="Rolls back # later edit."
+ other="Rolls back # later edits."
+ />{' '}
+ <Trans>Your current version is saved first, so this is reversible.</Trans>
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button
+ variant="outline"
+ data-testid="timeline-diff-restore-cancel"
+ onClick={() => setDialogOpen(false)}
+ >
+ <Trans>Cancel</Trans>
+ </Button>
+ <Button
+ variant="destructive"
+ data-testid="timeline-diff-restore-confirm"
+ disabled={restoring}
+ onClick={() => handleRestore()}
+ >
+ {restoring ? <Loader2 className="mr-2 size-4 animate-spin" /> : null}
+ <Trans>Restore</Trans>
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
diff --git a/packages/app/src/components/TimelinePanel.dom.test.tsx b/packages/app/src/components/TimelinePanel.dom.test.tsx
index a5bd3e274..d1b60b4d8 100644
--- a/packages/app/src/components/TimelinePanel.dom.test.tsx
+++ b/packages/app/src/components/TimelinePanel.dom.test.tsx
@@ -93,7 +93,7 @@ function mockHistory(entries: TimelineEntry[]) {
function renderTimeline() {
return render(
<TooltipProvider>
- <TimelineContent docName="notes" diffLayout="unified" onDiffLayoutChange={() => {}} />
+ <TimelineContent docName="notes" />
</TooltipProvider>,
);
}
@@ -110,7 +110,7 @@ describe('TimelineContent — actor/system commits only', () => {
// Two WIP rows render; the interleaved checkpoint row is dropped.
await waitFor(() => {
- expect(screen.getAllByTestId('timeline-entry-expand')).toHaveLength(2);
+ expect(screen.getAllByTestId('timeline-entry-open')).toHaveLength(2);
});
expect(screen.getByText('Alice')).toBeTruthy();
expect(screen.getByText('Bob')).toBeTruthy();
@@ -128,7 +128,7 @@ describe('TimelineContent — actor/system commits only', () => {
renderTimeline();
await waitFor(() => {
- expect(screen.getAllByTestId('timeline-entry-expand')).toHaveLength(2);
+ expect(screen.getAllByTestId('timeline-entry-open')).toHaveLength(2);
});
expect(screen.getByText('Alice')).toBeTruthy();
expect(screen.getByText('Upstream sync')).toBeTruthy();
@@ -142,7 +142,7 @@ describe('TimelineContent — actor/system commits only', () => {
await waitFor(() => {
expect(screen.getByText('No history yet')).toBeTruthy();
});
- expect(screen.queryAllByTestId('timeline-entry-expand')).toHaveLength(0);
+ expect(screen.queryAllByTestId('timeline-entry-open')).toHaveLength(0);
});
test('the panel header has no Save Version control', async () => {
diff --git a/packages/app/src/components/TimelinePanel.tsx b/packages/app/src/components/TimelinePanel.tsx
index fabaf9a8b..8cd8c0884 100644
--- a/packages/app/src/components/TimelinePanel.tsx
+++ b/packages/app/src/components/TimelinePanel.tsx
@@ -13,25 +13,18 @@
* visible (the server walks their ancestry), so dropping the checkpoint rows
* loses no edit history.
*
- * Per-row UX (shape parity with AgentActivityPanel's burst rows):
- * - Click anywhere on a row except the Restore icon → toggle inline expand.
- * Expanded rows render <ActivityPanelDiffView> below the header showing
- * the diff between that commit and the live Y.Text. Multi-expand is
- * supported; the displayed diff is a snapshot at expand time. Expansion
- * state is lifted to TimelineContent (Set<sha>), so a successful restore
- * can collapse every row in one place — no per-row signal counter, no
- * late-mount no-op effects.
- * - The per-row Restore icon (lucide Undo2, ghost variant, hover-destructive
- * on the icon) sits in the row header and is always visible — both
- * collapsed and expanded states. Click → shadcn Dialog confirmation →
- * POST /api/rollback. Cancel aborts the in-flight fetch via
- * AbortController so a mid-confirm cancel is honored. On success the row
- * collapses and any other expanded rows from this mount also collapse —
- * their cached `current` baseline is now stale.
- * - The diff renderer is loaded lazily under React.Suspense so the
- * react-diff-view bundle + CSS only land in the editor route once a user
- * actually expands a Timeline entry — matching the AgentActivityPanel
- * burst-row precedent.
+ * Per-row UX:
+ * - Click a row → open the version's "what changed" diff in the main editor
+ * pane (full-pane overlay, `TimelineDiffPane`), driven by `timeline-diff-store`.
+ * The active row is highlighted while its diff is open. There is no inline
+ * expand and no mode toggle — a version always shows what it changed vs the
+ * previous version.
+ * - The per-row Restore icon (lucide Undo2, ghost variant, hover-destructive)
+ * sits in the row header. Restore rolls back to that version via
+ * POST /api/rollback; the confirm dialog names how many later edits it
+ * undoes (`laterEdits` = the row's index). For the latest version
+ * (`laterEdits === 0`) there is nothing to roll back, so restore is instant
+ * with no confirm. Cancel aborts the in-flight fetch via AbortController.
*/
import {
AGENT_ICON_COLORS,
@@ -42,31 +35,24 @@ import {
type TimelineEntry,
} from '@inkeep/open-knowledge-core';
import { plural, t } from '@lingui/core/macro';
-import { Trans, useLingui } from '@lingui/react/macro';
-import type { LucideProps } from 'lucide-react';
+import { Plural, Trans, useLingui } from '@lingui/react/macro';
import {
ArrowDownToLine,
+ ArrowLeftRight,
ChevronDown,
ChevronRight,
- Columns2,
GitBranch,
HardDrive,
Loader2,
- Rows2,
+ RotateCcw,
Sparkles,
Undo2,
User,
} from 'lucide-react';
import { useTheme } from 'next-themes';
-import { lazy, Suspense, type SVGProps, useEffect, useId, useRef, useState } from 'react';
+import { useEffect, useId, useRef, useState } from 'react';
import { toast } from 'sonner';
-import type { DiffLayout } from '@/components/DiffView';
-import { ClaudeIcon } from '@/components/icons/claude';
-import { ClineIcon } from '@/components/icons/cline';
-import { CodexIcon } from '@/components/icons/codex';
-import { CopilotIcon } from '@/components/icons/copilot';
-import { CursorIcon } from '@/components/icons/cursor';
-import { WindsurfIcon } from '@/components/icons/windsurf';
+import { AgentIcon } from '@/components/icons/AgentIcon';
import { Button } from '@/components/ui/button';
import {
Dialog,
@@ -78,19 +64,14 @@ import {
} from '@/components/ui/dialog';
import { PanelHeader, PanelTitle } from '@/components/ui/panel';
import { Skeleton } from '@/components/ui/skeleton';
-import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
-import { LruStringCache } from '@/lib/lru-string-cache';
+import { closeAgentDiff } from '@/lib/agent-diff-store';
import { createSelfSchedulingPoll, type PollOutcome } from '@/lib/self-scheduling-poll';
import {
- HISTORICAL_CONTENT_CACHE_LIMIT,
- useTimelineEntryDiff,
-} from '@/lib/use-timeline-entry-diff';
-
-const LazyActivityPanelDiffView = lazy(async () => {
- const mod = await import('@/components/ActivityPanelDiffView');
- return { default: mod.ActivityPanelDiffView };
-});
+ closeTimelineDiff,
+ openTimelineDiff,
+ useTimelineDiffView,
+} from '@/lib/timeline-diff-store';
// History poll cadence. The loop is SELF-SCHEDULING: the
// next poll is armed only after the previous one settles, so a slow query on a
@@ -151,8 +132,6 @@ async function pollHistoryOnce(
interface TimelineContentProps {
docName: string;
- diffLayout: DiffLayout;
- onDiffLayoutChange: (layout: DiffLayout) => void;
}
// ─── Helpers ─────────────────────────────────────────────────────────────────
@@ -188,8 +167,34 @@ function formatAbsoluteTime(isoString: string): string {
});
}
-function shortSha(sha: string): string {
- return sha.slice(0, 7);
+/**
+ * Classify a timeline entry from its commit subject into a friendly descriptor,
+ * so the row shows "Restored to the version from …" / "Renamed …" instead of the
+ * raw `rollback: doc to a1b2c3d` / `rename: a -> b` subject. `edit` is the
+ * default — those rows fall back to the agent summary / doc list as before.
+ */
+type EntryDescriptor =
+ | { kind: 'restore'; targetSha7: string }
+ | { kind: 'rename'; from: string; to: string }
+ | { kind: 'reconcile' }
+ | { kind: 'upstream' }
+ | { kind: 'edit' };
+
+function classifyEntry(entry: TimelineEntry): EntryDescriptor {
+ if (entry.type === 'upstream') return { kind: 'upstream' };
+ const msg = entry.message;
+ const rollback = /^rollback: .+ to ([0-9a-f]{7,40})$/.exec(msg);
+ if (rollback) return { kind: 'restore', targetSha7: rollback[1].slice(0, 7) };
+ const rename = /^rename: (.+) -> (.+)$/.exec(msg);
+ if (rename) return { kind: 'rename', from: rename[1], to: rename[2] };
+ if (msg.startsWith('reconcile: ')) return { kind: 'reconcile' };
+ if (msg.startsWith('import: ')) return { kind: 'upstream' };
+ return { kind: 'edit' };
+}
+
+/** Basename of a doc path, for compact rename labels. */
+function docLeaf(path: string): string {
+ return path.split('/').pop() ?? path;
}
/** Map internal author names to user-friendly display names. Uses structured contributors when available. */
@@ -202,16 +207,6 @@ function displayAuthor(entry: TimelineEntry): string {
return entry.author;
}
-function AgentBrandIcon({ icon, ...props }: { icon?: string } & SVGProps<SVGSVGElement>) {
- if (icon === 'claude') return <ClaudeIcon {...props} />;
- if (icon === 'cursor') return <CursorIcon {...props} />;
- if (icon === 'windsurf') return <WindsurfIcon {...props} />;
- if (icon === 'openai') return <CodexIcon {...props} />;
- if (icon === 'cline') return <ClineIcon {...props} />;
- if (icon === 'github') return <CopilotIcon {...props} />;
- return <Sparkles strokeWidth={1.5} {...(props as LucideProps)} />;
-}
-
/** Icon for a timeline entry contributor. Brand icons for agents, lucide icons for system writers. */
function ContributorIcon({ entry, isDark }: { entry: TimelineEntry; isDark: boolean }) {
const iconClass = 'size-3.5 shrink-0 text-muted-foreground';
@@ -230,7 +225,7 @@ function ContributorIcon({ entry, isDark }: { entry: TimelineEntry; isDark: bool
// Known agent brand → brand icon with brand color (dark override when available)
if (icon !== 'bot') {
return (
- <AgentBrandIcon icon={icon} width={14} height={14} className="shrink-0" style={{ color }} />
+ <AgentIcon icon={icon} width={14} height={14} className="shrink-0" style={{ color }} />
);
}
@@ -354,90 +349,131 @@ function SummaryBullets({ summaries }: SummaryBulletsProps) {
);
}
-// ─── Inline diff panel ───────────────────────────────────────────────────────
-
-interface EntryDiffPanelProps {
- sha: string;
- docName: string;
- cache: LruStringCache;
- diffLayout: DiffLayout;
- panelId: string;
-}
+// ─── Entry row ────────────────────────────────────────────────────────────────
/**
- * Renders only when its parent expanded the row. Splitting this out from
- * EntryRow keeps the `useTimelineEntryDiff` subscription off collapsed rows
- * — no `useDocumentContext` subscription, no effect on activeProvider
- * churn. The lazy-loaded diff renderer also lives inside this gated subtree
- * so the react-diff-view bundle never lands for users who don't expand
- * Timeline rows.
+ * Row-2 detail line, chosen by the entry's classified kind. A restore renders
+ * "Restored to the version from <date>" and — when the target version is on the
+ * loaded page — links to it (click scrolls + flashes that row). Other kinds get
+ * a friendly label instead of the raw commit subject; ordinary edits fall back
+ * to the doc list.
*/
-function EntryDiffPanel({ sha, docName, cache, diffLayout, panelId }: EntryDiffPanelProps) {
- const result = useTimelineEntryDiff(sha, docName, cache);
+function EntryDetail({
+ descriptor,
+ allDocs,
+ versionBySha7,
+ onJumpToVersion,
+}: {
+ descriptor: EntryDescriptor;
+ allDocs: string[];
+ versionBySha7: Map<string, TimelineEntry>;
+ onJumpToVersion: (sha7: string) => void;
+}) {
+ const { t } = useLingui();
- return (
- <div id={panelId} className="px-3 pb-2" data-testid="timeline-entry-diff">
- {result.status === 'loading' && (
- <div className="flex items-center gap-2 py-2 text-xs text-muted-foreground">
- <Loader2 className="size-3 animate-spin" />
- <Trans>Loading diff</Trans>
- </div>
- )}
- {result.status === 'error' && (
- <p className="py-2 text-xs text-destructive">
- <Trans>Diff unavailable</Trans>
- </p>
- )}
- {result.status === 'ready' && (
- <Suspense
- fallback={
- <div className="flex items-center gap-2 py-2 text-xs text-muted-foreground">
- <Loader2 className="size-3 animate-spin" />
- <Trans>Loading diff renderer</Trans>
- </div>
- }
- >
- <LazyActivityPanelDiffView diff={result.diff} viewType={diffLayout} />
- </Suspense>
- )}
- </div>
- );
-}
+ if (descriptor.kind === 'restore') {
+ const target = versionBySha7.get(descriptor.targetSha7);
+ const label = target
+ ? t`Restored to the version from ${formatAbsoluteTime(target.timestamp)}`
+ : t`Restored an earlier version (${descriptor.targetSha7})`;
+ return (
+ <div className="flex items-center gap-1 text-xs text-muted-foreground">
+ <RotateCcw className="size-3 shrink-0" aria-hidden />
+ {target ? (
+ <button
+ type="button"
+ className="truncate text-left underline-offset-2 hover:text-foreground hover:underline"
+ title={label}
+ onClick={(e) => {
+ e.stopPropagation();
+ onJumpToVersion(descriptor.targetSha7);
+ }}
+ >
+ {label}
+ </button>
+ ) : (
+ <span className="truncate" title={label}>
+ {label}
+ </span>
+ )}
+ </div>
+ );
+ }
-// ─── Entry row ────────────────────────────────────────────────────────────────
+ if (descriptor.kind === 'rename') {
+ return (
+ <p
+ className="flex items-center gap-1 truncate text-xs text-muted-foreground"
+ title={`${descriptor.from} → ${descriptor.to}`}
+ >
+ <ArrowLeftRight className="size-3 shrink-0" aria-hidden />
+ <span className="truncate">
+ {t`Renamed ${docLeaf(descriptor.from)} → ${docLeaf(descriptor.to)}`}
+ </span>
+ </p>
+ );
+ }
+
+ if (descriptor.kind === 'reconcile') {
+ return <p className="truncate text-xs text-muted-foreground">{t`Synced from disk`}</p>;
+ }
+
+ if (allDocs.length > 0) {
+ return (
+ <p className="truncate text-xs text-muted-foreground" title={allDocs.join(', ')}>
+ {allDocs.join(', ')}
+ </p>
+ );
+ }
+
+ // Upstream syncs already say "Upstream sync" on the author line (displayAuthor)
+ // — a detail line would just repeat it, so render none.
+ if (descriptor.kind === 'upstream') return null;
+
+ return <p className="truncate text-xs text-muted-foreground">{t`Edited`}</p>;
+}
interface EntryRowProps {
entry: TimelineEntry;
isDark: boolean;
- diffLayout: DiffLayout;
- cache: LruStringCache;
docName: string;
- expanded: boolean;
- onToggleExpanded: (sha: string) => void;
+ /** Number of newer versions above this row — what a restore rolls back. */
+ laterEdits: number;
onRestoreSuccess: () => void;
+ /** Resolve a 7-char SHA to the version it points at (for restore-row labels). */
+ versionBySha7: Map<string, TimelineEntry>;
+ /** Scroll to + flash the version a restore row points at. */
+ onJumpToVersion: (sha7: string) => void;
+ /** Register this row's element so a jump can scroll it into view. */
+ registerRowRef: (el: HTMLDivElement | null) => void;
+ /** True while this row is the flash target of a just-clicked jump. */
+ flashing: boolean;
}
function EntryRow({
entry,
isDark,
- diffLayout,
- cache,
docName,
- expanded,
- onToggleExpanded,
+ laterEdits,
onRestoreSuccess,
+ versionBySha7,
+ onJumpToVersion,
+ registerRowRef,
+ flashing,
}: EntryRowProps) {
const { t } = useLingui();
const relative = formatRelativeTime(entry.timestamp);
const authorName = displayAuthor(entry);
const absoluteTime = formatAbsoluteTime(entry.timestamp);
- const entrySha = shortSha(entry.sha);
const allDocs = entry.contributors.flatMap((c) => c.docs);
const allSummaries = allSummariesFor(entry);
+ const descriptor = classifyEntry(entry);
const [dialogOpen, setDialogOpen] = useState(false);
const [restoring, setRestoring] = useState(false);
const abortRef = useRef<AbortController | null>(null);
- const diffPanelId = useId();
+ // Highlight the row whose diff is currently open in the main pane.
+ const activeDiff = useTimelineDiffView();
+ const isActive = activeDiff?.docName === docName && activeDiff.sha === entry.sha;
// Aborting an in-flight restore on unmount avoids state writes on a
// disposed component if the response lands after the user navigated away.
@@ -445,7 +481,21 @@ function EntryRow({
return () => abortRef.current?.abort();
}, []);
- const handleActivate = () => onToggleExpanded(entry.sha);
+ // Open the full-pane "what changed" diff in the main editor pane. The two
+ // full-pane diffs share one overlay slot — close the agent diff so they
+ // can't both paint.
+ const handleActivate = () => {
+ closeAgentDiff();
+ openTimelineDiff({
+ docName,
+ sha: entry.sha,
+ parentSha: entry.parentSha ?? null,
+ laterEdits,
+ authorName,
+ relativeTime: relative,
+ absoluteTime,
+ });
+ };
function handleCancelDialog() {
// Cancel honors the user's intent: any in-flight rollback is aborted so
@@ -516,17 +566,22 @@ function EntryRow({
return (
<>
- <div className="flex flex-col rounded-lg">
+ <div
+ ref={registerRowRef}
+ className={[
+ 'flex flex-col rounded-lg transition-shadow',
+ flashing ? 'ring-2 ring-ring ring-offset-1 ring-offset-background' : '',
+ ].join(' ')}
+ >
{/* biome-ignore lint/a11y/useSemanticElements: row contains a nested SummaryBullets expander and a Restore <button>; native nested buttons inside a <button> are invalid HTML, so the row uses div[role=button] to preserve keyboard activation while allowing the nested interactive children. */}
<div
role="button"
tabIndex={0}
- aria-expanded={expanded}
- aria-controls={expanded ? diffPanelId : undefined}
- data-testid="timeline-entry-expand"
+ aria-pressed={isActive}
+ data-testid="timeline-entry-open"
className={[
'group flex w-full items-start gap-2.5 rounded-lg px-3 py-2.5 text-left transition-colors cursor-pointer outline-none focus-visible:ring-2 focus-visible:ring-ring',
- expanded ? 'bg-muted' : 'hover:bg-muted/80',
+ isActive ? 'bg-muted' : 'hover:bg-muted/80',
].join(' ')}
onClick={handleActivate}
onKeyDown={(e) => {
@@ -564,7 +619,8 @@ function EntryRow({
disabled={restoring}
onClick={(e) => {
e.stopPropagation();
- setDialogOpen(true);
+ if (laterEdits > 0) setDialogOpen(true);
+ else handleRestore();
}}
>
{restoring ? (
@@ -580,27 +636,14 @@ function EntryRow({
{/* Row 2: details, aligned with title start */}
{allSummaries.length > 0 && <SummaryBullets summaries={allSummaries} />}
- {allDocs.length > 0 ? (
- <p className="truncate text-xs text-muted-foreground" title={allDocs.join(', ')}>
- {allDocs.join(', ')}
- </p>
- ) : (
- <p className="truncate text-xs text-muted-foreground" title={entry.message}>
- {entry.message}
- </p>
- )}
+ <EntryDetail
+ descriptor={descriptor}
+ allDocs={allDocs}
+ versionBySha7={versionBySha7}
+ onJumpToVersion={onJumpToVersion}
+ />
</div>
</div>
-
- {expanded && (
- <EntryDiffPanel
- sha={entry.sha}
- docName={docName}
- cache={cache}
- diffLayout={diffLayout}
- panelId={diffPanelId}
- />
- )}
</div>
<Dialog
@@ -612,16 +655,14 @@ function EntryRow({
>
<DialogContent>
<DialogHeader>
- <DialogTitle>{t`Restore to this point?`}</DialogTitle>
+ <DialogTitle>{t`Restore to this version?`}</DialogTitle>
<DialogDescription>
- <Trans>
- This will replace the current document content with the version from{' '}
- <span className="font-medium text-foreground">
- {relative} ({absoluteTime}, {entrySha})
- </span>{' '}
- by <span className="font-medium text-foreground">{authorName}</span>. Your current
- content is already saved in the timeline — you can restore it anytime.
- </Trans>
+ <Plural
+ value={laterEdits}
+ one="Rolls back # later edit."
+ other="Rolls back # later edits."
+ />{' '}
+ <Trans>Your current version is saved first, so this is reversible.</Trans>
</DialogDescription>
</DialogHeader>
<DialogFooter>
@@ -650,36 +691,39 @@ function EntryRow({
// ─── Main content (no Sheet wrapper) ─────────────────────────────────────────
-export function TimelineContent({ docName, diffLayout, onDiffLayoutChange }: TimelineContentProps) {
+export function TimelineContent({ docName }: TimelineContentProps) {
const { t } = useLingui();
const { resolvedTheme } = useTheme();
const isDark = resolvedTheme === 'dark';
const [entries, setEntries] = useState<TimelineEntry[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
- const [cache] = useState(() => new LruStringCache(HISTORICAL_CONTENT_CACHE_LIMIT));
- const [expandedShas, setExpandedShas] = useState<Set<string>>(() => new Set());
-
- // Reset expansion + cache on doc nav. The parent intentionally does not key
- // <TimelineContent> on docName (it would force a re-mount on every nav and
- // throw away the polling timer), so we clear locally.
- // biome-ignore lint/correctness/useExhaustiveDependencies: cache is a stable useState-initialized instance — including it in deps would not change behavior but reads as a noisier signal of "this effect depends on the cache" when in fact it depends only on the active doc.
- useEffect(() => {
- setExpandedShas(new Set());
- cache.clear();
- }, [docName]);
-
- function toggleExpanded(sha: string) {
- setExpandedShas((prev) => {
- const next = new Set(prev);
- if (next.has(sha)) next.delete(sha);
- else next.add(sha);
- return next;
- });
+ // Row elements keyed by full SHA, so a restore row can scroll its target into
+ // view; `flashSha` briefly rings that target after the jump.
+ const rowRefs = useRef(new Map<string, HTMLDivElement>());
+ const [flashSha, setFlashSha] = useState<string | null>(null);
+ const flashTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ // 7-char SHA → version, so a `rollback: … to <sha7>` row can name and link the
+ // version it restored (only versions on the loaded page resolve).
+ const versionBySha7 = new Map<string, TimelineEntry>();
+ for (const e of entries) versionBySha7.set(e.sha.slice(0, 7), e);
+
+ useEffect(() => () => clearTimeout(flashTimer.current ?? undefined), []);
+
+ function handleJumpToVersion(sha7: string) {
+ const target = versionBySha7.get(sha7);
+ if (!target) return;
+ rowRefs.current.get(target.sha)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ setFlashSha(target.sha);
+ clearTimeout(flashTimer.current ?? undefined);
+ flashTimer.current = setTimeout(() => setFlashSha(null), 1600);
}
function handleRestoreSuccess() {
- setExpandedShas(new Set());
+ // A restore made the open diff's baseline stale — close the pane. (Doc nav
+ // is handled by EditorArea, which closes the diff when the open doc changes.)
+ closeTimelineDiff();
}
useEffect(() => {
@@ -717,51 +761,14 @@ export function TimelineContent({ docName, diffLayout, onDiffLayoutChange }: Tim
};
}, [docName, t]);
- const hasEntries = !loading && !error && entries.length > 0;
-
return (
<div className="flex h-full flex-col">
- {/* Panel header — uses the shared PanelHeader primitive for parity with
- GraphPanel/LinksPanel (justify-between puts the title left, the
- diff-layout toggle right). The toggle only renders once there are
- entries to diff. */}
+ {/* Panel header. The diff layout (unified/split) toggle moved to the
+ full-pane diff view, where the diff actually renders. */}
<PanelHeader>
<PanelTitle>
<Trans>Timeline</Trans>
</PanelTitle>
-
- {hasEntries && (
- <Tooltip>
- <TooltipTrigger asChild>
- <ToggleGroup
- type="single"
- value={diffLayout}
- onValueChange={(v) => {
- if (v) onDiffLayoutChange(v as DiffLayout);
- }}
- aria-label={t`Diff layout`}
- variant="segmented"
- size="sm"
- spacing={1}
- className="bg-muted dark:bg-background p-0.5 rounded-md shrink-0"
- >
- <ToggleGroupItem
- value="unified"
- aria-label={t`Unified diff`}
- className="size-6 px-0"
- >
- <Rows2 className="size-3.5" />
- </ToggleGroupItem>
- <ToggleGroupItem value="split" aria-label={t`Split diff`} className="size-6 px-0">
- <Columns2 className="size-3.5" />
- </ToggleGroupItem>
- </ToggleGroup>
- </TooltipTrigger>
- <TooltipContent>
- {diffLayout === 'unified' ? <Trans>Unified diff</Trans> : <Trans>Split diff</Trans>}
- </TooltipContent>
- </Tooltip>
- )}
</PanelHeader>
{/* Scrollable entry list */}
<div className="flex-1 overflow-y-auto subtle-scrollbar scroll-fade-mask">
@@ -804,17 +811,21 @@ export function TimelineContent({ docName, diffLayout, onDiffLayoutChange }: Tim
{/* Flat reverse-chronological list of actor/system commits. */}
{!loading && !error && entries.length > 0 && (
<div className="flex flex-col gap-1 p-2">
- {entries.map((entry) => (
+ {entries.map((entry, index) => (
<EntryRow
key={entry.sha}
entry={entry}
isDark={isDark}
- diffLayout={diffLayout}
- cache={cache}
docName={docName}
- expanded={expandedShas.has(entry.sha)}
- onToggleExpanded={toggleExpanded}
+ laterEdits={index}
onRestoreSuccess={handleRestoreSuccess}
+ versionBySha7={versionBySha7}
+ onJumpToVersion={handleJumpToVersion}
+ registerRowRef={(el) => {
+ if (el) rowRefs.current.set(entry.sha, el);
+ else rowRefs.current.delete(entry.sha);
+ }}
+ flashing={flashSha === entry.sha}
/>
))}
</div>
diff --git a/packages/app/src/globals.css b/packages/app/src/globals.css
index c39b16ce6..b06fbe751 100644
--- a/packages/app/src/globals.css
+++ b/packages/app/src/globals.css
@@ -5345,6 +5345,52 @@ html.electron-mode [data-slot="sidebar-inner"] {
@apply font-mono bg-muted text-inherit border border-border rounded-md px-1 py-0.5 text-sm;
}
+/* Rendered (WYSIWYG) Timeline diff — inline track-changes decorations.
+ Scoped under .ProseMirror so they render inside the read-only diff editor's
+ content DOM (RenderedDiffView). `ins`/`del` are decoration classes, not real
+ nodes — see lib/rendered-diff/diff-decorations.ts. */
+.ProseMirror .ok-diff-ins {
+ background-color: color-mix(in srgb, var(--color-emerald-500) 18%, transparent);
+ border-radius: 2px;
+ box-decoration-break: clone;
+ -webkit-box-decoration-break: clone;
+}
+
+/* Whole added block (node decoration on the `<li>`/`<p>`/`<h2>` itself). */
+.ProseMirror .ok-diff-ins-block {
+ background-color: color-mix(in srgb, var(--color-emerald-500) 14%, transparent);
+ border-radius: 2px;
+ padding-inline: 0.25rem;
+ border-left: 2px solid var(--color-emerald-500);
+}
+
+.ProseMirror .ok-diff-del {
+ color: var(--color-red-600);
+ text-decoration: line-through;
+ background-color: color-mix(in srgb, var(--color-red-500) 10%, transparent);
+ border-radius: 2px;
+ opacity: 0.85;
+}
+
+.dark .ProseMirror .ok-diff-del {
+ color: var(--color-red-400);
+}
+
+/* Whole-block deletions render as a struck-through block (removed heading /
+ list / code) rather than an inline run. */
+.ProseMirror .ok-diff-del-block {
+ display: block;
+ margin-block: 0.15em;
+ padding-inline: 0.25rem;
+ border-left: 2px solid var(--color-red-500);
+}
+
+/* Removed content is chrome, not editable document — never show a text caret. */
+.ProseMirror .ok-diff-del,
+.ProseMirror .ok-diff-del * {
+ cursor: default;
+}
+
/* Mermaid WYSIWYG canvas (`mermaid-wysiwyg` package). The package injects its
own `<style data-mw>` at runtime with `--mw-*` custom-property hooks for all
interaction chrome (selection glow, popovers, in-place editors, plus-menus).
diff --git a/packages/app/src/lib/agent-diff-store.ts b/packages/app/src/lib/agent-diff-store.ts
new file mode 100644
index 000000000..3767e6eb8
--- /dev/null
+++ b/packages/app/src/lib/agent-diff-store.ts
@@ -0,0 +1,91 @@
+/**
+ * agent-diff-store — cross-component channel for the full-pane Agent edit diff.
+ * The Agent Activity panel (right DocPanel) picks a file + version; EditorArea
+ * (center pane) reads it and paints `AgentDiffPane` as a full-pane overlay over
+ * the editor. A module store (not DocumentContext) keeps this isolated from the
+ * central context + its test surface, matching `timeline-diff-store` and the
+ * app's other `*-store` channels.
+ *
+ * The view is a file *version*: `keptCount` edits applied (0 = the pre-agent
+ * original, `maxVersions` = now). The pane shows the whole file at that version,
+ * so scrubbing the undo slider walks the file's history. The overlay is per-doc:
+ * EditorArea paints it only while `docName` matches the open document and
+ * navigates to that doc on open (an agent's edits can span other files).
+ */
+import { useSyncExternalStore } from 'react';
+
+export interface AgentDiffView {
+ /** Agent connection id — used to fetch each version's diff. */
+ agentId: string;
+ /** Agent header metadata for the pane header (precomputed by the panel). */
+ agentName: string;
+ agentColor: string;
+ agentIcon?: string;
+ /** Extension-less doc the version belongs to (matched against the open doc). */
+ docName: string;
+ /** Version shown: 0 = original (pre-edit), `maxVersions` = now (all edits). */
+ keptCount: number;
+ /** Total edits on this file — the top of the version range. */
+ maxVersions: number;
+}
+
+let current: AgentDiffView | null = null;
+const listeners = new Set<() => void>();
+
+function notify(): void {
+ for (const listener of listeners) listener();
+}
+
+/** Open the full-pane diff at a file version. Replaces any currently-open one. */
+export function openAgentDiff(view: AgentDiffView): void {
+ current = view;
+ notify();
+}
+
+/** Set the shown version (clamped to `0..maxVersions`). No-op when closed. */
+export function setAgentDiffKept(keptCount: number): void {
+ if (current === null) return;
+ const clamped = Math.max(0, Math.min(keptCount, current.maxVersions));
+ if (clamped === current.keptCount) return;
+ current = { ...current, keptCount: clamped };
+ notify();
+}
+
+/**
+ * Update the version ceiling for the open file from live activity (a new burst
+ * landed / an undo committed). If the handle was pinned to "now" it follows to
+ * the new top; otherwise it just clamps into range. No-op unless a diff for
+ * this (agentId, docName) is open and the ceiling actually changed.
+ */
+export function setAgentDiffMax(agentId: string, docName: string, maxVersions: number): void {
+ if (current === null || current.agentId !== agentId || current.docName !== docName) return;
+ if (current.maxVersions === maxVersions) return;
+ const wasAtNow = current.keptCount === current.maxVersions;
+ const keptCount = wasAtNow ? maxVersions : Math.min(current.keptCount, maxVersions);
+ current = { ...current, maxVersions, keptCount };
+ notify();
+}
+
+/** Close the full-pane diff (no-op when already closed). */
+export function closeAgentDiff(): void {
+ if (current !== null) {
+ current = null;
+ notify();
+ }
+}
+
+function subscribe(callback: () => void): () => void {
+ listeners.add(callback);
+ return () => {
+ listeners.delete(callback);
+ };
+}
+
+function getSnapshot(): AgentDiffView | null {
+ return current;
+}
+
+/** Subscribe to the active full-pane agent diff (null when none is open). */
+export function useAgentDiffView(): AgentDiffView | null {
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+}
diff --git a/packages/app/src/lib/diff-change-nav.ts b/packages/app/src/lib/diff-change-nav.ts
new file mode 100644
index 000000000..b17947863
--- /dev/null
+++ b/packages/app/src/lib/diff-change-nav.ts
@@ -0,0 +1,37 @@
+/**
+ * diff-change-nav — pure helpers for the full-pane diff "change stepper" shared
+ * by `TimelineDiffPane` and `AgentDiffPane`. Both render a whole-file unified
+ * diff and let the user jump between the contiguous changed-line runs.
+ */
+
+/** Count contiguous +/- runs in a unified-diff string — one per "change" for the stepper. */
+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;
+ }
+ return count;
+}
+
+/**
+ * First changed code cell of each consecutive changed-row run, in DOM order —
+ * the scroll anchors for the change stepper. A new run starts whenever a changed
+ * row is not the immediate sibling of the previous changed row (context between).
+ */
+export function collectChangeAnchors(container: HTMLElement): Element[] {
+ const cells = Array.from(container.querySelectorAll('.diff-code-insert, .diff-code-delete'));
+ 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);
+ prevRow = row;
+ }
+ return anchors;
+}
diff --git a/packages/app/src/lib/rendered-diff/block-diff.ts b/packages/app/src/lib/rendered-diff/block-diff.ts
new file mode 100644
index 000000000..c146f2942
--- /dev/null
+++ b/packages/app/src/lib/rendered-diff/block-diff.ts
@@ -0,0 +1,133 @@
+/**
+ * Block-level alignment for the rendered diff. Whole-document word-level diffing
+ * matches individual shared words across reordered/rewritten blocks, producing
+ * unreadable interleaved word-salad. This aligns the two docs at the BLOCK level
+ * instead — unchanged blocks match exactly and vanish; a changed/added/removed
+ * block renders as a whole struck "before" + whole highlighted "after". Legible,
+ * and consistent with how the Source unified diff reads.
+ *
+ * Granularity: top-level document blocks, descending one level into lists so a
+ * single edited list item is one block (not the whole list). A block is keyed by
+ * `type.name` + its text, so an unchanged bullet matches and a reworded one does
+ * not. Formatting-only changes (bold/link toggles, no text change) are handled
+ * separately by the mark-change pass — they intentionally match here as "same".
+ */
+import type { Node as PMNode } from '@tiptap/pm/model';
+
+/** A content change as a before-range (`A`) and after-range (`B`). */
+export interface SpanChange {
+ fromA: number;
+ toA: number;
+ fromB: number;
+ toB: number;
+}
+
+interface Block {
+ /** Position before the node in its document. */
+ from: number;
+ /** Position after the node in its document. */
+ to: number;
+ /** Alignment key — matches an unchanged block, distinguishes a changed one. */
+ key: string;
+}
+
+// This schema uses the mdast-canonical unified `list` node (not `bulletList`/
+// `orderedList`); the others are kept as a safety net for schema variants.
+const LIST_TYPES = new Set(['list', 'bulletList', 'orderedList', 'taskList']);
+
+/**
+ * Flatten a doc into aligned block units: top-level children, but the items of a
+ * top-level list rather than the list as a whole (so one edited item is one unit).
+ */
+function collectBlocks(doc: PMNode): Block[] {
+ const blocks: Block[] = [];
+ doc.forEach((node, offset) => {
+ if (LIST_TYPES.has(node.type.name)) {
+ const listContentStart = offset + 1;
+ let itemOffset = 0;
+ node.forEach((item) => {
+ const from = listContentStart + itemOffset;
+ blocks.push({
+ from,
+ to: from + item.nodeSize,
+ key: `${item.type.name}:${item.textContent}`,
+ });
+ itemOffset += item.nodeSize;
+ });
+ } else {
+ blocks.push({
+ from: offset,
+ to: offset + node.nodeSize,
+ key: `${node.type.name}:${node.textContent}`,
+ });
+ }
+ });
+ return blocks;
+}
+
+type AlignOp = { type: 'same'; b: Block } | { type: 'del'; a: Block } | { type: 'ins'; b: Block };
+
+/**
+ * Longest-common-subsequence alignment of two block lists by key. Ties favor a
+ * deletion first, so a reworded block emits its old form (struck) before its new
+ * form (highlighted), reading "~~old~~ new" like a text replacement.
+ */
+function alignBlocks(before: Block[], after: Block[]): AlignOp[] {
+ const n = before.length;
+ const m = after.length;
+ const dp: number[][] = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(0));
+ for (let i = n - 1; i >= 0; i--) {
+ for (let j = m - 1; j >= 0; j--) {
+ dp[i][j] =
+ before[i].key === after[j].key
+ ? dp[i + 1][j + 1] + 1
+ : Math.max(dp[i + 1][j], dp[i][j + 1]);
+ }
+ }
+ const ops: AlignOp[] = [];
+ let i = 0;
+ let j = 0;
+ while (i < n && j < m) {
+ if (before[i].key === after[j].key) {
+ ops.push({ type: 'same', b: after[j] });
+ i++;
+ j++;
+ } else if (dp[i + 1][j] >= dp[i][j + 1]) {
+ ops.push({ type: 'del', a: before[i] });
+ i++;
+ } else {
+ ops.push({ type: 'ins', b: after[j] });
+ j++;
+ }
+ }
+ while (i < n) ops.push({ type: 'del', a: before[i++] });
+ while (j < m) ops.push({ type: 'ins', b: after[j++] });
+ return ops;
+}
+
+/**
+ * Block-level content changes between two docs. Each deleted block becomes a
+ * zero-width-in-B change carrying its before-range (rendered as a struck widget
+ * anchored where it used to be); each inserted block a zero-width-in-A change
+ * carrying its after-range (highlighted in place). Unchanged blocks produce
+ * nothing. `afterDoc` should be the exact doc that will be rendered so the
+ * after-coordinates line up with the decoration set.
+ */
+export function buildBlockChanges(beforeDoc: PMNode, afterDoc: PMNode): SpanChange[] {
+ const ops = alignBlocks(collectBlocks(beforeDoc), collectBlocks(afterDoc));
+ const changes: SpanChange[] = [];
+ // After-doc cursor: a deletion anchors here — just before the following
+ // inserted/unchanged content, so a reworded block reads old-then-new.
+ let bCursor = 0;
+ for (const op of ops) {
+ if (op.type === 'same') {
+ bCursor = op.b.to;
+ } else if (op.type === 'ins') {
+ changes.push({ fromA: 0, toA: 0, fromB: op.b.from, toB: op.b.to });
+ bCursor = op.b.to;
+ } else {
+ changes.push({ fromA: op.a.from, toA: op.a.to, fromB: bCursor, toB: bCursor });
+ }
+ }
+ return changes;
+}
diff --git a/packages/app/src/lib/rendered-diff/build-rendered-diff.test.ts b/packages/app/src/lib/rendered-diff/build-rendered-diff.test.ts
new file mode 100644
index 000000000..5892228b4
--- /dev/null
+++ b/packages/app/src/lib/rendered-diff/build-rendered-diff.test.ts
@@ -0,0 +1,154 @@
+/**
+ * Unit tests for the rendered-diff engine — pure, no DOM. Exercises the
+ * block-level content diff plus the mark-change pass (from `recreate-transform`)
+ * against the shared markdown schema (core `sharedExtensions`, node-safe) and
+ * asserts the resulting block/mark ranges.
+ */
+
+import { describe, expect, test } from 'bun:test';
+import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
+import { getSchema } from '@tiptap/core';
+import {
+ buildRenderedDiff,
+ RENDERED_DIFF_SIZE_CEILING,
+ type RenderedDiff,
+ type SpanChange,
+} from './build-rendered-diff';
+
+const schema = getSchema(sharedExtensions);
+const md = new MarkdownManager({ extensions: sharedExtensions });
+
+function ok(before: string, after: string): RenderedDiff {
+ const r = buildRenderedDiff(before, after, schema, md);
+ if (!r.ok) throw new Error(`expected ok, got failure: ${r.reason}`);
+ return r;
+}
+
+function counts(changes: readonly SpanChange[]): { ins: number; del: number } {
+ let ins = 0;
+ let del = 0;
+ for (const c of changes) {
+ if (c.toB > c.fromB) ins++;
+ if (c.toA > c.fromA) del++;
+ }
+ return { ins, del };
+}
+
+describe('buildRenderedDiff', () => {
+ test('no change → ok with zero changes', () => {
+ const r = ok('# Title\n\nSame body.', '# Title\n\nSame body.');
+ expect(r.changes.length).toBe(0);
+ });
+
+ test('pure insertion → an inserted range, no deletion', () => {
+ const r = ok('Alpha.\n\nBeta.', 'Alpha.\n\nBeta.\n\nGamma.');
+ const { ins, del } = counts(r.changes);
+ expect(ins).toBeGreaterThan(0);
+ expect(del).toBe(0);
+ });
+
+ test('pure deletion → a deleted range, no insertion', () => {
+ const r = ok('Alpha.\n\nBeta.\n\nGamma.', 'Alpha.\n\nGamma.');
+ const { ins, del } = counts(r.changes);
+ expect(del).toBeGreaterThan(0);
+ expect(ins).toBe(0);
+ });
+
+ test('word replacement → both an insertion and a deletion', () => {
+ const r = ok('The north star guides us.', 'The polar star guides us.');
+ const { ins, del } = counts(r.changes);
+ expect(ins).toBeGreaterThan(0);
+ expect(del).toBeGreaterThan(0);
+ });
+
+ test('reconstructed after-doc round-trips the after body', () => {
+ const before = '# H\n\none';
+ const after = '# H\n\none\n\ntwo';
+ const r = ok(before, after);
+ // afterDoc is the recreated target; serializing it back yields the after body.
+ expect(md.serialize(r.afterDoc.toJSON()).trim()).toBe(after.trim());
+ });
+
+ test('over the size ceiling → ok:false (source fallback)', () => {
+ const huge = 'x'.repeat(RENDERED_DIFF_SIZE_CEILING + 1);
+ const r = buildRenderedDiff(huge, `${huge}!`, schema, md);
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.reason).toBe('ceiling');
+ });
+
+ test('no change → no mark changes either', () => {
+ const r = ok('**Bold** and plain.', '**Bold** and plain.');
+ expect(r.markChanges.length).toBe(0);
+ });
+
+ test('bold removed (text unchanged) → a remove mark change, no content change', () => {
+ const r = ok('one **two three** four', 'one two three four');
+ expect(r.changes.length).toBe(0);
+ expect(r.markChanges.length).toBe(1);
+ const [mc] = r.markChanges;
+ expect(mc.kind).toBe('remove');
+ expect(mc.markName).toBe('strong');
+ expect(mc.toB).toBeGreaterThan(mc.fromB);
+ // Pure mark change (no content edits) → before/after coords coincide.
+ expect(mc.fromA).toBe(mc.fromB);
+ expect(mc.toA).toBe(mc.toB);
+ });
+
+ test('bold added (text unchanged) → an add mark change', () => {
+ const r = ok('one two three four', 'one **two three** four');
+ expect(r.changes.length).toBe(0);
+ expect(r.markChanges.length).toBe(1);
+ expect(r.markChanges[0]?.kind).toBe('add');
+ expect(r.markChanges[0]?.markName).toBe('strong');
+ });
+
+ test('link removed → a remove mark change on the link mark', () => {
+ const r = ok('see [the docs](https://example.com) now', 'see the docs now');
+ expect(r.markChanges.some((m) => m.kind === 'remove' && m.markName === 'link')).toBe(true);
+ });
+
+ test('mark on newly inserted text is not double-reported (dropped)', () => {
+ // The whole bold phrase is inserted — it must read as an insertion, not as a
+ // separate "formatting added" mark change on the same range.
+ const r = ok('start.', 'start. **fresh bold**');
+ const { ins } = counts(r.changes);
+ expect(ins).toBeGreaterThan(0);
+ expect(r.markChanges.length).toBe(0);
+ });
+
+ // Block-level alignment: heavy rewrite/reorder must produce a few whole-block
+ // changes, not word-salad, and must leave unchanged sibling blocks alone.
+ test('editing one list item leaves the other items untouched', () => {
+ const before = `- [[proposals/0001|Proposal 0001]] vision.
+- [[specs/x/spec|Spec A]] tasks.
+- Old third item.`;
+ const after = `- [[proposals/0001|Proposal 0001]] vision.
+- [[specs/x/spec|Spec A]] tasks.
+- Reworded third item.`;
+ const r = ok(before, after);
+ // Exactly the third item: one whole-block delete + one whole-block insert.
+ expect(r.changes.length).toBe(2);
+ const touched = r.changes
+ .map(
+ (c) =>
+ (c.toB > c.fromB ? r.afterDoc.textBetween(c.fromB, c.toB, ' ') : '') +
+ (c.toA > c.fromA ? r.beforeDoc.textBetween(c.fromA, c.toA, ' ') : ''),
+ )
+ .join('');
+ expect(touched).toContain('third item');
+ expect(touched).not.toContain('Proposal');
+ expect(touched).not.toContain('Spec');
+ });
+
+ test('rewrite + reorder of bullets stays block-level (no word-salad)', () => {
+ const before = `- Agent Activity Panel (per-file diffs, per-file undo).
+- Change summaries per write.`;
+ const after = `- **Timeline tab** — a unified human+agent feed.
+- Agent Activity Panel (separate, agent-scoped: per-file diffs, per-file undo).
+- Change summaries per write, shown on Timeline rows.`;
+ const r = ok(before, after);
+ // Two removed bullets + three added bullets = 5 whole-block changes, not the
+ // ~29 interleaved word ranges the whole-doc word diff produced.
+ expect(r.changes.length).toBeLessThanOrEqual(6);
+ });
+});
diff --git a/packages/app/src/lib/rendered-diff/build-rendered-diff.ts b/packages/app/src/lib/rendered-diff/build-rendered-diff.ts
new file mode 100644
index 000000000..9274a1443
--- /dev/null
+++ b/packages/app/src/lib/rendered-diff/build-rendered-diff.ts
@@ -0,0 +1,160 @@
+/**
+ * `buildRenderedDiff` — the pure diff engine behind the Timeline's rendered
+ * (WYSIWYG) diff. Given two markdown bodies + a schema, it returns the "after"
+ * ProseMirror document plus the word-level change ranges between the two
+ * versions, ready for the decoration builder (`diff-decorations.ts`) to paint.
+ *
+ * Pure + deterministic: no DOM, no I/O. `beforeDoc` is returned alongside so
+ * the decoration builder can slice removed content out of it for deletion
+ * widgets. Callers guard with `ok` — a `false` return (parse/recreate failure,
+ * or over the size/change ceiling) signals the pane to fall back to the raw
+ * Source diff rather than render a broken or pathologically slow view.
+ */
+
+import { recreateTransform } from '@fellow/prosemirror-recreate-transform';
+import type { MarkdownManager } from '@inkeep/open-knowledge-core';
+import type { Node as PMNode, Schema } from '@tiptap/pm/model';
+import { AddMarkStep, RemoveMarkStep, type Transform } from '@tiptap/pm/transform';
+import { buildBlockChanges, type SpanChange } from './block-diff';
+
+export type { SpanChange } from './block-diff';
+
+/**
+ * Above this the rendered diff is skipped in favor of the Source view: a huge
+ * doc or a huge edit distance makes `recreateTransform` slow and its output
+ * noisy. Deliberately generous — most timeline docs sit far below it.
+ */
+export const RENDERED_DIFF_SIZE_CEILING = 200_000;
+const RENDERED_DIFF_CHANGE_CEILING = 400;
+
+/**
+ * A formatting-only change (mark added or removed) with no accompanying text
+ * change — e.g. bolding a word or removing a link. The block-level content diff
+ * is position-based and a mark step changes no positions, so these are surfaced
+ * separately (from the transform's mark steps) and rendered like a replacement:
+ * the BEFORE form (old marks) struck through in red, the AFTER form (new marks)
+ * highlighted in green. `fromA/toA` index the before doc (the struck slice);
+ * `fromB/toB` index the after doc (the highlighted range).
+ */
+export interface MarkChange {
+ fromA: number;
+ toA: number;
+ fromB: number;
+ toB: number;
+ /** Schema mark name, e.g. `strong`, `em`, `link`, `code`. */
+ markName: string;
+ kind: 'add' | 'remove';
+}
+
+export interface RenderedDiff {
+ ok: true;
+ /** The "after" version, rendered as the document. */
+ afterDoc: PMNode;
+ /** The "before" version — deletion widgets slice removed content from it. */
+ beforeDoc: PMNode;
+ /** Block-level added/removed ranges, old + new coordinates. */
+ changes: readonly SpanChange[];
+ /** Formatting-only (mark add/remove) ranges in after-doc coordinates. */
+ markChanges: readonly MarkChange[];
+}
+
+interface RenderedDiffFailure {
+ ok: false;
+ reason: 'parse' | 'recreate' | 'ceiling';
+}
+
+export type RenderedDiffResult = RenderedDiff | RenderedDiffFailure;
+
+function toDoc(md: MarkdownManager, schema: Schema, body: string): PMNode {
+ // parseWithFallback (not parse): historical on-disk bytes are untrusted and
+ // may carry a schema-hostile construct; the fallback substitutes a raw node
+ // instead of throwing into the caller.
+ return schema.nodeFromJSON(md.parseWithFallback(body));
+}
+
+/**
+ * Pull formatting-only changes out of the recreated transform. `recreateTransform`
+ * with `complexSteps` emits clean `addMark`/`removeMark` steps (a bold toggle is
+ * one such step carrying the text range + mark type). These change no positions,
+ * so the block-level content diff can't see them — we read them here. Each step's
+ * range is mapped both forward (through the later steps → after-doc coords,
+ * `fromB/toB`) and backward (through the earlier steps, inverted → before-doc
+ * coords, `fromA/toA`). A mark range fully inside an inserted content range is
+ * dropped: newly inserted text is already highlighted as an insertion, so its
+ * formatting is not a separate signal.
+ */
+function collectMarkChanges(tr: Transform, changes: readonly SpanChange[]): MarkChange[] {
+ const inserted = changes.filter((c) => c.toB > c.fromB);
+ const out: MarkChange[] = [];
+ tr.steps.forEach((step, i) => {
+ const kind =
+ step instanceof AddMarkStep ? 'add' : step instanceof RemoveMarkStep ? 'remove' : null;
+ if (kind === null) return;
+ const markStep = step as AddMarkStep | RemoveMarkStep;
+ const forward = tr.mapping.slice(i + 1);
+ const fromB = forward.map(markStep.from, -1);
+ const toB = forward.map(markStep.to, 1);
+ if (toB <= fromB) return;
+ if (inserted.some((c) => c.fromB <= fromB && toB <= c.toB)) return;
+ const backward = tr.mapping.slice(0, i).invert();
+ const fromA = backward.map(markStep.from);
+ const toA = backward.map(markStep.to);
+ if (toA <= fromA) return;
+ out.push({ fromA, toA, fromB, toB, markName: markStep.mark.type.name, kind });
+ });
+ return out;
+}
+
+/**
+ * Compute the rendered diff between two markdown bodies. `before`/`after` are
+ * the frontmatter-stripped historical bodies (from `useTimelineEntryDiff`).
+ */
+export function buildRenderedDiff(
+ before: string,
+ after: string,
+ schema: Schema,
+ md: MarkdownManager,
+): RenderedDiffResult {
+ if (before.length > RENDERED_DIFF_SIZE_CEILING || after.length > RENDERED_DIFF_SIZE_CEILING) {
+ return { ok: false, reason: 'ceiling' };
+ }
+
+ let beforeDoc: PMNode;
+ let afterDoc: PMNode;
+ try {
+ beforeDoc = toDoc(md, schema, before);
+ afterDoc = toDoc(md, schema, after);
+ } catch {
+ return { ok: false, reason: 'parse' };
+ }
+
+ // Formatting-only changes come from the word-level transform (mark steps); the
+ // content diff is block-level. The transform is best-effort: if it throws on a
+ // pathological pair we still render the block diff, just without mark changes.
+ let renderDoc = afterDoc;
+ let tr: Transform | null = null;
+ try {
+ // complexSteps: allow non-Replace (mark) steps so bold/link toggles surface;
+ // wordDiffs keeps a mark step's range tight; simplifyDiff merges adjacent.
+ tr = recreateTransform(beforeDoc, afterDoc, {
+ complexSteps: true,
+ wordDiffs: true,
+ simplifyDiff: true,
+ });
+ renderDoc = tr.doc;
+ } catch {
+ // Keep the parsed afterDoc as the render target; drop mark changes.
+ }
+
+ // Compute block ranges against the doc we actually render (renderDoc), not the
+ // pre-transform afterDoc — so a decoration boundary can never be invalid even
+ // if `recreateTransform` normalized the structure. Mark ranges map into the
+ // same coordinate space, and dedup against the block insertions.
+ const contentChanges = buildBlockChanges(beforeDoc, renderDoc);
+ const markChanges = tr ? collectMarkChanges(tr, contentChanges) : [];
+
+ if (contentChanges.length + markChanges.length > RENDERED_DIFF_CHANGE_CEILING) {
+ return { ok: false, reason: 'ceiling' };
+ }
+ return { ok: true, afterDoc: renderDoc, beforeDoc, changes: contentChanges, markChanges };
+}
diff --git a/packages/app/src/lib/rendered-diff/diff-decorations.ts b/packages/app/src/lib/rendered-diff/diff-decorations.ts
new file mode 100644
index 000000000..8a120ca42
--- /dev/null
+++ b/packages/app/src/lib/rendered-diff/diff-decorations.ts
@@ -0,0 +1,152 @@
+/**
+ * `buildDiffDecorations` — turns the engine's change ranges into a ProseMirror
+ * `DecorationSet` painted over the rendered "after" document:
+ *
+ * - Inserted blocks (`toB > fromB`) → node decoration (`ok-diff-ins-block`)
+ * over the whole added block: highlighted in place.
+ * - Deleted blocks (`toA > fromA`) → a widget decoration at `fromB` whose DOM
+ * is the removed slice of the BEFORE doc, serialized through the real schema
+ * (`DOMSerializer`) so a removed heading/list/code renders formatted, then
+ * struck through (`ok-diff-del`). A reworded block is both at once — the
+ * struck old block (side −1) then the highlighted new block — reading
+ * "~~old~~ new" like a text replacement.
+ * - Mark changes (formatting-only, e.g. bold/link added or removed) → rendered
+ * as a replacement: the before-doc slice (old marks) as a struck `ok-diff-del`
+ * widget, plus an inline `ok-diff-ins` highlight over the after range. Reuses
+ * the same machinery so formatting reads like any other diff.
+ *
+ * Open-slice handling: deleting list items yields
+ * an OPEN slice — bare `<li>` with no enclosing `<ul>`, so markers wouldn't
+ * render. When every top-level child of the removed fragment is a list item we
+ * re-wrap the serialized output in a `<ul>` so the removed list reads as a
+ * list. Other open slices render as-is (acceptable for v1).
+ *
+ * Static by construction: the diff document never changes (read-only), so the
+ * set is built once and needs no mapping across transactions.
+ */
+import { DOMSerializer, type Fragment, type Node as PMNode, type Schema } from '@tiptap/pm/model';
+import { Decoration, DecorationSet } from '@tiptap/pm/view';
+import type { MarkChange, SpanChange } from './build-rendered-diff';
+
+/**
+ * Every change anchor this module paints: an inline insertion/mark highlight
+ * (`ok-diff-ins`), a whole-block insertion highlight (`ok-diff-ins-block`), or a
+ * deletion widget (`data-diff-deleted`). The pane's scroll-to-first-change and
+ * prev/next stepper query by this exact selector — keep it the single source so
+ * a new decoration class can't silently fall out of navigation.
+ */
+export const RENDERED_DIFF_CHANGE_SELECTOR =
+ '.ok-diff-ins, .ok-diff-ins-block, [data-diff-deleted]';
+
+/**
+ * Number of DOM elements `buildDiffDecorations` paints that match
+ * `RENDERED_DIFF_CHANGE_SELECTOR` — the count the change stepper navigates.
+ * Kept next to the builder so the two can't drift: a content change is one
+ * element (an `ok-diff-ins-block` node OR a `data-diff-deleted` widget), a mark
+ * change is TWO (the struck before-form widget PLUS the highlighted after-form
+ * inline). The stepper's "N / M" must use THIS, not `changes.length +
+ * markChanges.length`, or M undercounts the real anchors by `markChanges.length`.
+ */
+export function countRenderedDiffAnchors(diff: {
+ changes: readonly SpanChange[];
+ markChanges: readonly MarkChange[];
+}): number {
+ return diff.changes.length + 2 * diff.markChanges.length;
+}
+
+function fragmentHasBlock(frag: Fragment): boolean {
+ let hasBlock = false;
+ frag.forEach((child) => {
+ if (child.isBlock) hasBlock = true;
+ });
+ return hasBlock;
+}
+
+/** True when every top-level child is a list item — the open-slice rewrap case. */
+function isAllListItems(frag: Fragment): boolean {
+ if (frag.childCount === 0) return false;
+ let all = true;
+ frag.forEach((child) => {
+ if (child.type.name !== 'listItem' && child.type.name !== 'taskItem') all = false;
+ });
+ return all;
+}
+
+function buildDeletedWidget(
+ serializer: DOMSerializer,
+ content: Fragment,
+ isBlock: boolean,
+): HTMLElement {
+ const host = document.createElement(isBlock ? 'div' : 'span');
+ host.className = isBlock ? 'ok-diff-del ok-diff-del-block' : 'ok-diff-del';
+ host.setAttribute('data-diff-deleted', '');
+ const rendered = serializer.serializeFragment(content);
+ if (isBlock && isAllListItems(content)) {
+ const ul = document.createElement('ul');
+ ul.appendChild(rendered);
+ host.appendChild(ul);
+ } else {
+ host.appendChild(rendered);
+ }
+ return host;
+}
+
+/**
+ * Build the decoration set for a rendered diff. `afterDoc` is the rendered
+ * document (the set is anchored to it); `beforeDoc` supplies removed content;
+ * `changes` come from `buildRenderedDiff`.
+ */
+export function buildDiffDecorations(
+ afterDoc: PMNode,
+ beforeDoc: PMNode,
+ changes: readonly SpanChange[],
+ markChanges: readonly MarkChange[],
+ schema: Schema,
+): DecorationSet {
+ const serializer = DOMSerializer.fromSchema(schema);
+ const decorations: Decoration[] = [];
+
+ // Formatting-only changes render like a replacement: the BEFORE form (old
+ // marks — e.g. still bold) struck through in red as a widget, the AFTER form
+ // (new marks) highlighted green in place. Same machinery as a text replace, so
+ // "bold removed" reads as ~~**text**~~ text, consistent with content diffs.
+ for (const mark of markChanges) {
+ const slice = beforeDoc.slice(mark.fromA, mark.toA);
+ const isBlock = fragmentHasBlock(slice.content);
+ decorations.push(
+ Decoration.widget(mark.fromB, () => buildDeletedWidget(serializer, slice.content, isBlock), {
+ side: -1,
+ ignoreSelection: true,
+ marks: [],
+ }),
+ );
+ decorations.push(
+ Decoration.inline(mark.fromB, mark.toB, { class: 'ok-diff-ins' }, { inclusiveEnd: true }),
+ );
+ }
+
+ for (const change of changes) {
+ if (change.toB > change.fromB) {
+ // Whole added block → node decoration so the block's own DOM element
+ // (`<li>`, `<p>`, `<h2>`…) carries the highlight, rather than an inline
+ // span that can't straddle block boundaries cleanly.
+ decorations.push(Decoration.node(change.fromB, change.toB, { class: 'ok-diff-ins-block' }));
+ }
+ if (change.toA > change.fromA) {
+ const slice = beforeDoc.slice(change.fromA, change.toA);
+ const isBlock = fragmentHasBlock(slice.content);
+ decorations.push(
+ Decoration.widget(
+ change.fromB,
+ () => buildDeletedWidget(serializer, slice.content, isBlock),
+ // side −1 so the removed content renders BEFORE any inserted range
+ // at the same position (reads "~~old~~ new"). `ignoreSelection` +
+ // no marks: it is inert chrome, not part of the document.
+ { side: -1, ignoreSelection: true, marks: [] },
+ ),
+ );
+ }
+ }
+
+ return DecorationSet.create(afterDoc, decorations);
+}
diff --git a/packages/app/src/lib/rendered-diff/diff-extensions.ts b/packages/app/src/lib/rendered-diff/diff-extensions.ts
new file mode 100644
index 000000000..aaa9bc06f
--- /dev/null
+++ b/packages/app/src/lib/rendered-diff/diff-extensions.ts
@@ -0,0 +1,44 @@
+/**
+ * `diffExtensions` — the extension set for the read-only rendered-diff editor.
+ *
+ * Derived from the app's `sharedExtensions` so the diff renders with full
+ * editor fidelity (same schema, same node views for lists/code/math/wiki-links
+ * → correct ordered lists, tables, styling). Two adjustments:
+ *
+ * 1. Drop edit affordances (slash menu, drag handle, table controls, file
+ * handler, autolink/input rules, keyboard-nav, find/replace, selection +
+ * source-dirty observers). `editable:false` already makes most inert; the
+ * imperative DOM-mounters (drag handle, table controls) are dropped so
+ * their hover chrome never appears in a diff. An unmatched name simply
+ * stays (inert read-only) — safe.
+ * 2. Swap the app `JsxComponent` (React NodeView → `componentMap` → `Mirror`,
+ * which opens a live `HocuspocusProvider` via `useMirrorSource`) for
+ * core's base `JsxComponent`, which renders statically via `toDOM`.
+ * `Mirror` is the only editor node view that opens a live provider on
+ * render, so this single swap keeps the read-only diff from spawning
+ * providers or network. Other embeds (Image/Video/Math/Callout/…) then
+ * render via static `toDOM` — a v1 simplification; rich per-embed
+ * rendering is future work.
+ */
+import { JsxComponent as CoreJsxComponent } from '@inkeep/open-knowledge-core';
+import type { Extensions } from '@tiptap/core';
+import { sharedExtensions } from '@/editor/extensions/shared';
+
+const DROP_NAMES = new Set([
+ 'slashCommand',
+ 'blockDragHandle',
+ 'blockMover',
+ 'tableInsertControls',
+ 'fileHandler',
+ 'gfmAutolink',
+ 'inlineLinkInputRule',
+ 'keyboardNav',
+ 'tiptapFindReplace',
+ 'selectionState',
+ 'sourceDirtyObserver',
+ 'tabFocusTrap',
+]);
+
+export const diffExtensions: Extensions = sharedExtensions
+ .filter((ext) => !DROP_NAMES.has(ext.name))
+ .map((ext) => (ext.name === 'jsxComponent' ? CoreJsxComponent : ext));
diff --git a/packages/app/src/lib/timeline-diff-store.ts b/packages/app/src/lib/timeline-diff-store.ts
new file mode 100644
index 000000000..030a930a3
--- /dev/null
+++ b/packages/app/src/lib/timeline-diff-store.ts
@@ -0,0 +1,69 @@
+/**
+ * timeline-diff-store — cross-component channel for the full-pane Timeline
+ * diff. The Timeline panel (right DocPanel) sets the active version; EditorArea
+ * (center pane) reads it and paints `TimelineDiffPane` as a full-pane overlay
+ * over the editor. A module store (not DocumentContext) keeps this isolated
+ * from the central context + its test surface, matching the app's other
+ * `*-store` + `doc-panel-events` channels.
+ *
+ * The overlay is per-doc: EditorArea only paints it while `docName` matches the
+ * open document, and clears it on doc navigation — so a stale version can never
+ * paint over an unrelated doc.
+ */
+import { useSyncExternalStore } from 'react';
+
+export interface TimelineDiffView {
+ /** Extension-less doc the version belongs to (matched against the open doc). */
+ docName: string;
+ /** The version being viewed — also the rollback target. */
+ sha: string;
+ /** vs-parent baseline (list-adjacency); null for the first/oldest version. */
+ parentSha: string | null;
+ /**
+ * Number of newer visible timeline versions stacked after this one — what a
+ * Restore rolls back. 0 for the latest version (Restore is then a no-op, so
+ * the confirm's "rolls back N edits" warning is suppressed).
+ */
+ laterEdits: number;
+ /** Display metadata for the pane header (precomputed by the Timeline row). */
+ authorName: string;
+ relativeTime: string;
+ absoluteTime: string;
+}
+
+let current: TimelineDiffView | null = null;
+const listeners = new Set<() => void>();
+
+function notify(): void {
+ for (const listener of listeners) listener();
+}
+
+/** Open the full-pane diff for a version. Replaces any currently-open one. */
+export function openTimelineDiff(view: TimelineDiffView): void {
+ current = view;
+ notify();
+}
+
+/** Close the full-pane diff (no-op when already closed). */
+export function closeTimelineDiff(): void {
+ if (current !== null) {
+ current = null;
+ notify();
+ }
+}
+
+function subscribe(callback: () => void): () => void {
+ listeners.add(callback);
+ return () => {
+ listeners.delete(callback);
+ };
+}
+
+function getSnapshot(): TimelineDiffView | null {
+ return current;
+}
+
+/** Subscribe to the active full-pane diff (null when none is open). */
+export function useTimelineDiffView(): TimelineDiffView | null {
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+}
diff --git a/packages/app/src/lib/use-activity-panel.ts b/packages/app/src/lib/use-activity-panel.ts
index 9c6b64ea5..769ddf093 100644
--- a/packages/app/src/lib/use-activity-panel.ts
+++ b/packages/app/src/lib/use-activity-panel.ts
@@ -7,7 +7,7 @@
* and re-fetch after a 500 ms trailing-edge debounce.
* 3. Subscribe to `__system__` awareness for `agentPresence` and expose a
* `writingDocs` set so file rows can show a "writing…" indicator.
- * 4. Provide `fetchBurstDiff(docName, stackIndex)` — lazy per-burst diff
+ * 4. Provide `fetchBurstDiff(docName, keptCount)` — lazy per-version diff
* fetch with a component-scoped cache so re-expand doesn't re-fetch.
* 5. Cancelled-flag semantics: an in-flight fetch that completes AFTER the
* connectionId swapped or the component unmounted must NOT update state.
@@ -60,12 +60,14 @@ interface UseActivityPanelResult {
/** Trigger a re-fetch of `/api/agent-activity`. No-op when inert. */
reload: () => void;
/**
- * Lazy-fetch the unified-diff text for a single burst.
+ * Lazy-fetch the unified-diff text for a file version. `keptCount` is the
+ * edits-to-keep count the `agent-burst-diff` endpoint expects (0 = original,
+ * `bursts.length` = now); for a given burst pass `burst.stackIndex + 1`.
* Returns the cached diff when available. Re-fetches on cache miss.
* Throws on network / server failure — callers surface the error in the
* burst row's expanded state.
*/
- fetchBurstDiff: (docName: string, stackIndex: number) => Promise<string>;
+ fetchBurstDiff: (docName: string, keptCount: number) => Promise<string>;
}
const REFETCH_DEBOUNCE_MS = 500;
@@ -75,7 +77,7 @@ const REFETCH_DEBOUNCE_MS = 500;
* files) don't grow renderer memory unboundedly. Sized to match the
* `ProviderPool` precedent (`MAX_POOL = 10`) × ~6 bursts typical for a mid-
* sized file = 60; rounded up. Beyond the cap, LRU eviction drops the
- * least-recently-fetched entry. Cache keys are `${docName}\0${stackIndex}`.
+ * least-recently-fetched entry. Cache keys are `${docName}\0${keptCount}`.
*/
const BURST_DIFF_CACHE_LIMIT = 64;
@@ -119,14 +121,22 @@ async function fetchAgentActivity(connectionId: string): Promise<{
return success.data;
}
-async function fetchBurstDiffHttp(
+/**
+ * Fetch a single agent burst version: the unified-diff text plus the
+ * frontmatter-stripped `before`/`after` bodies (for the WYSIWYG diff). Exported
+ * so the full-pane `AgentDiffPane` (painted in EditorArea, outside this hook's
+ * subtree) can fetch the same version the panel shows without duplicating the
+ * request/parse contract. The panel's `fetchBurstDiff` wraps this with an LRU
+ * cache; the pane keeps its own small cache.
+ */
+export async function fetchAgentBurstDiff(
connectionId: string,
docName: string,
- stackIndex: number,
-): Promise<string> {
+ keptCount: number,
+): Promise<{ diff: string; before: string; after: string }> {
const url = `/api/agent-burst-diff?agentId=${encodeURIComponent(
connectionId,
- )}&docName=${encodeURIComponent(docName)}&stackIndex=${stackIndex}`;
+ )}&docName=${encodeURIComponent(docName)}&keptCount=${keptCount}`;
const res = await fetch(url);
let body: unknown;
try {
@@ -154,7 +164,8 @@ async function fetchBurstDiffHttp(
{ cause: success.error, status: res.status },
);
}
- return success.data.diff;
+ const { diff, before, after } = success.data;
+ return { diff, before, after };
}
// ---------------------------------------------------------------
@@ -167,7 +178,7 @@ export function useActivityPanel(connectionId: string | null): UseActivityPanelR
const [status, setStatus] = useState<ActivityPanelStatus>('idle');
const [error, setError] = useState<string | null>(null);
- // Burst-diff cache — keyed by `${docName}\0${stackIndex}`. LRU-bounded at
+ // Burst-diff cache — keyed by `${docName}\0${keptCount}`. LRU-bounded at
// BURST_DIFF_CACHE_LIMIT so long-lived agent sessions can't exhaust
// renderer memory. Cleared when connectionId changes so stale entries
// from the previous agent's session can never leak into the new view.
@@ -264,13 +275,15 @@ export function useActivityPanel(connectionId: string | null): UseActivityPanelR
};
}, [connectionId, systemProvider]);
- // (4) Lazy burst-diff fetch with cache.
- const fetchBurstDiff = async (docName: string, stackIndex: number): Promise<string> => {
+ // (4) Lazy burst-diff fetch with cache. `keptCount` is the version index the
+ // endpoint expects (edits-to-keep), NOT a 0-based burst stackIndex.
+ const fetchBurstDiff = async (docName: string, keptCount: number): Promise<string> => {
if (!connectionId) return '';
- const key = `${docName}\0${stackIndex}`;
+ const key = `${docName}\0${keptCount}`;
const cached = diffCacheRef.current.get(key);
if (cached !== undefined) return cached;
- const diff = await fetchBurstDiffHttp(connectionId, docName, stackIndex);
+ // Inline burst rows show Source only, so keep just the unified diff here.
+ const { diff } = await fetchAgentBurstDiff(connectionId, docName, keptCount);
diffCacheRef.current.set(key, diff);
return diff;
};
diff --git a/packages/app/src/lib/use-timeline-entry-diff.ts b/packages/app/src/lib/use-timeline-entry-diff.ts
index 379842244..da4b714d9 100644
--- a/packages/app/src/lib/use-timeline-entry-diff.ts
+++ b/packages/app/src/lib/use-timeline-entry-diff.ts
@@ -2,8 +2,10 @@
* `useTimelineEntryDiff` — data layer for the inline diff in the Timeline
* tab's expanded entry rows. Mirrors the cache + cancellation shape of
* `useActivityPanel`'s burst-diff fetch, but the diff is computed client-side
- * (no server endpoint synthesizes it) so the live Y.Text WIP is part of the
- * comparison.
+ * (no server endpoint synthesizes it). Two reference frames (see
+ * `TimelineDiffMode`): `vs-parent` diffs the previous version against this one
+ * (immutable audit), `vs-live` diffs this version against the live Y.Text WIP
+ * (restore preview).
*
* Responsibilities:
* 1. On `sha` set: fetch `GET /api/history/<sha>?docName=<>`. Cache the
@@ -45,7 +47,37 @@ type UseTimelineEntryDiffResult =
| { status: 'idle'; diff: null }
| { status: 'loading'; diff: null }
| { status: 'error'; diff: null }
- | { status: 'ready'; diff: string };
+ | {
+ status: 'ready';
+ /** Unified-diff string (for the source view). Empty when the bodies match. */
+ diff: string;
+ additions: number;
+ deletions: number;
+ /**
+ * Frontmatter-stripped bodies of both sides, for the rendered prose diff
+ * (word-level). `before` is the parent/version content, `after` is this
+ * version's content (vs-parent) or live Y.Text (vs-live). Equal when there
+ * is no change — the prose view then renders `after` as the plain document.
+ */
+ before: string;
+ after: string;
+ };
+
+/**
+ * Count added/removed lines in a `diff.createPatch` unified-diff string. Lines
+ * starting with a single `+`/`-` are changes; the `+++`/`---` file headers and
+ * `@@` hunk headers are excluded. Cheap enough to run on expand — no server
+ * round-trip, and the `+N −M` stat is only shown while a row is open.
+ */
+export function countDiffStat(patch: string): { additions: number; deletions: number } {
+ let additions = 0;
+ let deletions = 0;
+ for (const line of patch.split('\n')) {
+ if (line.startsWith('+') && !line.startsWith('+++')) additions++;
+ else if (line.startsWith('-') && !line.startsWith('---')) deletions++;
+ }
+ return { additions, deletions };
+}
/**
* Composite cache key format for `LruStringCache`. Exported for unit tests
@@ -71,13 +103,30 @@ export function computeTimelineDiff(
const historical = stripFrontmatter(historicalRaw).body;
const current = stripFrontmatter(currentRaw).body;
if (historical === current) return '';
- return createPatch(docName, historical, current, '', '', { context: 3 });
+ // Whole-file context: the patch includes every line so the diff renders the
+ // full document with the change highlighted in place (the pane then scrolls
+ // to the first change), rather than just the changed hunk.
+ const context = Math.max(historical.split('\n').length, current.split('\n').length);
+ return createPatch(docName, historical, current, '', '', { context });
}
+/**
+ * Which reference frame the diff compares against:
+ * - `vs-parent`: `content@parentSha` → `content@sha`. Both historical, so the
+ * diff is immutable and never drifts as the live doc changes — the honest
+ * "exactly what this version's author changed." When `parentSha` is null
+ * (first/oldest version), the parent side is empty (whole doc as additions).
+ * - `vs-live`: `content@sha` → live Y.Text. The "what a restore would undo"
+ * preview; the "after" side is mutable, so this is recomputed every run.
+ */
+export type TimelineDiffMode = 'vs-parent' | 'vs-live';
+
export function useTimelineEntryDiff(
sha: string | null,
docName: string,
cache: LruStringCache,
+ mode: TimelineDiffMode = 'vs-live',
+ parentSha: string | null = null,
): UseTimelineEntryDiffResult {
const { activeProvider } = useDocumentContext();
const [result, setResult] = useState<UseTimelineEntryDiffResult>({ status: 'idle', diff: null });
@@ -99,37 +148,72 @@ export function useTimelineEntryDiff(
let cancelled = false;
setResult({ status: 'loading', diff: null });
+ // Fetch a historical version's content by SHA, cached forever (historical
+ // bytes never change). Shared by both the `sha` side and the vs-parent
+ // `parentSha` side. Returns null on a non-ok response so the caller can
+ // surface the error state.
+ async function fetchHistoricalContent(versionSha: string): Promise<string | null> {
+ const key = timelineEntryCacheKey(docName, versionSha);
+ const cached = cache.get(key);
+ if (cached !== undefined) return cached;
+ const res = await fetch(`/api/history/${versionSha}?docName=${encodeURIComponent(docName)}`);
+ if (!res.ok) {
+ console.error('[timeline-diff] history fetch returned non-ok response', {
+ sha: versionSha,
+ docName,
+ status: res.status,
+ });
+ return null;
+ }
+ const body = (await res.json()) as { content?: string };
+ const content = body.content ?? '';
+ cache.set(key, content);
+ return content;
+ }
+
async function run() {
try {
- const key = timelineEntryCacheKey(docName, activeSha);
- let historicalRaw = cache.get(key);
- if (historicalRaw === undefined) {
- const res = await fetch(
- `/api/history/${activeSha}?docName=${encodeURIComponent(docName)}`,
- );
+ const shaContent = await fetchHistoricalContent(activeSha);
+ if (cancelled) return;
+ if (shaContent === null) {
+ setResult({ status: 'error', diff: null });
+ return;
+ }
+
+ let beforeRaw: string;
+ let afterRaw: string;
+ if (mode === 'vs-parent') {
+ // Immutable audit diff: previous version → this version. Both sides
+ // historical, so the result is stable and fully cacheable.
+ const parentContent = parentSha ? await fetchHistoricalContent(parentSha) : '';
if (cancelled) return;
- if (!res.ok) {
+ if (parentContent === null) {
setResult({ status: 'error', diff: null });
return;
}
- const body = (await res.json()) as { content?: string };
- if (cancelled) return;
- historicalRaw = body.content ?? '';
- cache.set(key, historicalRaw);
+ beforeRaw = parentContent;
+ afterRaw = shaContent;
+ } else {
+ // Restore preview: this version → live Y.Text. The "after" side is
+ // mutable, so this branch is recomputed on every effect run.
+ beforeRaw = shaContent;
+ afterRaw = providerRef.current?.document.getText('source').toString() ?? '';
}
+ // Frontmatter-stripped bodies drive the rendered prose diff (word-level);
+ // `computeTimelineDiff` stays the single source of the source-view patch.
+ const before = stripFrontmatter(beforeRaw).body;
+ const after = stripFrontmatter(afterRaw).body;
+ const patchStr = computeTimelineDiff(beforeRaw, afterRaw, docName);
if (cancelled) return;
-
- const currentRaw = providerRef.current?.document.getText('source').toString() ?? '';
- const patchStr = computeTimelineDiff(historicalRaw, currentRaw, docName);
-
- if (cancelled) return;
- setResult({ status: 'ready', diff: patchStr });
+ const { additions, deletions } = countDiffStat(patchStr);
+ setResult({ status: 'ready', diff: patchStr, additions, deletions, before, after });
} catch (err) {
if (!cancelled) {
console.error('[timeline-diff] failed to load entry diff', {
sha: activeSha,
docName,
+ mode,
err,
});
setResult({ status: 'error', diff: null });
@@ -141,7 +225,7 @@ export function useTimelineEntryDiff(
return () => {
cancelled = true;
};
- }, [sha, docName, cache]);
+ }, [sha, docName, cache, mode, parentSha]);
return result;
}
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 5eb354c76..f0b34f96e 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -17,9 +17,10 @@
"-Qw-1t": ["GitHub authentication failed. Try signing in again."],
"-WFFG2": ["Default properties"],
"-YV1Uo": ["Pattern ", ["patternNumber"]],
+ "-bFGPF": ["Next change"],
+ "-dNlfM": ["Undid the last edit on ", ["docName"]],
"-g6KIS": ["Unrecognized link"],
"-gdcIo": ["Auto-sync is on — your commits push and remote changes pull on intervals."],
- "-i7ik4": ["Collapse burst ", ["burstNumber"], " diff"],
"-kbIAr": ["Links & images"],
"-lCAuQ": ["Loading graph"],
"-o5XAG": [
@@ -75,6 +76,7 @@
],
"0jD-Gn": ["A team knowledge base, a personal wiki, project docs..."],
"0kTAXe": ["Open source: ", ["mirrorSrc"]],
+ "0qyKG6": ["Synced from disk"],
"0rwwOn": ["By tag"],
"0s8-e8": [
"Select, enter, or leave block components and fallback source blocks from keyboard boundaries."
@@ -88,6 +90,7 @@
"12F9WL": ["(no id)"],
"151wvk": ["Show sidebar"],
"16D5Zj": ["Are you sure you want to delete ", ["itemName"], "? This action cannot be undone."],
+ "170Js2": ["Hide panel"],
"1AumWo": ["Push failed — check the server logs for details."],
"1CalO6": ["Style"],
"1EcCom": [["keyName"], " value"],
@@ -140,7 +143,6 @@
"2YOwme": ["Restarted — now running v", ["appRuntime"], "."],
"2YZwPB": ["Forward-links response did not match expected shape."],
"2bVHbB": ["Available in every project on this computer."],
- "2fkdnR": ["Nothing to undo on this file"],
"2hYmUH": ["[email protected]"],
"2hpdRq": ["Hide panel (", ["panelShortcutLabel"], ")"],
"2j1kfc": ["Enter a valid URL (for example https://api.openai.com/v1)."],
@@ -160,7 +162,6 @@
"34qyH5": ["Could not reach server"],
"36WXSC": ["Couldn't delete template: ", ["error"]],
"36aWJD": ["Join us on Discord"],
- "379t2h": ["Unified diff"],
"38foVZ": ["Loading diff"],
"3BnyYc": ["This doc isn't on GitHub yet. The link won't work until it's pushed."],
"3DJEEt": [
@@ -185,6 +186,7 @@
"3TCafD": ["Stored on this machine."],
"3VbwPp": ["Open ", ["keyName"], " in browser"],
"3VsNTI": ["Loading document"],
+ "3YWddZ": ["No content changes in this version"],
"3YvS-c": ["New tab"],
"3_6U6f": ["Connect to GitHub"],
"3__SjS": ["breadcrumb"],
@@ -252,6 +254,7 @@
". Change it in Settings → Sync."
],
"4zGlN_": ["Paste image URL or click upload"],
+ "4z_1j2": ["Rendered"],
"5-FeN2": ["Share URL"],
"5-o4kO": ["Only markdown files"],
"50ORFs": ["Reset ", ["0"], " to default"],
@@ -286,6 +289,7 @@
"5Umg9i": ["Disable external link previews"],
"5WDhAk": ["Link to a page or external URL."],
"5ZB7XC": ["File drop zone"],
+ "5ZbJFS": ["Your current version is saved first, so this is reversible."],
"5_8TCr": ["Fix all (", ["count"], ")"],
"5_j-DA": ["Kill Terminal"],
"5e1Dri": ["The menu label agents pick this template by (required)."],
@@ -320,6 +324,7 @@
"6-wLTJ": [["behind"], " behind origin"],
"60vpJN": ["What were you doing?"],
"62Pc08": ["Install for Claude Chat & Cowork (Desktop App)"],
+ "62bOuM": ["Latest edit"],
"636K3K": ["Delete adjacent chip"],
"67f-3g": ["Duplicate succeeded but the sidebar may be out of date — refresh to resync"],
"6Aih4U": ["Offline"],
@@ -350,6 +355,7 @@
"6gRgw8": ["Retry"],
"6h4zVU": ["What would you like to create?"],
"6hfDJr": ["Server error: ", ["status"]],
+ "6iDEWA": ["Show panel"],
"6ibbCg": ["Create your first file"],
"6ki7F2": [["0", "plural", { "one": ["#", " item"], "other": ["#", " items"] }]],
"6lGV3K": ["Show less"],
@@ -371,7 +377,6 @@
"7Fkcej": ["+ Add ", ["addChildName"]],
"7H4UHD": ["Documents tagged <0>#", ["tagName"], "</0>"],
"7JtSLi": ["Failed to delete path"],
- "7KeV5F": ["Undo all failed: ", ["message"]],
"7OhaRy": ["Source search"],
"7Ongq0": ["Condense my AGENTS.md file to less than 40k characters"],
"7OwvEL": ["Show HTML preview"],
@@ -431,6 +436,7 @@
"8eW0WQ": ["No matching repositories."],
"8fRyLo": ["Invalid patch payload"],
"8fc_3j": ["Protected branch — cannot push"],
+ "8lwQlE": [["0"], " added, ", ["1"], " removed"],
"8m8diM": ["No location selected. Use Browse to choose a folder."],
"8nWu1k": ["Empty diagram"],
"8tjQCz": ["Explore"],
@@ -518,9 +524,9 @@
],
"Aif3E7": ["Enable semantic search"],
"Am78jY": ["Drag ", ["keyName"], " to reorder"],
+ "ApeA0n": ["Undid ", ["dropCount"], " edits on ", ["docName"]],
"Aq-O0x": ["status"],
"AqnqMJ": ["API key set"],
- "ArBWJf": ["Undo last edit"],
"AsqRE_": ["Default location for new attachments"],
"AtBdnD": ["Couldn't delete skill: ", ["error"]],
"B11p-O": ["Edit markdown link"],
@@ -691,7 +697,6 @@
"EcM3k7": ["Failed to clean up pending ", ["kind"]],
"EcR0fl": ["Checking for installed agents"],
"EdQY6l": ["None"],
- "EeRZnZ": ["Expand burst ", ["burstNumber"], " diff"],
"Ef7StM": ["Unknown"],
"EhDLBx": ["You modified <0>", ["filePath"], "</0> locally, but it was deleted upstream."],
"Ehkru0": ["Open, navigate, accept, or dismiss CodeMirror completion suggestions."],
@@ -802,6 +807,7 @@
"GemPfn": ["Failed to parse forward-links error response (HTTP ", ["status"], ")"],
"Gfr4fu": ["Server can't open documents"],
"GhjUB_": ["Reconnected"],
+ "GkYV_4": ["Renamed ", ["0"], " → ", ["1"]],
"Gp_twO": ["Local path"],
"GsBUCk": ["Loading settings"],
"Gt4gOO": ["This folder has unpushed changes. Recipients will see the last pushed version."],
@@ -822,7 +828,6 @@
"HPTPGr": ["Create a new spec file for my user story"],
"HSh8u_": ["Folders"],
"HTW0Zw": ["One more step: run <0>claude</0> in this project and approve OpenKnowledge once."],
- "HXFyWD": ["Split diff"],
"HdkSiO": ["New file"],
"HfI1dR": ["I already have it locally →"],
"HjNrT0": [["0", "plural", { "one": ["#", " backlink"], "other": ["#", " backlinks"] }]],
@@ -880,7 +885,6 @@
"Ix0K8o": ["Hide external URL nodes"],
"IxyZXD": ["Screenshot"],
"Izb10l": ["Fix all ", ["count"], " fixable problems"],
- "J2MgzQ": ["Undo all edits on ", ["docName"]],
"J2Mv98": ["Name (e.g. ", ["login"], ")"],
"J2eKUI": ["File"],
"J3HzPL": ["Collapse ", ["keyName"]],
@@ -973,6 +977,16 @@
"LCUy_N": ["Session ended"],
"LDuM35": ["Replace current match from field"],
"LE7t79": ["Clone to a new folder"],
+ "LKIPzv": [
+ [
+ "laterEdits",
+ "plural",
+ {
+ "one": ["Removes ", "#", " newer edit on this file."],
+ "other": ["Removes ", "#", " newer edits on this file."]
+ }
+ ]
+ ],
"LKOLNn": ["No AI agents installed"],
"LNum6A": [["minutes"], " min ago"],
"LRgZAt": [["owner"], "/", ["name"], " already exists"],
@@ -1032,12 +1046,12 @@
"MJqRO6": ["Your report is being sent."],
"MKOVhz": ["Enable git auto-sync"],
"MQIM_Y": ["Couldn't copy. Select the URL above to copy it manually."],
+ "MRZxAn": ["Edited"],
"MTs6g3": ["Couldn't reconnect after server restart"],
"MUBR8r": ["Rename succeeded but the tabstrip may be out of date — refresh to resync"],
"MUrVEo": ["No recent projects."],
"MV-Dkb": ["Found ", ["countDisplay"], " markdown files"],
"MVxpbf": ["Find and replace"],
- "MWrUEd": ["Undo all"],
"MZSBsh": [
"No templates yet. Add one to give new docs in this folder a ready-made starting point."
],
@@ -1199,7 +1213,6 @@
],
"PrJYSN": ["This folder isn't on GitHub yet. The link won't work until it's pushed."],
"PrhzDE": ["Pan up"],
- "Pyp1NA": ["Restore to this point?"],
"Q1mtyd": ["Hide sidebar"],
"Q5fqMz": ["Connection error — try again"],
"Q6hhn8": ["Preferences"],
@@ -1289,8 +1302,8 @@
"S9t1PI": ["Fixing ", ["0"], "/", ["1"]],
"SCoBBH": ["Tag suggestions"],
"SCzAbA": [["phase"], " — ", ["pct"], "%"],
- "SEYWYq": ["Undo all edits on this file?"],
"SFN6dN": ["Heading 3"],
+ "SOPwPh": ["Restore to this edit"],
"STTOnz": [["keyName"], " type: complex value (nested; read-only)"],
"SUOoXn": ["Failed to open project."],
"SVLPt5": [["formatted"], " GitHub stars"],
@@ -1518,7 +1531,6 @@
"XuQzrk": [
"Couldn't restart the server — another process owns it. Quit other OpenKnowledge windows for this project, then try again."
],
- "XvPJaT": ["Diff layout"],
"Xv_ijG": ["https://github.com/owner/repo or owner/repo"],
"Xw_maT": ["Type a query, then press ↵ to search your pages by meaning."],
"Xwump4": ["no git repository here"],
@@ -1571,6 +1583,7 @@
"Z6rrjc": [
"No <0>.markdownlint.*</0> file yet — every rule runs on the same defaults as the VS Code markdownlint extension: all on, except line length."
],
+ "Z79bnE": ["View diff for edit ", ["burstNumber"], " of ", ["docName"]],
"Z7x_Zh": [
"Git needs ",
["tool"],
@@ -1579,13 +1592,6 @@
"Z8KDox": ["Enter a folder name (e.g. brain)."],
"Z8lGw6": ["Share"],
"ZARuZJ": ["Couldn't load files"],
- "ZBYKxv": [
- "Reverts every change this agent made to <0>",
- ["docName"],
- "</0> this session (",
- ["burstCount", "plural", { "one": ["#", " burst"], "other": ["#", " bursts"] }],
- "). Other files and writers are unaffected."
- ],
"ZBt4rI": ["Instruction for the AI"],
"ZBxvV3": ["New Terminal"],
"ZI8uvA": ["No problems found."],
@@ -1594,6 +1600,7 @@
"ZQJ1IV": ["Activate the last editor tab."],
"ZQLDTl": ["created folder"],
"ZU8VV_": ["Remove failed: ", ["error"]],
+ "ZW3mlR": ["Diff render mode"],
"ZWgr0b": ["In a subfolder"],
"ZWolSV": [
"You picked the filesystem root (/). Scaffolding here will scan every file on this machine — make sure that's what you want."
@@ -1610,6 +1617,7 @@
],
"ZgGuA4": [["0", "plural", { "one": ["File"], "other": ["Files"] }]],
"ZgJVnp": ["Check spelling while typing"],
+ "Zhe80e": ["Restore to edit ", ["burstNumber"], " of ", ["docName"]],
"ZhhOwV": ["Quote"],
"ZjtgI-": ["Command palette"],
"ZoOlzR": [
@@ -1657,6 +1665,7 @@
"_ayOfA": [
"A knowledge base that follows Google's Open Knowledge Format, a shared way of organizing what you know. Pick this if you want your notes to work well with other tools that understand the format."
],
+ "_azghp": ["Previous change"],
"_bth6g": ["Claude Code is installed, but OpenKnowledge tools aren't connected to it yet."],
"_eguJc": ["Uploading"],
"_gkGSK": ["deleted template"],
@@ -1668,6 +1677,7 @@
"_tjopj": ["Paste duplicate"],
"a-cKXz": ["Select all source"],
"a3H_MR": ["Open and focus the Ask AI composer for the current editor selection."],
+ "a4FRQv": ["Undo to this edit?"],
"a5Gha5": ["Local changes blocked the merge"],
"a5W0q0": [
"Are you sure you want to delete ",
@@ -1696,6 +1706,7 @@
"arUUsK": ["Product updates"],
"ax9kie": ["Link preview settings not yet loaded — try again in a moment"],
"az8lvo": ["Off"],
+ "b18t0_": ["Close diff"],
"b3Thhd": ["Upload failed"],
"b4AQFK": ["Open activity panel for ", ["tooltipName"], ", editing ", ["realCurrentDoc"]],
"b4VvP-": [
@@ -1939,17 +1950,6 @@
["shareBranch"],
" already exists. Open its worktree from the switcher instead."
],
- "h6EvY-": [
- "This will replace the current document content with the version from <0>",
- ["relative"],
- " (",
- ["absoluteTime"],
- ", ",
- ["entrySha"],
- ")</0> by <1>",
- ["authorName"],
- "</1>. Your current content is already saved in the timeline — you can restore it anytime."
- ],
"h7FzJC": ["Link-graph response did not match expected shape."],
"h9QFb9": ["Skill \"", ["0"], "\" deleted"],
"hBMK4W": ["Project templates"],
@@ -1990,6 +1990,7 @@
"hyCxJY": ["Open that worktree instead"],
"hynz2K": ["Download started"],
"i-ShMB": ["Diagram"],
+ "i09An-": ["Restored an earlier version (", ["0"], ")"],
"i1flq_": ["Wiki link suggestions"],
"i3f2kh": ["No matching commands."],
"i92eAT": ["We'll create a repository and start syncing — no terminal needed."],
@@ -2013,7 +2014,6 @@
"iKSP5j": ["Word wrap"],
"iKZkk1": ["Property value"],
"iMkWoF": ["Turn on"],
- "iNFKkm": ["No diff."],
"iO8V-7": ["Create worktree"],
"iOHg1t": ["Open embedded URL in new tab"],
"iRdfLr": ["Dev instance: ", ["label"]],
@@ -2090,6 +2090,7 @@
"k4CuuV": [
"Ready-made folders and templates to get you started quickly. Select a pack to preview what gets created, then add it to your project."
],
+ "k7Hoig": ["No content changes at this version."],
"kCNU4q": [
"Indexing your pages — ",
["semanticIndexedCount"],
@@ -2130,6 +2131,7 @@
"khCa4M": ["Teaches coding agents in this project to read and write through OpenKnowledge."],
"kj9pAE": ["Creating page"],
"kknhfj": ["No changes"],
+ "klPS-L": ["Original file — before this agent's edits."],
"kmKqZg": ["Clusters"],
"knjOzA": ["Tag value"],
"kolRU1": ["Do you want to permanently delete instead?"],
@@ -2183,7 +2185,6 @@
"lzwo7p": ["Could not open GitHub sign-in. Please try again."],
"m16xKo": ["Add"],
"m2T1Xj": ["Tag #", ["tagValue"], ", ", ["uses"]],
- "m4v3XT": ["Undo last edit on ", ["docName"]],
"m6YGpY": ["Active panel content for the selected tab shows here."],
"mBltnd": ["Path suggestions"],
"mGaZwZ": ["See the full install guide"],
@@ -2191,7 +2192,6 @@
"mLAjyL": [
"Give the AI tools you use access to read and update your projects. Checking a box sets it up right away; unchecking removes it."
],
- "mNY1G6": ["Undo all edits"],
"mPneVR": ["Updated \"", ["display"], "\" to ", ["0"], "."],
"mPy9lS": [
"Organize my existing specs into a linked index grouped by area, and flag any that have drifted out of sync with the current code."
@@ -2231,6 +2231,7 @@
"mwMF9u": ["Open CodeMirror search in source editor mode."],
"mxY24F": ["Duplicate the focused file-tree item when focus is in the Files sidebar."],
"n2lRue": ["Commit or stash changes to switch:"],
+ "n3wx1q": ["Restore to this version?"],
"n5n_vi": ["Private repository"],
"n6hXUm": [
"Auto-sync periodically fetches, pulls, and pushes commits to your remote git repository so your edits stay in sync across machines."
@@ -2264,6 +2265,16 @@
"ndeI89": ["Use Cmd/Ctrl+C to copy the link below, or open OK in the desktop app."],
"ndwmea": ["unavailable on this platform"],
"neRy3o": ["Split list item"],
+ "nfPccR": [
+ [
+ "laterEdits",
+ "plural",
+ {
+ "one": ["Rolls back ", "#", " later edit."],
+ "other": ["Rolls back ", "#", " later edits."]
+ }
+ ]
+ ],
"nfoduq": ["create worktree"],
"nft48x": [
"Stored at <0>.ok/templates/</0> in this project. Available in every folder (folder-scoped templates can override by filename)."
@@ -2352,7 +2363,6 @@
"pFagOn": ["Source editing"],
"pHYP6v": ["Open <0>Customize</0> in the sidebar <1/> <2>Skills</2>."],
"pQf2Ux": [".ok/skills is back to local-only."],
- "pRc-Im": ["Undone all edits on ", ["docName"]],
"pTPqMK": ["Toggle a fenced code block."],
"pWT04I": ["Checking..."],
"pWbsW6": ["Loading docs"],
@@ -2365,7 +2375,6 @@
"phM8Kh": ["Found the repo but could not open the project. Please try again."],
"pha01Y": ["Project-level pages with no incoming graph edges."],
"pkAft1": ["Search failed."],
- "pmKdif": ["Failed: ", ["loadError"]],
"pmOGtg": [
"Use the default OpenAI endpoint or override it with an OpenAI-compatible base URL for Azure or a self-hosted provider."
],
@@ -2440,7 +2449,6 @@
"rVJpLz": [
"On — hovering an external link sends its URL to the destination site to fetch a preview."
],
- "rVgSRB": ["Collapse ", ["docName"]],
"rVxu1k": ["No pages link here yet."],
"rXz97P": ["Numbered list of items."],
"rZ9HZq": ["To do"],
@@ -2474,6 +2482,7 @@
"sER-bs": ["Files"],
"sFhaTJ": ["Disambiguates similarly-named templates in the menu."],
"sHrqDx": ["Couldn't rename skill: ", ["0"]],
+ "sICrVf": ["Restored to the version from ", ["0"]],
"sIGbBZ": ["Convert selection to footnote"],
"sIxSSP": ["Resolve conflict in your terminal"],
"sJK6pq": ["Permission denied"],
@@ -2524,7 +2533,6 @@
"tHKQ6j": ["Renaming"],
"tP5DDk": ["Apply link"],
"tUvUfp": ["Use a folder you already have."],
- "tW_yvQ": ["Expand ", ["docName"]],
"t_YqKh": ["Remove"],
"teD0H9": ["Couldn't open a worktree for that branch."],
"tfDRzk": ["Save"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 71eb59960..da5356a3d 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -186,6 +186,15 @@ msgstr "{0, plural, one {Folder} other {Folders}}"
msgid "{0, plural, one {No problems across # document.} other {No problems across # documents.}}"
msgstr "{0, plural, one {No problems across # document.} other {No problems across # documents.}}"
+#. placeholder {0}: result.additions
+#. placeholder {0}: stat.additions
+#. placeholder {1}: result.deletions
+#. placeholder {1}: stat.deletions
+#: src/components/AgentDiffPane.tsx
+#: src/components/TimelineDiffPane.tsx
+msgid "{0} added, {1} removed"
+msgstr "{0} added, {1} removed"
+
#. placeholder {0}: labels[key]
#: src/components/settings/CustomThemeEditor.tsx
msgid "{0} hex value"
@@ -419,6 +428,15 @@ msgstr "{keyName} value"
msgid "{label} ({0})"
msgstr "{label} ({0})"
+#: src/components/ActivityPanelBurstRow.tsx
+msgid "{laterEdits, plural, one {Removes # newer edit on this file.} other {Removes # newer edits on this file.}}"
+msgstr "{laterEdits, plural, one {Removes # newer edit on this file.} other {Removes # newer edits on this file.}}"
+
+#: src/components/TimelineDiffPane.tsx
+#: src/components/TimelinePanel.tsx
+msgid "{laterEdits, plural, one {Rolls back # later edit.} other {Rolls back # later edits.}}"
+msgstr "{laterEdits, plural, one {Rolls back # later edit.} other {Rolls back # later edits.}}"
+
#: src/components/GraphPanel.tsx
msgid "{linkCount, plural, one {# link} other {# links}}"
msgstr "{linkCount, plural, one {# link} other {# links}}"
@@ -1357,7 +1375,7 @@ msgstr "Can't safely edit this project config"
msgid "Can't safely edit this tool's config"
msgstr "Can't safely edit this tool's config"
-#: src/components/ActivityPanelFileRow.tsx
+#: src/components/ActivityPanelBurstRow.tsx
#: src/components/AuthModal.tsx
#: src/components/CloneDialog.tsx
#: src/components/ConsentDialogBody.tsx
@@ -1380,6 +1398,7 @@ msgstr "Can't safely edit this tool's config"
#: src/components/ShareReceiveDialog.tsx
#: src/components/SkillRenameDialog.tsx
#: src/components/SkillUpdateDialog.tsx
+#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
#: src/components/TrashFailureModal.tsx
#: src/editor/components/CodePreviewEditModal.tsx
@@ -1598,6 +1617,11 @@ msgstr "Close all"
msgid "Close all unpinned"
msgstr "Close all unpinned"
+#: src/components/AgentDiffPane.tsx
+#: src/components/TimelineDiffPane.tsx
+msgid "Close diff"
+msgstr "Close diff"
+
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Close find"
msgstr "Close find"
@@ -1662,10 +1686,6 @@ msgstr "Collaborators see your in-progress edits as soon as they sync."
msgid "Collapse"
msgstr "Collapse"
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Collapse {docName}"
-msgstr "Collapse {docName}"
-
#: src/components/ArrayOfObjectsWidget.tsx
#: src/components/ObjectWidget.tsx
msgid "Collapse {keyName}"
@@ -1681,10 +1701,6 @@ msgstr "Collapse all"
msgid "Collapse Ask AI"
msgstr "Collapse Ask AI"
-#: src/components/ActivityPanelBurstRow.tsx
-msgid "Collapse burst {burstNumber} diff"
-msgstr "Collapse burst {burstNumber} diff"
-
#: src/components/GraphPanel.tsx
msgid "Collapse graph"
msgstr "Collapse graph"
@@ -2728,11 +2744,13 @@ msgstr "Diagram from Mermaid source — flowchart, sequence, class, state, ER, g
msgid "Diagram view mode"
msgstr "Diagram view mode"
-#: src/components/TimelinePanel.tsx
-msgid "Diff layout"
-msgstr "Diff layout"
+#: src/components/AgentDiffPane.tsx
+#: src/components/TimelineDiffPane.tsx
+msgid "Diff render mode"
+msgstr "Diff render mode"
-#: src/components/TimelinePanel.tsx
+#: src/components/AgentDiffPane.tsx
+#: src/components/TimelineDiffPane.tsx
msgid "Diff unavailable"
msgstr "Diff unavailable"
@@ -3006,6 +3024,10 @@ msgstr "Edit wiki link"
msgid "Edit with AI"
msgstr "Edit with AI"
+#: src/components/TimelinePanel.tsx
+msgid "Edited"
+msgstr "Edited"
+
#: src/editor/link-preview/InternalDocPreviewCard.tsx
msgid "Edited {editedAgo}"
msgstr "Edited {editedAgo}"
@@ -3202,10 +3224,6 @@ msgstr "Existing branch <0>{trimmed}</0> will be checked out into its own window
msgid "Exit merge"
msgstr "Exit merge"
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Expand {docName}"
-msgstr "Expand {docName}"
-
#: src/components/ArrayOfObjectsWidget.tsx
#: src/components/ObjectWidget.tsx
msgid "Expand {keyName}"
@@ -3217,10 +3235,6 @@ msgstr "Expand {keyName}"
msgid "Expand all"
msgstr "Expand all"
-#: src/components/ActivityPanelBurstRow.tsx
-msgid "Expand burst {burstNumber} diff"
-msgstr "Expand burst {burstNumber} diff"
-
#: src/components/GraphPanel.tsx
msgid "Expand graph"
msgstr "Expand graph"
@@ -3514,10 +3528,6 @@ msgstr "Failed to update the project sync default — {detail}"
msgid "Failed to upload file"
msgstr "Failed to upload file"
-#: src/components/ActivityPanelBurstRow.tsx
-msgid "Failed: {loadError}"
-msgstr "Failed: {loadError}"
-
#: src/editor/slash-command/items.tsx
msgid "Fenced code block with monospace text."
msgstr "Fenced code block with monospace text."
@@ -3991,6 +4001,11 @@ msgstr "Hide folder"
msgid "Hide HTML preview"
msgstr "Hide HTML preview"
+#: src/components/AgentDiffPane.tsx
+#: src/components/TimelineDiffPane.tsx
+msgid "Hide panel"
+msgstr "Hide panel"
+
#: src/components/EditorToolbar.tsx
msgid "Hide panel ({panelShortcut})"
msgstr "Hide panel ({panelShortcut})"
@@ -4401,6 +4416,10 @@ msgstr "Label <0>(visible link text)</0>"
msgid "Last sync"
msgstr "Last sync"
+#: src/components/ActivityPanelBurstRow.tsx
+msgid "Latest edit"
+msgstr "Latest edit"
+
#: src/editor/components/Pdf.tsx
msgid "Layout"
msgstr "Layout"
@@ -4513,12 +4532,13 @@ msgstr "Loading branch state"
msgid "Loading conflict for {filePath}"
msgstr "Loading conflict for {filePath}"
-#: src/components/ActivityPanelBurstRow.tsx
-#: src/components/TimelinePanel.tsx
+#: src/components/AgentDiffPane.tsx
+#: src/components/TimelineDiffPane.tsx
msgid "Loading diff"
msgstr "Loading diff"
-#: src/components/TimelinePanel.tsx
+#: src/components/AgentDiffPane.tsx
+#: src/components/TimelineDiffPane.tsx
msgid "Loading diff renderer"
msgstr "Loading diff renderer"
@@ -5032,6 +5052,10 @@ msgstr "New terminal tab"
msgid "New worktree"
msgstr "New worktree"
+#: src/components/TimelineDiffPane.tsx
+msgid "Next change"
+msgstr "Next change"
+
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Next match"
msgstr "Next match"
@@ -5060,14 +5084,18 @@ msgstr "No changes"
msgid "No collab server for this worktree — run <0>ok start</0> here, or reopen the project."
msgstr "No collab server for this worktree — run <0>ok start</0> here, or reopen the project."
+#: src/components/AgentDiffPane.tsx
+msgid "No content changes at this version."
+msgstr "No content changes at this version."
+
+#: src/components/TimelineDiffPane.tsx
+msgid "No content changes in this version"
+msgstr "No content changes in this version"
+
#: src/components/SkillRow.tsx
msgid "No description yet — add one so agents know when to use this skill."
msgstr "No description yet — add one so agents know when to use this skill."
-#: src/components/ActivityPanelBurstRow.tsx
-msgid "No diff."
-msgstr "No diff."
-
#: src/components/GraphPanel.tsx
msgid "No disconnected pages. Pages appear here only when they have no incoming and no outgoing graph edges."
msgstr "No disconnected pages. Pages appear here only when they have no incoming and no outgoing graph edges."
@@ -5335,10 +5363,6 @@ msgstr "Not now"
msgid "Nothing set yet."
msgstr "Nothing set yet."
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Nothing to undo on this file"
-msgstr "Nothing to undo on this file"
-
#: src/components/ReportBugDialogBody.tsx
msgid "Nothing was uploaded. The report stays on this Mac until you email it to us."
msgstr "Nothing was uploaded. The report stays on this Mac until you email it to us."
@@ -5773,6 +5797,10 @@ msgstr "Organize my existing specs into a linked index grouped by area, and flag
msgid "Organize specs"
msgstr "Organize specs"
+#: src/components/AgentDiffPane.tsx
+msgid "Original file — before this agent's edits."
+msgstr "Original file — before this agent's edits."
+
#: src/components/GraphPanel.tsx
msgid "Orphan mode"
msgstr "Orphan mode"
@@ -6022,6 +6050,10 @@ msgstr "Preview unavailable: {errorDetail}"
msgid "Previews of links to other documents in this project are always on and read from the local index — nothing leaves your computer for those."
msgstr "Previews of links to other documents in this project are always on and read from the local index — nothing leaves your computer for those."
+#: src/components/TimelineDiffPane.tsx
+msgid "Previous change"
+msgstr "Previous change"
+
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Previous match"
msgstr "Previous match"
@@ -6420,6 +6452,12 @@ msgstr "Rename succeeded but the sidebar may be out of date — refresh to resyn
msgid "Rename succeeded but the tabstrip may be out of date — refresh to resync"
msgstr "Rename succeeded but the tabstrip may be out of date — refresh to resync"
+#. placeholder {0}: docLeaf(descriptor.from)
+#. placeholder {1}: docLeaf(descriptor.to)
+#: src/components/TimelinePanel.tsx
+msgid "Renamed {0} → {1}"
+msgstr "Renamed {0} → {1}"
+
#: src/components/SkillRenameDialog.tsx
msgid "Renamed to \"{trimmed}\""
msgstr "Renamed to \"{trimmed}\""
@@ -6436,6 +6474,11 @@ msgstr "Renaming"
msgid "Renaming changes the file on disk and the id agents use to pick this template."
msgstr "Renaming changes the file on disk and the id agents use to pick this template."
+#: src/components/AgentDiffPane.tsx
+#: src/components/TimelineDiffPane.tsx
+msgid "Rendered"
+msgstr "Rendered"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Reopen closed tab"
msgstr "Reopen closed tab"
@@ -6598,30 +6641,52 @@ msgstr "Restarting closes this project's server. Connected agents (Claude Code,
msgid "Restarting the server…"
msgstr "Restarting the server…"
+#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
msgid "Restore"
msgstr "Restore"
+#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
msgid "Restore failed"
msgstr "Restore failed"
+#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
msgid "Restore failed — document unchanged"
msgstr "Restore failed — document unchanged"
+#: src/components/ActivityPanelBurstRow.tsx
+msgid "Restore to edit {burstNumber} of {docName}"
+msgstr "Restore to edit {burstNumber} of {docName}"
+
+#: src/components/ActivityPanelBurstRow.tsx
+msgid "Restore to this edit"
+msgstr "Restore to this edit"
+
#: src/components/TimelinePanel.tsx
msgid "Restore to this point"
msgstr "Restore to this point"
+#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
-msgid "Restore to this point?"
-msgstr "Restore to this point?"
+msgid "Restore to this version?"
+msgstr "Restore to this version?"
#: src/components/DiffViewBoundary.tsx
msgid "Restore with remote changes"
msgstr "Restore with remote changes"
+#. placeholder {0}: descriptor.targetSha7
+#: src/components/TimelinePanel.tsx
+msgid "Restored an earlier version ({0})"
+msgstr "Restored an earlier version ({0})"
+
+#. placeholder {0}: formatAbsoluteTime(target.timestamp)
+#: src/components/TimelinePanel.tsx
+msgid "Restored to the version from {0}"
+msgstr "Restored to the version from {0}"
+
#: src/components/CommandPalette.tsx
msgid "Results capped — this workspace has more files than search can index. A missing file may be a cap artifact, not a typo."
msgstr "Results capped — this workspace has more files than search can index. A missing file may be a cap artifact, not a typo."
@@ -6670,10 +6735,6 @@ msgstr "Reveal in Finder, {hint}"
msgid "Reveal in Finder, No workspace"
msgstr "Reveal in Finder, No workspace"
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Reverts every change this agent made to <0>{docName}</0> this session ({burstCount, plural, one {# burst} other {# bursts}}). Other files and writers are unaffected."
-msgstr "Reverts every change this agent made to <0>{docName}</0> this session ({burstCount, plural, one {# burst} other {# bursts}}). Other files and writers are unaffected."
-
#: src/components/SyncStatusBadge.tsx
msgid "Review conflicts"
msgstr "Review conflicts"
@@ -6998,7 +7059,7 @@ msgstr "Server-side cleanup failed for {failedCount, plural, one {# item} other
msgid "Session ended"
msgstr "Session ended"
-#: src/components/ActivityPanelFileRow.tsx
+#: src/components/ActivityPanelBurstRow.tsx
msgid "Session ended — undo unavailable"
msgstr "Session ended — undo unavailable"
@@ -7200,6 +7261,11 @@ msgstr "Show or hide Files"
msgid "Show or hide terminal"
msgstr "Show or hide terminal"
+#: src/components/AgentDiffPane.tsx
+#: src/components/TimelineDiffPane.tsx
+msgid "Show panel"
+msgstr "Show panel"
+
#: src/components/EditorToolbar.tsx
msgid "Show panel ({panelShortcut})"
msgstr "Show panel ({panelShortcut})"
@@ -7359,7 +7425,9 @@ msgstr "Something went wrong starting the terminal."
msgid "Something went wrong. Please try again."
msgstr "Something went wrong. Please try again."
+#: src/components/AgentDiffPane.tsx
#: src/components/MermaidFileViewer.tsx
+#: src/components/TimelineDiffPane.tsx
msgid "Source"
msgstr "Source"
@@ -7399,10 +7467,6 @@ msgstr "Source search"
msgid "Source undo or redo"
msgstr "Source undo or redo"
-#: src/components/TimelinePanel.tsx
-msgid "Split diff"
-msgstr "Split diff"
-
#: src/lib/keyboard-shortcuts.ts
msgid "Split list item"
msgstr "Split list item"
@@ -7634,6 +7698,10 @@ msgstr "Sync status: {syncStateLabel} — git identity unset"
msgid "Synced"
msgstr "Synced"
+#: src/components/TimelinePanel.tsx
+msgid "Synced from disk"
+msgstr "Synced from disk"
+
#: src/components/ShareFreshnessWarning.tsx
msgid "Synced. The link is up to date."
msgstr "Synced. The link is up to date."
@@ -8144,10 +8212,6 @@ msgstr "This template lives in a parent folder — deleting it affects every fol
msgid "This usually means one of:"
msgstr "This usually means one of:"
-#: src/components/TimelinePanel.tsx
-msgid "This will replace the current document content with the version from <0>{relative} ({absoluteTime}, {entrySha})</0> by <1>{authorName}</1>. Your current content is already saved in the timeline — you can restore it anytime."
-msgstr "This will replace the current document content with the version from <0>{relative} ({absoluteTime}, {entrySha})</0> by <1>{authorName}</1>. Your current content is already saved in the timeline — you can restore it anytime."
-
#: src/components/DocPanel.tsx
#: src/components/TimelinePanel.tsx
msgid "Timeline"
@@ -8316,30 +8380,19 @@ msgstr "Uncommitted changes"
msgid "Underline"
msgstr "Underline"
+#: src/components/ActivityModeContent.tsx
+msgid "Undid {dropCount} edits on {docName}"
+msgstr "Undid {dropCount} edits on {docName}"
+
+#: src/components/ActivityModeContent.tsx
+msgid "Undid the last edit on {docName}"
+msgstr "Undid the last edit on {docName}"
+
+#: src/components/ActivityPanelBurstRow.tsx
#: src/components/settings/SharingSection.tsx
msgid "Undo"
msgstr "Undo"
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Undo all"
-msgstr "Undo all"
-
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Undo all edits"
-msgstr "Undo all edits"
-
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Undo all edits on {docName}"
-msgstr "Undo all edits on {docName}"
-
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Undo all edits on this file?"
-msgstr "Undo all edits on this file?"
-
-#: src/components/ActivityModeContent.tsx
-msgid "Undo all failed: {message}"
-msgstr "Undo all failed: {message}"
-
#: src/components/ActivityModeContent.tsx
msgid "Undo buttons are disabled — per-session state has been garbage-collected."
msgstr "Undo buttons are disabled — per-session state has been garbage-collected."
@@ -8348,14 +8401,6 @@ msgstr "Undo buttons are disabled — per-session state has been garbage-collect
msgid "Undo failed: {message}"
msgstr "Undo failed: {message}"
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Undo last edit"
-msgstr "Undo last edit"
-
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Undo last edit on {docName}"
-msgstr "Undo last edit on {docName}"
-
#: src/lib/keyboard-shortcuts.ts
msgid "Undo or redo"
msgstr "Undo or redo"
@@ -8364,18 +8409,14 @@ msgstr "Undo or redo"
msgid "Undo or redo visual-editor changes through TipTap collaboration history."
msgstr "Undo or redo visual-editor changes through TipTap collaboration history."
+#: src/components/ActivityPanelBurstRow.tsx
+msgid "Undo to this edit?"
+msgstr "Undo to this edit?"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Undo, redo, or undo selection changes through CodeMirror history."
msgstr "Undo, redo, or undo selection changes through CodeMirror history."
-#: src/components/ActivityModeContent.tsx
-msgid "Undone all edits on {docName}"
-msgstr "Undone all edits on {docName}"
-
-#: src/components/TimelinePanel.tsx
-msgid "Unified diff"
-msgstr "Unified diff"
-
#: src/components/skill-actions.tsx
msgid "Uninstall"
msgstr "Uninstall"
@@ -8595,6 +8636,10 @@ msgstr "View"
msgid "View as text"
msgstr "View as text"
+#: src/components/ActivityPanelBurstRow.tsx
+msgid "View diff for edit {burstNumber} of {docName}"
+msgstr "View diff for edit {burstNumber} of {docName}"
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Visibility"
msgstr "Visibility"
@@ -8905,6 +8950,11 @@ msgstr "You're subscribed!"
msgid "Your copy of branch <0>{shareBranch}</0> has changes that aren't on GitHub. The {targetNoun} will appear once the branch syncs."
msgstr "Your copy of branch <0>{shareBranch}</0> has changes that aren't on GitHub. The {targetNoun} will appear once the branch syncs."
+#: src/components/TimelineDiffPane.tsx
+#: src/components/TimelinePanel.tsx
+msgid "Your current version is saved first, so this is reversible."
+msgstr "Your current version is saved first, so this is reversible."
+
#: src/components/settings/EmbeddingsKeySection.tsx
msgid "Your embeddings provider API key, used only to create embeddings of your content for semantic search. Stored once for this machine in <0>~/.ok/secrets.yml</0> (readable only by your user account) and shared across all projects. Turn the feature on per project in This project → Search, where you can also override the endpoint."
msgstr "Your embeddings provider API key, used only to create embeddings of your content for semantic search. Stored once for this machine in <0>~/.ok/secrets.yml</0> (readable only by your user account) and shared across all projects. Turn the feature on per project in This project → Search, where you can also override the endpoint."
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index c651ca620..bf3d9846b 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -17,9 +17,10 @@
"-Qw-1t": ["ĜĩţĤũƀ àũţĥēńţĩćàţĩōń ƒàĩĺēď. Ţŕŷ śĩĝńĩńĝ ĩń àĝàĩń."],
"-WFFG2": ["Ďēƒàũĺţ ƥŕōƥēŕţĩēś"],
"-YV1Uo": ["Ƥàţţēŕń ", ["patternNumber"]],
+ "-bFGPF": ["Ńēxţ ćĥàńĝē"],
+ "-dNlfM": ["Ũńďĩď ţĥē ĺàśţ ēďĩţ ōń ", ["docName"]],
"-g6KIS": ["Ũńŕēćōĝńĩźēď ĺĩńķ"],
"-gdcIo": ["Àũţō-śŷńć ĩś ōń — ŷōũŕ ćōḿḿĩţś ƥũśĥ àńď ŕēḿōţē ćĥàńĝēś ƥũĺĺ ōń ĩńţēŕvàĺś."],
- "-i7ik4": ["Ćōĺĺàƥśē ƀũŕśţ ", ["burstNumber"], " ďĩƒƒ"],
"-kbIAr": ["Ĺĩńķś & ĩḿàĝēś"],
"-lCAuQ": ["Ĺōàďĩńĝ ĝŕàƥĥ"],
"-o5XAG": [
@@ -75,6 +76,7 @@
],
"0jD-Gn": ["À ţēàḿ ķńōŵĺēďĝē ƀàśē, à ƥēŕśōńàĺ ŵĩķĩ, ƥŕōĴēćţ ďōćś..."],
"0kTAXe": ["Ōƥēń śōũŕćē: ", ["mirrorSrc"]],
+ "0qyKG6": ["Śŷńćēď ƒŕōḿ ďĩśķ"],
"0rwwOn": ["ßŷ ţàĝ"],
"0s8-e8": [
"Śēĺēćţ, ēńţēŕ, ōŕ ĺēàvē ƀĺōćķ ćōḿƥōńēńţś àńď ƒàĺĺƀàćķ śōũŕćē ƀĺōćķś ƒŕōḿ ķēŷƀōàŕď ƀōũńďàŕĩēś."
@@ -88,6 +90,7 @@
"12F9WL": ["(ńō ĩď)"],
"151wvk": ["Śĥōŵ śĩďēƀàŕ"],
"16D5Zj": ["Àŕē ŷōũ śũŕē ŷōũ ŵàńţ ţō ďēĺēţē ", ["itemName"], "? Ţĥĩś àćţĩōń ćàńńōţ ƀē ũńďōńē."],
+ "170Js2": ["Ĥĩďē ƥàńēĺ"],
"1AumWo": ["Ƥũśĥ ƒàĩĺēď — ćĥēćķ ţĥē śēŕvēŕ ĺōĝś ƒōŕ ďēţàĩĺś."],
"1CalO6": ["Śţŷĺē"],
"1EcCom": [["keyName"], " vàĺũē"],
@@ -140,7 +143,6 @@
"2YOwme": ["Ŕēśţàŕţēď — ńōŵ ŕũńńĩńĝ v", ["appRuntime"], "."],
"2YZwPB": ["Ƒōŕŵàŕď-ĺĩńķś ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ēxƥēćţēď śĥàƥē."],
"2bVHbB": ["Àvàĩĺàƀĺē ĩń ēvēŕŷ ƥŕōĴēćţ ōń ţĥĩś ćōḿƥũţēŕ."],
- "2fkdnR": ["Ńōţĥĩńĝ ţō ũńďō ōń ţĥĩś ƒĩĺē"],
"2hYmUH": ["ḿŷ@ēḿàĩĺ.ćōḿ"],
"2hpdRq": ["Ĥĩďē ƥàńēĺ (", ["panelShortcutLabel"], ")"],
"2j1kfc": ["Ēńţēŕ à vàĺĩď ŨŔĹ (ƒōŕ ēxàḿƥĺē ĥţţƥś://àƥĩ.ōƥēńàĩ.ćōḿ/v1)."],
@@ -160,7 +162,6 @@
"34qyH5": ["Ćōũĺď ńōţ ŕēàćĥ śēŕvēŕ"],
"36WXSC": ["Ćōũĺďń'ţ ďēĺēţē ţēḿƥĺàţē: ", ["error"]],
"36aWJD": ["ĵōĩń ũś ōń Ďĩśćōŕď"],
- "379t2h": ["Ũńĩƒĩēď ďĩƒƒ"],
"38foVZ": ["Ĺōàďĩńĝ ďĩƒƒ"],
"3BnyYc": ["Ţĥĩś ďōć ĩśń'ţ ōń ĜĩţĤũƀ ŷēţ. Ţĥē ĺĩńķ ŵōń'ţ ŵōŕķ ũńţĩĺ ĩţ'ś ƥũśĥēď."],
"3DJEEt": [
@@ -185,6 +186,7 @@
"3TCafD": ["Śţōŕēď ōń ţĥĩś ḿàćĥĩńē."],
"3VbwPp": ["Ōƥēń ", ["keyName"], " ĩń ƀŕōŵśēŕ"],
"3VsNTI": ["Ĺōàďĩńĝ ďōćũḿēńţ"],
+ "3YWddZ": ["Ńō ćōńţēńţ ćĥàńĝēś ĩń ţĥĩś vēŕśĩōń"],
"3YvS-c": ["Ńēŵ ţàƀ"],
"3_6U6f": ["Ćōńńēćţ ţō ĜĩţĤũƀ"],
"3__SjS": ["ƀŕēàďćŕũḿƀ"],
@@ -252,6 +254,7 @@
". Ćĥàńĝē ĩţ ĩń Śēţţĩńĝś → Śŷńć."
],
"4zGlN_": ["Ƥàśţē ĩḿàĝē ŨŔĹ ōŕ ćĺĩćķ ũƥĺōàď"],
+ "4z_1j2": ["Ŕēńďēŕēď"],
"5-FeN2": ["Śĥàŕē ŨŔĹ"],
"5-o4kO": ["Ōńĺŷ ḿàŕķďōŵń ƒĩĺēś"],
"50ORFs": ["Ŕēśēţ ", ["0"], " ţō ďēƒàũĺţ"],
@@ -286,6 +289,7 @@
"5Umg9i": ["Ďĩśàƀĺē ēxţēŕńàĺ ĺĩńķ ƥŕēvĩēŵś"],
"5WDhAk": ["Ĺĩńķ ţō à ƥàĝē ōŕ ēxţēŕńàĺ ŨŔĹ."],
"5ZB7XC": ["Ƒĩĺē ďŕōƥ źōńē"],
+ "5ZbJFS": ["Ŷōũŕ ćũŕŕēńţ vēŕśĩōń ĩś śàvēď ƒĩŕśţ, śō ţĥĩś ĩś ŕēvēŕśĩƀĺē."],
"5_8TCr": ["Ƒĩx àĺĺ (", ["count"], ")"],
"5_j-DA": ["Ķĩĺĺ Ţēŕḿĩńàĺ"],
"5e1Dri": ["Ţĥē ḿēńũ ĺàƀēĺ àĝēńţś ƥĩćķ ţĥĩś ţēḿƥĺàţē ƀŷ (ŕēǫũĩŕēď)."],
@@ -320,6 +324,7 @@
"6-wLTJ": [["behind"], " ƀēĥĩńď ōŕĩĝĩń"],
"60vpJN": ["Ŵĥàţ ŵēŕē ŷōũ ďōĩńĝ?"],
"62Pc08": ["Ĩńśţàĺĺ ƒōŕ Ćĺàũďē Ćĥàţ & Ćōŵōŕķ (Ďēśķţōƥ Àƥƥ)"],
+ "62bOuM": ["Ĺàţēśţ ēďĩţ"],
"636K3K": ["Ďēĺēţē àďĴàćēńţ ćĥĩƥ"],
"67f-3g": ["Ďũƥĺĩćàţē śũććēēďēď ƀũţ ţĥē śĩďēƀàŕ ḿàŷ ƀē ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],
"6Aih4U": ["Ōƒƒĺĩńē"],
@@ -350,6 +355,7 @@
"6gRgw8": ["Ŕēţŕŷ"],
"6h4zVU": ["Ŵĥàţ ŵōũĺď ŷōũ ĺĩķē ţō ćŕēàţē?"],
"6hfDJr": ["Śēŕvēŕ ēŕŕōŕ: ", ["status"]],
+ "6iDEWA": ["Śĥōŵ ƥàńēĺ"],
"6ibbCg": ["Ćŕēàţē ŷōũŕ ƒĩŕśţ ƒĩĺē"],
"6ki7F2": [["0", "plural", { "one": ["#", " ĩţēḿ"], "other": ["#", " ĩţēḿś"] }]],
"6lGV3K": ["Śĥōŵ ĺēśś"],
@@ -371,7 +377,6 @@
"7Fkcej": ["+ Àďď ", ["addChildName"]],
"7H4UHD": ["Ďōćũḿēńţś ţàĝĝēď <0>#", ["tagName"], "</0>"],
"7JtSLi": ["Ƒàĩĺēď ţō ďēĺēţē ƥàţĥ"],
- "7KeV5F": ["Ũńďō àĺĺ ƒàĩĺēď: ", ["message"]],
"7OhaRy": ["Śōũŕćē śēàŕćĥ"],
"7Ongq0": ["Ćōńďēńśē ḿŷ ÀĜĒŃŢŚ.ḿď ƒĩĺē ţō ĺēśś ţĥàń 40ķ ćĥàŕàćţēŕś"],
"7OwvEL": ["Śĥōŵ ĤŢḾĹ ƥŕēvĩēŵ"],
@@ -431,6 +436,7 @@
"8eW0WQ": ["Ńō ḿàţćĥĩńĝ ŕēƥōśĩţōŕĩēś."],
"8fRyLo": ["Ĩńvàĺĩď ƥàţćĥ ƥàŷĺōàď"],
"8fc_3j": ["Ƥŕōţēćţēď ƀŕàńćĥ — ćàńńōţ ƥũśĥ"],
+ "8lwQlE": [["0"], " àďďēď, ", ["1"], " ŕēḿōvēď"],
"8m8diM": ["Ńō ĺōćàţĩōń śēĺēćţēď. Ũśē ßŕōŵśē ţō ćĥōōśē à ƒōĺďēŕ."],
"8nWu1k": ["Ēḿƥţŷ ďĩàĝŕàḿ"],
"8tjQCz": ["Ēxƥĺōŕē"],
@@ -518,9 +524,9 @@
],
"Aif3E7": ["Ēńàƀĺē śēḿàńţĩć śēàŕćĥ"],
"Am78jY": ["Ďŕàĝ ", ["keyName"], " ţō ŕēōŕďēŕ"],
+ "ApeA0n": ["Ũńďĩď ", ["dropCount"], " ēďĩţś ōń ", ["docName"]],
"Aq-O0x": ["śţàţũś"],
"AqnqMJ": ["ÀƤĨ ķēŷ śēţ"],
- "ArBWJf": ["Ũńďō ĺàśţ ēďĩţ"],
"AsqRE_": ["Ďēƒàũĺţ ĺōćàţĩōń ƒōŕ ńēŵ àţţàćĥḿēńţś"],
"AtBdnD": ["Ćōũĺďń'ţ ďēĺēţē śķĩĺĺ: ", ["error"]],
"B11p-O": ["Ēďĩţ ḿàŕķďōŵń ĺĩńķ"],
@@ -691,7 +697,6 @@
"EcM3k7": ["Ƒàĩĺēď ţō ćĺēàń ũƥ ƥēńďĩńĝ ", ["kind"]],
"EcR0fl": ["Ćĥēćķĩńĝ ƒōŕ ĩńśţàĺĺēď àĝēńţś"],
"EdQY6l": ["Ńōńē"],
- "EeRZnZ": ["Ēxƥàńď ƀũŕśţ ", ["burstNumber"], " ďĩƒƒ"],
"Ef7StM": ["Ũńķńōŵń"],
"EhDLBx": ["Ŷōũ ḿōďĩƒĩēď <0>", ["filePath"], "</0> ĺōćàĺĺŷ, ƀũţ ĩţ ŵàś ďēĺēţēď ũƥśţŕēàḿ."],
"Ehkru0": ["Ōƥēń, ńàvĩĝàţē, àććēƥţ, ōŕ ďĩśḿĩśś ĆōďēḾĩŕŕōŕ ćōḿƥĺēţĩōń śũĝĝēśţĩōńś."],
@@ -802,6 +807,7 @@
"GemPfn": ["Ƒàĩĺēď ţō ƥàŕśē ƒōŕŵàŕď-ĺĩńķś ēŕŕōŕ ŕēśƥōńśē (ĤŢŢƤ ", ["status"], ")"],
"Gfr4fu": ["Śēŕvēŕ ćàń'ţ ōƥēń ďōćũḿēńţś"],
"GhjUB_": ["Ŕēćōńńēćţēď"],
+ "GkYV_4": ["Ŕēńàḿēď ", ["0"], " → ", ["1"]],
"Gp_twO": ["Ĺōćàĺ ƥàţĥ"],
"GsBUCk": ["Ĺōàďĩńĝ śēţţĩńĝś"],
"Gt4gOO": ["Ţĥĩś ƒōĺďēŕ ĥàś ũńƥũśĥēď ćĥàńĝēś. Ŕēćĩƥĩēńţś ŵĩĺĺ śēē ţĥē ĺàśţ ƥũśĥēď vēŕśĩōń."],
@@ -822,7 +828,6 @@
"HPTPGr": ["Ćŕēàţē à ńēŵ śƥēć ƒĩĺē ƒōŕ ḿŷ ũśēŕ śţōŕŷ"],
"HSh8u_": ["Ƒōĺďēŕś"],
"HTW0Zw": ["Ōńē ḿōŕē śţēƥ: ŕũń <0>ćĺàũďē</0> ĩń ţĥĩś ƥŕōĴēćţ àńď àƥƥŕōvē ŌƥēńĶńōŵĺēďĝē ōńćē."],
- "HXFyWD": ["Śƥĺĩţ ďĩƒƒ"],
"HdkSiO": ["Ńēŵ ƒĩĺē"],
"HfI1dR": ["Ĩ àĺŕēàďŷ ĥàvē ĩţ ĺōćàĺĺŷ →"],
"HjNrT0": [["0", "plural", { "one": ["#", " ƀàćķĺĩńķ"], "other": ["#", " ƀàćķĺĩńķś"] }]],
@@ -880,7 +885,6 @@
"Ix0K8o": ["Ĥĩďē ēxţēŕńàĺ ŨŔĹ ńōďēś"],
"IxyZXD": ["Śćŕēēńśĥōţ"],
"Izb10l": ["Ƒĩx àĺĺ ", ["count"], " ƒĩxàƀĺē ƥŕōƀĺēḿś"],
- "J2MgzQ": ["Ũńďō àĺĺ ēďĩţś ōń ", ["docName"]],
"J2Mv98": ["Ńàḿē (ē.ĝ. ", ["login"], ")"],
"J2eKUI": ["Ƒĩĺē"],
"J3HzPL": ["Ćōĺĺàƥśē ", ["keyName"]],
@@ -973,6 +977,16 @@
"LCUy_N": ["Śēśśĩōń ēńďēď"],
"LDuM35": ["Ŕēƥĺàćē ćũŕŕēńţ ḿàţćĥ ƒŕōḿ ƒĩēĺď"],
"LE7t79": ["Ćĺōńē ţō à ńēŵ ƒōĺďēŕ"],
+ "LKIPzv": [
+ [
+ "laterEdits",
+ "plural",
+ {
+ "one": ["Ŕēḿōvēś ", "#", " ńēŵēŕ ēďĩţ ōń ţĥĩś ƒĩĺē."],
+ "other": ["Ŕēḿōvēś ", "#", " ńēŵēŕ ēďĩţś ōń ţĥĩś ƒĩĺē."]
+ }
+ ]
+ ],
"LKOLNn": ["Ńō ÀĨ àĝēńţś ĩńśţàĺĺēď"],
"LNum6A": [["minutes"], " ḿĩń àĝō"],
"LRgZAt": [["owner"], "/", ["name"], " àĺŕēàďŷ ēxĩśţś"],
@@ -1032,12 +1046,12 @@
"MJqRO6": ["Ŷōũŕ ŕēƥōŕţ ĩś ƀēĩńĝ śēńţ."],
"MKOVhz": ["Ēńàƀĺē ĝĩţ àũţō-śŷńć"],
"MQIM_Y": ["Ćōũĺďń'ţ ćōƥŷ. Śēĺēćţ ţĥē ŨŔĹ àƀōvē ţō ćōƥŷ ĩţ ḿàńũàĺĺŷ."],
+ "MRZxAn": ["Ēďĩţēď"],
"MTs6g3": ["Ćōũĺďń'ţ ŕēćōńńēćţ àƒţēŕ śēŕvēŕ ŕēśţàŕţ"],
"MUBR8r": ["Ŕēńàḿē śũććēēďēď ƀũţ ţĥē ţàƀśţŕĩƥ ḿàŷ ƀē ōũţ ōƒ ďàţē — ŕēƒŕēśĥ ţō ŕēśŷńć"],
"MUrVEo": ["Ńō ŕēćēńţ ƥŕōĴēćţś."],
"MV-Dkb": ["Ƒōũńď ", ["countDisplay"], " ḿàŕķďōŵń ƒĩĺēś"],
"MVxpbf": ["Ƒĩńď àńď ŕēƥĺàćē"],
- "MWrUEd": ["Ũńďō àĺĺ"],
"MZSBsh": [
"Ńō ţēḿƥĺàţēś ŷēţ. Àďď ōńē ţō ĝĩvē ńēŵ ďōćś ĩń ţĥĩś ƒōĺďēŕ à ŕēàďŷ-ḿàďē śţàŕţĩńĝ ƥōĩńţ."
],
@@ -1199,7 +1213,6 @@
],
"PrJYSN": ["Ţĥĩś ƒōĺďēŕ ĩśń'ţ ōń ĜĩţĤũƀ ŷēţ. Ţĥē ĺĩńķ ŵōń'ţ ŵōŕķ ũńţĩĺ ĩţ'ś ƥũśĥēď."],
"PrhzDE": ["Ƥàń ũƥ"],
- "Pyp1NA": ["Ŕēśţōŕē ţō ţĥĩś ƥōĩńţ?"],
"Q1mtyd": ["Ĥĩďē śĩďēƀàŕ"],
"Q5fqMz": ["Ćōńńēćţĩōń ēŕŕōŕ — ţŕŷ àĝàĩń"],
"Q6hhn8": ["Ƥŕēƒēŕēńćēś"],
@@ -1289,8 +1302,8 @@
"S9t1PI": ["Ƒĩxĩńĝ ", ["0"], "/", ["1"]],
"SCoBBH": ["Ţàĝ śũĝĝēśţĩōńś"],
"SCzAbA": [["phase"], " — ", ["pct"], "%"],
- "SEYWYq": ["Ũńďō àĺĺ ēďĩţś ōń ţĥĩś ƒĩĺē?"],
"SFN6dN": ["Ĥēàďĩńĝ 3"],
+ "SOPwPh": ["Ŕēśţōŕē ţō ţĥĩś ēďĩţ"],
"STTOnz": [["keyName"], " ţŷƥē: ćōḿƥĺēx vàĺũē (ńēśţēď; ŕēàď-ōńĺŷ)"],
"SUOoXn": ["Ƒàĩĺēď ţō ōƥēń ƥŕōĴēćţ."],
"SVLPt5": [["formatted"], " ĜĩţĤũƀ śţàŕś"],
@@ -1518,7 +1531,6 @@
"XuQzrk": [
"Ćōũĺďń'ţ ŕēśţàŕţ ţĥē śēŕvēŕ — àńōţĥēŕ ƥŕōćēśś ōŵńś ĩţ. Ǫũĩţ ōţĥēŕ ŌƥēńĶńōŵĺēďĝē ŵĩńďōŵś ƒōŕ ţĥĩś ƥŕōĴēćţ, ţĥēń ţŕŷ àĝàĩń."
],
- "XvPJaT": ["Ďĩƒƒ ĺàŷōũţ"],
"Xv_ijG": ["ĥţţƥś://ĝĩţĥũƀ.ćōḿ/ōŵńēŕ/ŕēƥō ōŕ ōŵńēŕ/ŕēƥō"],
"Xw_maT": ["Ţŷƥē à ǫũēŕŷ, ţĥēń ƥŕēśś ↵ ţō śēàŕćĥ ŷōũŕ ƥàĝēś ƀŷ ḿēàńĩńĝ."],
"Xwump4": ["ńō ĝĩţ ŕēƥōśĩţōŕŷ ĥēŕē"],
@@ -1571,6 +1583,7 @@
"Z6rrjc": [
"Ńō <0>.ḿàŕķďōŵńĺĩńţ.*</0> ƒĩĺē ŷēţ — ēvēŕŷ ŕũĺē ŕũńś ōń ţĥē śàḿē ďēƒàũĺţś àś ţĥē VŚ Ćōďē ḿàŕķďōŵńĺĩńţ ēxţēńśĩōń: àĺĺ ōń, ēxćēƥţ ĺĩńē ĺēńĝţĥ."
],
+ "Z79bnE": ["Vĩēŵ ďĩƒƒ ƒōŕ ēďĩţ ", ["burstNumber"], " ōƒ ", ["docName"]],
"Z7x_Zh": [
"Ĝĩţ ńēēďś ",
["tool"],
@@ -1579,13 +1592,6 @@
"Z8KDox": ["Ēńţēŕ à ƒōĺďēŕ ńàḿē (ē.ĝ. ƀŕàĩń)."],
"Z8lGw6": ["Śĥàŕē"],
"ZARuZJ": ["Ćōũĺďń'ţ ĺōàď ƒĩĺēś"],
- "ZBYKxv": [
- "Ŕēvēŕţś ēvēŕŷ ćĥàńĝē ţĥĩś àĝēńţ ḿàďē ţō <0>",
- ["docName"],
- "</0> ţĥĩś śēśśĩōń (",
- ["burstCount", "plural", { "one": ["#", " ƀũŕśţ"], "other": ["#", " ƀũŕśţś"] }],
- "). Ōţĥēŕ ƒĩĺēś àńď ŵŕĩţēŕś àŕē ũńàƒƒēćţēď."
- ],
"ZBt4rI": ["Ĩńśţŕũćţĩōń ƒōŕ ţĥē ÀĨ"],
"ZBxvV3": ["Ńēŵ Ţēŕḿĩńàĺ"],
"ZI8uvA": ["Ńō ƥŕōƀĺēḿś ƒōũńď."],
@@ -1594,6 +1600,7 @@
"ZQJ1IV": ["Àćţĩvàţē ţĥē ĺàśţ ēďĩţōŕ ţàƀ."],
"ZQLDTl": ["ćŕēàţēď ƒōĺďēŕ"],
"ZU8VV_": ["Ŕēḿōvē ƒàĩĺēď: ", ["error"]],
+ "ZW3mlR": ["Ďĩƒƒ ŕēńďēŕ ḿōďē"],
"ZWgr0b": ["Ĩń à śũƀƒōĺďēŕ"],
"ZWolSV": [
"Ŷōũ ƥĩćķēď ţĥē ƒĩĺēśŷśţēḿ ŕōōţ (/). Śćàƒƒōĺďĩńĝ ĥēŕē ŵĩĺĺ śćàń ēvēŕŷ ƒĩĺē ōń ţĥĩś ḿàćĥĩńē — ḿàķē śũŕē ţĥàţ'ś ŵĥàţ ŷōũ ŵàńţ."
@@ -1610,6 +1617,7 @@
],
"ZgGuA4": [["0", "plural", { "one": ["Ƒĩĺē"], "other": ["Ƒĩĺēś"] }]],
"ZgJVnp": ["Ćĥēćķ śƥēĺĺĩńĝ ŵĥĩĺē ţŷƥĩńĝ"],
+ "Zhe80e": ["Ŕēśţōŕē ţō ēďĩţ ", ["burstNumber"], " ōƒ ", ["docName"]],
"ZhhOwV": ["Ǫũōţē"],
"ZjtgI-": ["Ćōḿḿàńď ƥàĺēţţē"],
"ZoOlzR": [
@@ -1657,6 +1665,7 @@
"_ayOfA": [
"À ķńōŵĺēďĝē ƀàśē ţĥàţ ƒōĺĺōŵś Ĝōōĝĺē'ś Ōƥēń Ķńōŵĺēďĝē Ƒōŕḿàţ, à śĥàŕēď ŵàŷ ōƒ ōŕĝàńĩźĩńĝ ŵĥàţ ŷōũ ķńōŵ. Ƥĩćķ ţĥĩś ĩƒ ŷōũ ŵàńţ ŷōũŕ ńōţēś ţō ŵōŕķ ŵēĺĺ ŵĩţĥ ōţĥēŕ ţōōĺś ţĥàţ ũńďēŕśţàńď ţĥē ƒōŕḿàţ."
],
+ "_azghp": ["Ƥŕēvĩōũś ćĥàńĝē"],
"_bth6g": ["Ćĺàũďē Ćōďē ĩś ĩńśţàĺĺēď, ƀũţ ŌƥēńĶńōŵĺēďĝē ţōōĺś àŕēń'ţ ćōńńēćţēď ţō ĩţ ŷēţ."],
"_eguJc": ["Ũƥĺōàďĩńĝ"],
"_gkGSK": ["ďēĺēţēď ţēḿƥĺàţē"],
@@ -1668,6 +1677,7 @@
"_tjopj": ["Ƥàśţē ďũƥĺĩćàţē"],
"a-cKXz": ["Śēĺēćţ àĺĺ śōũŕćē"],
"a3H_MR": ["Ōƥēń àńď ƒōćũś ţĥē Àśķ ÀĨ ćōḿƥōśēŕ ƒōŕ ţĥē ćũŕŕēńţ ēďĩţōŕ śēĺēćţĩōń."],
+ "a4FRQv": ["Ũńďō ţō ţĥĩś ēďĩţ?"],
"a5Gha5": ["Ĺōćàĺ ćĥàńĝēś ƀĺōćķēď ţĥē ḿēŕĝē"],
"a5W0q0": [
"Àŕē ŷōũ śũŕē ŷōũ ŵàńţ ţō ďēĺēţē ",
@@ -1696,6 +1706,7 @@
"arUUsK": ["Ƥŕōďũćţ ũƥďàţēś"],
"ax9kie": ["Ĺĩńķ ƥŕēvĩēŵ śēţţĩńĝś ńōţ ŷēţ ĺōàďēď — ţŕŷ àĝàĩń ĩń à ḿōḿēńţ"],
"az8lvo": ["Ōƒƒ"],
+ "b18t0_": ["Ćĺōśē ďĩƒƒ"],
"b3Thhd": ["Ũƥĺōàď ƒàĩĺēď"],
"b4AQFK": ["Ōƥēń àćţĩvĩţŷ ƥàńēĺ ƒōŕ ", ["tooltipName"], ", ēďĩţĩńĝ ", ["realCurrentDoc"]],
"b4VvP-": [
@@ -1939,17 +1950,6 @@
["shareBranch"],
" àĺŕēàďŷ ēxĩśţś. Ōƥēń ĩţś ŵōŕķţŕēē ƒŕōḿ ţĥē śŵĩţćĥēŕ ĩńśţēàď."
],
- "h6EvY-": [
- "Ţĥĩś ŵĩĺĺ ŕēƥĺàćē ţĥē ćũŕŕēńţ ďōćũḿēńţ ćōńţēńţ ŵĩţĥ ţĥē vēŕśĩōń ƒŕōḿ <0>",
- ["relative"],
- " (",
- ["absoluteTime"],
- ", ",
- ["entrySha"],
- ")</0> ƀŷ <1>",
- ["authorName"],
- "</1>. Ŷōũŕ ćũŕŕēńţ ćōńţēńţ ĩś àĺŕēàďŷ śàvēď ĩń ţĥē ţĩḿēĺĩńē — ŷōũ ćàń ŕēśţōŕē ĩţ àńŷţĩḿē."
- ],
"h7FzJC": ["Ĺĩńķ-ĝŕàƥĥ ŕēśƥōńśē ďĩď ńōţ ḿàţćĥ ēxƥēćţēď śĥàƥē."],
"h9QFb9": ["Śķĩĺĺ \"", ["0"], "\" ďēĺēţēď"],
"hBMK4W": ["ƤŕōĴēćţ ţēḿƥĺàţēś"],
@@ -1990,6 +1990,7 @@
"hyCxJY": ["Ōƥēń ţĥàţ ŵōŕķţŕēē ĩńśţēàď"],
"hynz2K": ["Ďōŵńĺōàď śţàŕţēď"],
"i-ShMB": ["Ďĩàĝŕàḿ"],
+ "i09An-": ["Ŕēśţōŕēď àń ēàŕĺĩēŕ vēŕśĩōń (", ["0"], ")"],
"i1flq_": ["Ŵĩķĩ ĺĩńķ śũĝĝēśţĩōńś"],
"i3f2kh": ["Ńō ḿàţćĥĩńĝ ćōḿḿàńďś."],
"i92eAT": ["Ŵē'ĺĺ ćŕēàţē à ŕēƥōśĩţōŕŷ àńď śţàŕţ śŷńćĩńĝ — ńō ţēŕḿĩńàĺ ńēēďēď."],
@@ -2013,7 +2014,6 @@
"iKSP5j": ["Ŵōŕď ŵŕàƥ"],
"iKZkk1": ["Ƥŕōƥēŕţŷ vàĺũē"],
"iMkWoF": ["Ţũŕń ōń"],
- "iNFKkm": ["Ńō ďĩƒƒ."],
"iO8V-7": ["Ćŕēàţē ŵōŕķţŕēē"],
"iOHg1t": ["Ōƥēń ēḿƀēďďēď ŨŔĹ ĩń ńēŵ ţàƀ"],
"iRdfLr": ["Ďēv ĩńśţàńćē: ", ["label"]],
@@ -2090,6 +2090,7 @@
"k4CuuV": [
"Ŕēàďŷ-ḿàďē ƒōĺďēŕś àńď ţēḿƥĺàţēś ţō ĝēţ ŷōũ śţàŕţēď ǫũĩćķĺŷ. Śēĺēćţ à ƥàćķ ţō ƥŕēvĩēŵ ŵĥàţ ĝēţś ćŕēàţēď, ţĥēń àďď ĩţ ţō ŷōũŕ ƥŕōĴēćţ."
],
+ "k7Hoig": ["Ńō ćōńţēńţ ćĥàńĝēś àţ ţĥĩś vēŕśĩōń."],
"kCNU4q": [
"Ĩńďēxĩńĝ ŷōũŕ ƥàĝēś — ",
["semanticIndexedCount"],
@@ -2130,6 +2131,7 @@
"khCa4M": ["Ţēàćĥēś ćōďĩńĝ àĝēńţś ĩń ţĥĩś ƥŕōĴēćţ ţō ŕēàď àńď ŵŕĩţē ţĥŕōũĝĥ ŌƥēńĶńōŵĺēďĝē."],
"kj9pAE": ["Ćŕēàţĩńĝ ƥàĝē"],
"kknhfj": ["Ńō ćĥàńĝēś"],
+ "klPS-L": ["Ōŕĩĝĩńàĺ ƒĩĺē — ƀēƒōŕē ţĥĩś àĝēńţ'ś ēďĩţś."],
"kmKqZg": ["Ćĺũśţēŕś"],
"knjOzA": ["Ţàĝ vàĺũē"],
"kolRU1": ["Ďō ŷōũ ŵàńţ ţō ƥēŕḿàńēńţĺŷ ďēĺēţē ĩńśţēàď?"],
@@ -2183,7 +2185,6 @@
"lzwo7p": ["Ćōũĺď ńōţ ōƥēń ĜĩţĤũƀ śĩĝń-ĩń. Ƥĺēàśē ţŕŷ àĝàĩń."],
"m16xKo": ["Àďď"],
"m2T1Xj": ["Ţàĝ #", ["tagValue"], ", ", ["uses"]],
- "m4v3XT": ["Ũńďō ĺàśţ ēďĩţ ōń ", ["docName"]],
"m6YGpY": ["Àćţĩvē ƥàńēĺ ćōńţēńţ ƒōŕ ţĥē śēĺēćţēď ţàƀ śĥōŵś ĥēŕē."],
"mBltnd": ["Ƥàţĥ śũĝĝēśţĩōńś"],
"mGaZwZ": ["Śēē ţĥē ƒũĺĺ ĩńśţàĺĺ ĝũĩďē"],
@@ -2191,7 +2192,6 @@
"mLAjyL": [
"Ĝĩvē ţĥē ÀĨ ţōōĺś ŷōũ ũśē àććēśś ţō ŕēàď àńď ũƥďàţē ŷōũŕ ƥŕōĴēćţś. Ćĥēćķĩńĝ à ƀōx śēţś ĩţ ũƥ ŕĩĝĥţ àŵàŷ; ũńćĥēćķĩńĝ ŕēḿōvēś ĩţ."
],
- "mNY1G6": ["Ũńďō àĺĺ ēďĩţś"],
"mPneVR": ["Ũƥďàţēď \"", ["display"], "\" ţō ", ["0"], "."],
"mPy9lS": [
"Ōŕĝàńĩźē ḿŷ ēxĩśţĩńĝ śƥēćś ĩńţō à ĺĩńķēď ĩńďēx ĝŕōũƥēď ƀŷ àŕēà, àńď ƒĺàĝ àńŷ ţĥàţ ĥàvē ďŕĩƒţēď ōũţ ōƒ śŷńć ŵĩţĥ ţĥē ćũŕŕēńţ ćōďē."
@@ -2231,6 +2231,7 @@
"mwMF9u": ["Ōƥēń ĆōďēḾĩŕŕōŕ śēàŕćĥ ĩń śōũŕćē ēďĩţōŕ ḿōďē."],
"mxY24F": ["Ďũƥĺĩćàţē ţĥē ƒōćũśēď ƒĩĺē-ţŕēē ĩţēḿ ŵĥēń ƒōćũś ĩś ĩń ţĥē Ƒĩĺēś śĩďēƀàŕ."],
"n2lRue": ["Ćōḿḿĩţ ōŕ śţàśĥ ćĥàńĝēś ţō śŵĩţćĥ:"],
+ "n3wx1q": ["Ŕēśţōŕē ţō ţĥĩś vēŕśĩōń?"],
"n5n_vi": ["Ƥŕĩvàţē ŕēƥōśĩţōŕŷ"],
"n6hXUm": [
"Àũţō-śŷńć ƥēŕĩōďĩćàĺĺŷ ƒēţćĥēś, ƥũĺĺś, àńď ƥũśĥēś ćōḿḿĩţś ţō ŷōũŕ ŕēḿōţē ĝĩţ ŕēƥōśĩţōŕŷ śō ŷōũŕ ēďĩţś śţàŷ ĩń śŷńć àćŕōśś ḿàćĥĩńēś."
@@ -2264,6 +2265,16 @@
"ndeI89": ["Ũśē Ćḿď/Ćţŕĺ+Ć ţō ćōƥŷ ţĥē ĺĩńķ ƀēĺōŵ, ōŕ ōƥēń ŌĶ ĩń ţĥē ďēśķţōƥ àƥƥ."],
"ndwmea": ["ũńàvàĩĺàƀĺē ōń ţĥĩś ƥĺàţƒōŕḿ"],
"neRy3o": ["Śƥĺĩţ ĺĩśţ ĩţēḿ"],
+ "nfPccR": [
+ [
+ "laterEdits",
+ "plural",
+ {
+ "one": ["Ŕōĺĺś ƀàćķ ", "#", " ĺàţēŕ ēďĩţ."],
+ "other": ["Ŕōĺĺś ƀàćķ ", "#", " ĺàţēŕ ēďĩţś."]
+ }
+ ]
+ ],
"nfoduq": ["ćŕēàţē ŵōŕķţŕēē"],
"nft48x": [
"Śţōŕēď àţ <0>.ōķ/ţēḿƥĺàţēś/</0> ĩń ţĥĩś ƥŕōĴēćţ. Àvàĩĺàƀĺē ĩń ēvēŕŷ ƒōĺďēŕ (ƒōĺďēŕ-śćōƥēď ţēḿƥĺàţēś ćàń ōvēŕŕĩďē ƀŷ ƒĩĺēńàḿē)."
@@ -2352,7 +2363,6 @@
"pFagOn": ["Śōũŕćē ēďĩţĩńĝ"],
"pHYP6v": ["Ōƥēń <0>Ćũśţōḿĩźē</0> ĩń ţĥē śĩďēƀàŕ <1/> <2>Śķĩĺĺś</2>."],
"pQf2Ux": [".ōķ/śķĩĺĺś ĩś ƀàćķ ţō ĺōćàĺ-ōńĺŷ."],
- "pRc-Im": ["Ũńďōńē àĺĺ ēďĩţś ōń ", ["docName"]],
"pTPqMK": ["Ţōĝĝĺē à ƒēńćēď ćōďē ƀĺōćķ."],
"pWT04I": ["Ćĥēćķĩńĝ..."],
"pWbsW6": ["Ĺōàďĩńĝ ďōćś"],
@@ -2365,7 +2375,6 @@
"phM8Kh": ["Ƒōũńď ţĥē ŕēƥō ƀũţ ćōũĺď ńōţ ōƥēń ţĥē ƥŕōĴēćţ. Ƥĺēàśē ţŕŷ àĝàĩń."],
"pha01Y": ["ƤŕōĴēćţ-ĺēvēĺ ƥàĝēś ŵĩţĥ ńō ĩńćōḿĩńĝ ĝŕàƥĥ ēďĝēś."],
"pkAft1": ["Śēàŕćĥ ƒàĩĺēď."],
- "pmKdif": ["Ƒàĩĺēď: ", ["loadError"]],
"pmOGtg": [
"Ũśē ţĥē ďēƒàũĺţ ŌƥēńÀĨ ēńďƥōĩńţ ōŕ ōvēŕŕĩďē ĩţ ŵĩţĥ àń ŌƥēńÀĨ-ćōḿƥàţĩƀĺē ƀàśē ŨŔĹ ƒōŕ Àźũŕē ōŕ à śēĺƒ-ĥōśţēď ƥŕōvĩďēŕ."
],
@@ -2440,7 +2449,6 @@
"rVJpLz": [
"Ōń — ĥōvēŕĩńĝ àń ēxţēŕńàĺ ĺĩńķ śēńďś ĩţś ŨŔĹ ţō ţĥē ďēśţĩńàţĩōń śĩţē ţō ƒēţćĥ à ƥŕēvĩēŵ."
],
- "rVgSRB": ["Ćōĺĺàƥśē ", ["docName"]],
"rVxu1k": ["Ńō ƥàĝēś ĺĩńķ ĥēŕē ŷēţ."],
"rXz97P": ["Ńũḿƀēŕēď ĺĩśţ ōƒ ĩţēḿś."],
"rZ9HZq": ["Ţō ďō"],
@@ -2474,6 +2482,7 @@
"sER-bs": ["Ƒĩĺēś"],
"sFhaTJ": ["Ďĩśàḿƀĩĝũàţēś śĩḿĩĺàŕĺŷ-ńàḿēď ţēḿƥĺàţēś ĩń ţĥē ḿēńũ."],
"sHrqDx": ["Ćōũĺďń'ţ ŕēńàḿē śķĩĺĺ: ", ["0"]],
+ "sICrVf": ["Ŕēśţōŕēď ţō ţĥē vēŕśĩōń ƒŕōḿ ", ["0"]],
"sIGbBZ": ["Ćōńvēŕţ śēĺēćţĩōń ţō ƒōōţńōţē"],
"sIxSSP": ["Ŕēśōĺvē ćōńƒĺĩćţ ĩń ŷōũŕ ţēŕḿĩńàĺ"],
"sJK6pq": ["Ƥēŕḿĩśśĩōń ďēńĩēď"],
@@ -2524,7 +2533,6 @@
"tHKQ6j": ["Ŕēńàḿĩńĝ"],
"tP5DDk": ["Àƥƥĺŷ ĺĩńķ"],
"tUvUfp": ["Ũśē à ƒōĺďēŕ ŷōũ àĺŕēàďŷ ĥàvē."],
- "tW_yvQ": ["Ēxƥàńď ", ["docName"]],
"t_YqKh": ["Ŕēḿōvē"],
"teD0H9": ["Ćōũĺďń'ţ ōƥēń à ŵōŕķţŕēē ƒōŕ ţĥàţ ƀŕàńćĥ."],
"tfDRzk": ["Śàvē"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 59e93a1fa..80dbe84f9 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -186,6 +186,15 @@ msgstr ""
msgid "{0, plural, one {No problems across # document.} other {No problems across # documents.}}"
msgstr ""
+#. placeholder {0}: result.additions
+#. placeholder {0}: stat.additions
+#. placeholder {1}: result.deletions
+#. placeholder {1}: stat.deletions
+#: src/components/AgentDiffPane.tsx
+#: src/components/TimelineDiffPane.tsx
+msgid "{0} added, {1} removed"
+msgstr ""
+
#. placeholder {0}: labels[key]
#: src/components/settings/CustomThemeEditor.tsx
msgid "{0} hex value"
@@ -419,6 +428,15 @@ msgstr ""
msgid "{label} ({0})"
msgstr ""
+#: src/components/ActivityPanelBurstRow.tsx
+msgid "{laterEdits, plural, one {Removes # newer edit on this file.} other {Removes # newer edits on this file.}}"
+msgstr ""
+
+#: src/components/TimelineDiffPane.tsx
+#: src/components/TimelinePanel.tsx
+msgid "{laterEdits, plural, one {Rolls back # later edit.} other {Rolls back # later edits.}}"
+msgstr ""
+
#: src/components/GraphPanel.tsx
msgid "{linkCount, plural, one {# link} other {# links}}"
msgstr ""
@@ -1353,7 +1371,7 @@ msgstr ""
msgid "Can't safely edit this tool's config"
msgstr ""
-#: src/components/ActivityPanelFileRow.tsx
+#: src/components/ActivityPanelBurstRow.tsx
#: src/components/AuthModal.tsx
#: src/components/CloneDialog.tsx
#: src/components/ConsentDialogBody.tsx
@@ -1376,6 +1394,7 @@ msgstr ""
#: src/components/ShareReceiveDialog.tsx
#: src/components/SkillRenameDialog.tsx
#: src/components/SkillUpdateDialog.tsx
+#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
#: src/components/TrashFailureModal.tsx
#: src/editor/components/CodePreviewEditModal.tsx
@@ -1594,6 +1613,11 @@ msgstr ""
msgid "Close all unpinned"
msgstr ""
+#: src/components/AgentDiffPane.tsx
+#: src/components/TimelineDiffPane.tsx
+msgid "Close diff"
+msgstr ""
+
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Close find"
msgstr ""
@@ -1658,10 +1682,6 @@ msgstr ""
msgid "Collapse"
msgstr ""
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Collapse {docName}"
-msgstr ""
-
#: src/components/ArrayOfObjectsWidget.tsx
#: src/components/ObjectWidget.tsx
msgid "Collapse {keyName}"
@@ -1677,10 +1697,6 @@ msgstr ""
msgid "Collapse Ask AI"
msgstr ""
-#: src/components/ActivityPanelBurstRow.tsx
-msgid "Collapse burst {burstNumber} diff"
-msgstr ""
-
#: src/components/GraphPanel.tsx
msgid "Collapse graph"
msgstr ""
@@ -2724,11 +2740,13 @@ msgstr ""
msgid "Diagram view mode"
msgstr ""
-#: src/components/TimelinePanel.tsx
-msgid "Diff layout"
+#: src/components/AgentDiffPane.tsx
+#: src/components/TimelineDiffPane.tsx
+msgid "Diff render mode"
msgstr ""
-#: src/components/TimelinePanel.tsx
+#: src/components/AgentDiffPane.tsx
+#: src/components/TimelineDiffPane.tsx
msgid "Diff unavailable"
msgstr ""
@@ -3002,6 +3020,10 @@ msgstr ""
msgid "Edit with AI"
msgstr ""
+#: src/components/TimelinePanel.tsx
+msgid "Edited"
+msgstr ""
+
#: src/editor/link-preview/InternalDocPreviewCard.tsx
msgid "Edited {editedAgo}"
msgstr ""
@@ -3198,10 +3220,6 @@ msgstr ""
msgid "Exit merge"
msgstr ""
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Expand {docName}"
-msgstr ""
-
#: src/components/ArrayOfObjectsWidget.tsx
#: src/components/ObjectWidget.tsx
msgid "Expand {keyName}"
@@ -3213,10 +3231,6 @@ msgstr ""
msgid "Expand all"
msgstr ""
-#: src/components/ActivityPanelBurstRow.tsx
-msgid "Expand burst {burstNumber} diff"
-msgstr ""
-
#: src/components/GraphPanel.tsx
msgid "Expand graph"
msgstr ""
@@ -3510,10 +3524,6 @@ msgstr ""
msgid "Failed to upload file"
msgstr ""
-#: src/components/ActivityPanelBurstRow.tsx
-msgid "Failed: {loadError}"
-msgstr ""
-
#: src/editor/slash-command/items.tsx
msgid "Fenced code block with monospace text."
msgstr ""
@@ -3987,6 +3997,11 @@ msgstr ""
msgid "Hide HTML preview"
msgstr ""
+#: src/components/AgentDiffPane.tsx
+#: src/components/TimelineDiffPane.tsx
+msgid "Hide panel"
+msgstr ""
+
#: src/components/EditorToolbar.tsx
msgid "Hide panel ({panelShortcut})"
msgstr ""
@@ -4397,6 +4412,10 @@ msgstr ""
msgid "Last sync"
msgstr ""
+#: src/components/ActivityPanelBurstRow.tsx
+msgid "Latest edit"
+msgstr ""
+
#: src/editor/components/Pdf.tsx
msgid "Layout"
msgstr ""
@@ -4509,12 +4528,13 @@ msgstr ""
msgid "Loading conflict for {filePath}"
msgstr ""
-#: src/components/ActivityPanelBurstRow.tsx
-#: src/components/TimelinePanel.tsx
+#: src/components/AgentDiffPane.tsx
+#: src/components/TimelineDiffPane.tsx
msgid "Loading diff"
msgstr ""
-#: src/components/TimelinePanel.tsx
+#: src/components/AgentDiffPane.tsx
+#: src/components/TimelineDiffPane.tsx
msgid "Loading diff renderer"
msgstr ""
@@ -5028,6 +5048,10 @@ msgstr ""
msgid "New worktree"
msgstr ""
+#: src/components/TimelineDiffPane.tsx
+msgid "Next change"
+msgstr ""
+
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Next match"
msgstr ""
@@ -5056,12 +5080,16 @@ msgstr ""
msgid "No collab server for this worktree — run <0>ok start</0> here, or reopen the project."
msgstr ""
-#: src/components/SkillRow.tsx
-msgid "No description yet — add one so agents know when to use this skill."
+#: src/components/AgentDiffPane.tsx
+msgid "No content changes at this version."
msgstr ""
-#: src/components/ActivityPanelBurstRow.tsx
-msgid "No diff."
+#: src/components/TimelineDiffPane.tsx
+msgid "No content changes in this version"
+msgstr ""
+
+#: src/components/SkillRow.tsx
+msgid "No description yet — add one so agents know when to use this skill."
msgstr ""
#: src/components/GraphPanel.tsx
@@ -5331,10 +5359,6 @@ msgstr ""
msgid "Nothing set yet."
msgstr ""
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Nothing to undo on this file"
-msgstr ""
-
#: src/components/ReportBugDialogBody.tsx
msgid "Nothing was uploaded. The report stays on this Mac until you email it to us."
msgstr ""
@@ -5769,6 +5793,10 @@ msgstr ""
msgid "Organize specs"
msgstr ""
+#: src/components/AgentDiffPane.tsx
+msgid "Original file — before this agent's edits."
+msgstr ""
+
#: src/components/GraphPanel.tsx
msgid "Orphan mode"
msgstr ""
@@ -6018,6 +6046,10 @@ msgstr ""
msgid "Previews of links to other documents in this project are always on and read from the local index — nothing leaves your computer for those."
msgstr ""
+#: src/components/TimelineDiffPane.tsx
+msgid "Previous change"
+msgstr ""
+
#: src/editor/find-replace/FindReplaceBar.tsx
msgid "Previous match"
msgstr ""
@@ -6416,6 +6448,12 @@ msgstr ""
msgid "Rename succeeded but the tabstrip may be out of date — refresh to resync"
msgstr ""
+#. placeholder {0}: docLeaf(descriptor.from)
+#. placeholder {1}: docLeaf(descriptor.to)
+#: src/components/TimelinePanel.tsx
+msgid "Renamed {0} → {1}"
+msgstr ""
+
#: src/components/SkillRenameDialog.tsx
msgid "Renamed to \"{trimmed}\""
msgstr ""
@@ -6432,6 +6470,11 @@ msgstr ""
msgid "Renaming changes the file on disk and the id agents use to pick this template."
msgstr ""
+#: src/components/AgentDiffPane.tsx
+#: src/components/TimelineDiffPane.tsx
+msgid "Rendered"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Reopen closed tab"
msgstr ""
@@ -6594,30 +6637,52 @@ msgstr ""
msgid "Restarting the server…"
msgstr ""
+#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
msgid "Restore"
msgstr ""
+#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
msgid "Restore failed"
msgstr ""
+#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
msgid "Restore failed — document unchanged"
msgstr ""
+#: src/components/ActivityPanelBurstRow.tsx
+msgid "Restore to edit {burstNumber} of {docName}"
+msgstr ""
+
+#: src/components/ActivityPanelBurstRow.tsx
+msgid "Restore to this edit"
+msgstr ""
+
#: src/components/TimelinePanel.tsx
msgid "Restore to this point"
msgstr ""
+#: src/components/TimelineDiffPane.tsx
#: src/components/TimelinePanel.tsx
-msgid "Restore to this point?"
+msgid "Restore to this version?"
msgstr ""
#: src/components/DiffViewBoundary.tsx
msgid "Restore with remote changes"
msgstr ""
+#. placeholder {0}: descriptor.targetSha7
+#: src/components/TimelinePanel.tsx
+msgid "Restored an earlier version ({0})"
+msgstr ""
+
+#. placeholder {0}: formatAbsoluteTime(target.timestamp)
+#: src/components/TimelinePanel.tsx
+msgid "Restored to the version from {0}"
+msgstr ""
+
#: src/components/CommandPalette.tsx
msgid "Results capped — this workspace has more files than search can index. A missing file may be a cap artifact, not a typo."
msgstr ""
@@ -6666,10 +6731,6 @@ msgstr ""
msgid "Reveal in Finder, No workspace"
msgstr ""
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Reverts every change this agent made to <0>{docName}</0> this session ({burstCount, plural, one {# burst} other {# bursts}}). Other files and writers are unaffected."
-msgstr ""
-
#: src/components/SyncStatusBadge.tsx
msgid "Review conflicts"
msgstr ""
@@ -6994,7 +7055,7 @@ msgstr ""
msgid "Session ended"
msgstr ""
-#: src/components/ActivityPanelFileRow.tsx
+#: src/components/ActivityPanelBurstRow.tsx
msgid "Session ended — undo unavailable"
msgstr ""
@@ -7196,6 +7257,11 @@ msgstr ""
msgid "Show or hide terminal"
msgstr ""
+#: src/components/AgentDiffPane.tsx
+#: src/components/TimelineDiffPane.tsx
+msgid "Show panel"
+msgstr ""
+
#: src/components/EditorToolbar.tsx
msgid "Show panel ({panelShortcut})"
msgstr ""
@@ -7355,7 +7421,9 @@ msgstr ""
msgid "Something went wrong. Please try again."
msgstr ""
+#: src/components/AgentDiffPane.tsx
#: src/components/MermaidFileViewer.tsx
+#: src/components/TimelineDiffPane.tsx
msgid "Source"
msgstr ""
@@ -7395,10 +7463,6 @@ msgstr ""
msgid "Source undo or redo"
msgstr ""
-#: src/components/TimelinePanel.tsx
-msgid "Split diff"
-msgstr ""
-
#: src/lib/keyboard-shortcuts.ts
msgid "Split list item"
msgstr ""
@@ -7630,6 +7694,10 @@ msgstr ""
msgid "Synced"
msgstr ""
+#: src/components/TimelinePanel.tsx
+msgid "Synced from disk"
+msgstr ""
+
#: src/components/ShareFreshnessWarning.tsx
msgid "Synced. The link is up to date."
msgstr ""
@@ -8140,10 +8208,6 @@ msgstr ""
msgid "This usually means one of:"
msgstr ""
-#: src/components/TimelinePanel.tsx
-msgid "This will replace the current document content with the version from <0>{relative} ({absoluteTime}, {entrySha})</0> by <1>{authorName}</1>. Your current content is already saved in the timeline — you can restore it anytime."
-msgstr ""
-
#: src/components/DocPanel.tsx
#: src/components/TimelinePanel.tsx
msgid "Timeline"
@@ -8312,28 +8376,17 @@ msgstr ""
msgid "Underline"
msgstr ""
-#: src/components/settings/SharingSection.tsx
-msgid "Undo"
-msgstr ""
-
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Undo all"
-msgstr ""
-
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Undo all edits"
-msgstr ""
-
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Undo all edits on {docName}"
+#: src/components/ActivityModeContent.tsx
+msgid "Undid {dropCount} edits on {docName}"
msgstr ""
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Undo all edits on this file?"
+#: src/components/ActivityModeContent.tsx
+msgid "Undid the last edit on {docName}"
msgstr ""
-#: src/components/ActivityModeContent.tsx
-msgid "Undo all failed: {message}"
+#: src/components/ActivityPanelBurstRow.tsx
+#: src/components/settings/SharingSection.tsx
+msgid "Undo"
msgstr ""
#: src/components/ActivityModeContent.tsx
@@ -8344,14 +8397,6 @@ msgstr ""
msgid "Undo failed: {message}"
msgstr ""
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Undo last edit"
-msgstr ""
-
-#: src/components/ActivityPanelFileRow.tsx
-msgid "Undo last edit on {docName}"
-msgstr ""
-
#: src/lib/keyboard-shortcuts.ts
msgid "Undo or redo"
msgstr ""
@@ -8360,16 +8405,12 @@ msgstr ""
msgid "Undo or redo visual-editor changes through TipTap collaboration history."
msgstr ""
-#: src/lib/keyboard-shortcuts.ts
-msgid "Undo, redo, or undo selection changes through CodeMirror history."
-msgstr ""
-
-#: src/components/ActivityModeContent.tsx
-msgid "Undone all edits on {docName}"
+#: src/components/ActivityPanelBurstRow.tsx
+msgid "Undo to this edit?"
msgstr ""
-#: src/components/TimelinePanel.tsx
-msgid "Unified diff"
+#: src/lib/keyboard-shortcuts.ts
+msgid "Undo, redo, or undo selection changes through CodeMirror history."
msgstr ""
#: src/components/skill-actions.tsx
@@ -8591,6 +8632,10 @@ msgstr ""
msgid "View as text"
msgstr ""
+#: src/components/ActivityPanelBurstRow.tsx
+msgid "View diff for edit {burstNumber} of {docName}"
+msgstr ""
+
#: src/components/PublishToGitHubDialog.tsx
msgid "Visibility"
msgstr ""
@@ -8901,6 +8946,11 @@ msgstr ""
msgid "Your copy of branch <0>{shareBranch}</0> has changes that aren't on GitHub. The {targetNoun} will appear once the branch syncs."
msgstr ""
+#: src/components/TimelineDiffPane.tsx
+#: src/components/TimelinePanel.tsx
+msgid "Your current version is saved first, so this is reversible."
+msgstr ""
+
#: src/components/settings/EmbeddingsKeySection.tsx
msgid "Your embeddings provider API key, used only to create embeddings of your content for semantic search. Stored once for this machine in <0>~/.ok/secrets.yml</0> (readable only by your user account) and shared across all projects. Turn the feature on per project in This project → Search, where you can also override the endpoint."
msgstr ""
diff --git a/packages/app/tests/integration/api-error-envelope/agent-burst-diff.test.ts b/packages/app/tests/integration/api-error-envelope/agent-burst-diff.test.ts
index 28d71d088..f49bcac16 100644
--- a/packages/app/tests/integration/api-error-envelope/agent-burst-diff.test.ts
+++ b/packages/app/tests/integration/api-error-envelope/agent-burst-diff.test.ts
@@ -3,10 +3,10 @@
*
*
* Asserts the canonical RFC 9457 wire shape for
- * `GET /api/agent-burst-diff?agentId=...&docName=...&stackIndex=...`:
+ * `GET /api/agent-burst-diff?agentId=...&docName=...&keptCount=...`:
* - missing agentId / docName → 400 `urn:ok:error:invalid-request`.
* - reserved docname → 400 `urn:ok:error:reserved-doc-name`.
- * - non-numeric / negative stackIndex → 400 `urn:ok:error:invalid-request`.
+ * - non-numeric / negative keptCount → 400 `urn:ok:error:invalid-request`.
* - no active session → 404 `urn:ok:error:no-active-session`.
* - method-not-allowed on POST → 405 `urn:ok:error:method-not-allowed`.
*
@@ -34,7 +34,7 @@ afterAll(async () => {
describe('agent-burst-diff envelope (RFC 9457)', () => {
test('missing agentId emits 400 urn:ok:error:invalid-request', async () => {
const res = await fetch(
- `http://127.0.0.1:${server.port}/api/agent-burst-diff?docName=foo&stackIndex=0`,
+ `http://127.0.0.1:${server.port}/api/agent-burst-diff?docName=foo&keptCount=0`,
);
expect(res.status).toBe(400);
expect(res.headers.get('content-type')).toBe('application/problem+json');
@@ -49,7 +49,7 @@ describe('agent-burst-diff envelope (RFC 9457)', () => {
test('missing docName emits 400 urn:ok:error:invalid-request', async () => {
const res = await fetch(
- `http://127.0.0.1:${server.port}/api/agent-burst-diff?agentId=agent-x&stackIndex=0`,
+ `http://127.0.0.1:${server.port}/api/agent-burst-diff?agentId=agent-x&keptCount=0`,
);
expect(res.status).toBe(400);
@@ -63,7 +63,7 @@ describe('agent-burst-diff envelope (RFC 9457)', () => {
test('reserved docname emits 400 urn:ok:error:reserved-doc-name', async () => {
const res = await fetch(
- `http://127.0.0.1:${server.port}/api/agent-burst-diff?agentId=agent-x&docName=__system__&stackIndex=0`,
+ `http://127.0.0.1:${server.port}/api/agent-burst-diff?agentId=agent-x&docName=__system__&keptCount=0`,
);
expect(res.status).toBe(400);
@@ -74,9 +74,9 @@ describe('agent-burst-diff envelope (RFC 9457)', () => {
}
});
- test('negative stackIndex emits 400 urn:ok:error:invalid-request', async () => {
+ test('negative keptCount emits 400 urn:ok:error:invalid-request', async () => {
const res = await fetch(
- `http://127.0.0.1:${server.port}/api/agent-burst-diff?agentId=agent-x&docName=foo&stackIndex=-1`,
+ `http://127.0.0.1:${server.port}/api/agent-burst-diff?agentId=agent-x&docName=foo&keptCount=-1`,
);
expect(res.status).toBe(400);
@@ -90,7 +90,7 @@ describe('agent-burst-diff envelope (RFC 9457)', () => {
test('no active session emits 404 urn:ok:error:no-active-session', async () => {
const res = await fetch(
- `http://127.0.0.1:${server.port}/api/agent-burst-diff?agentId=agent-x&docName=does-not-exist-${crypto.randomUUID().slice(0, 8)}&stackIndex=0`,
+ `http://127.0.0.1:${server.port}/api/agent-burst-diff?agentId=agent-x&docName=does-not-exist-${crypto.randomUUID().slice(0, 8)}&keptCount=0`,
);
expect(res.status).toBe(404);
diff --git a/packages/app/tests/stress/agent-activity-panel.e2e.ts b/packages/app/tests/stress/agent-activity-panel.e2e.ts
index 165ea5205..9aa62103b 100644
--- a/packages/app/tests/stress/agent-activity-panel.e2e.ts
+++ b/packages/app/tests/stress/agent-activity-panel.e2e.ts
@@ -12,8 +12,10 @@
* `'doc'` mode. Tooltip copy is verified.
* - click a filename in the activity list → main editor navigates;
* panel stays in `'agent'` mode.
- * - Undo last dispatch does not move the main editor's
- * active doc and does not exit the activity view.
+ * - click an edit row → opens that version's agent-diff pane; the pane
+ * paints over the editor, so the main editor follows to the agent's doc
+ * while the activity view stays open (supersedes the original AC-P7
+ * "active doc unchanged on undo" — the agent-diff pane now drives nav).
*
* Behaviour deliberately NOT tested here, with rationale:
* - live CC1 update (700 ms arrival budget) — the Playwright
@@ -30,8 +32,8 @@
* [data-testid="docpanel-exit-agent-mode"] — back-arrow button
* [data-testid="activity-panel-file-row"] — one file entry
* [data-testid="activity-panel-file-row-filename"] — filename link
- * [data-testid="activity-panel-file-row-carrot"] — expand toggle
- * [data-testid="activity-panel-undo-last"] — undo-last button
+ * [data-testid="activity-panel-burst-open"] — one edit row (opens its diff)
+ * [data-testid="activity-panel-burst-restore"] — per-edit restore action
*/
import { expect, test, waitForActiveProviderSynced as waitForProvider } from './_helpers';
@@ -237,7 +239,10 @@ test.describe('Activity mode (DocPanel) — avatar drill-in, back-arrow exit', (
await expect(panel).toBeVisible();
});
- test('AC-P4 (carryover): undo does not move main editor active doc', async ({ page, api }) => {
+ test('clicking an edit row opens the version diff and the editor follows to the agent doc', async ({
+ page,
+ api,
+ }) => {
const docView = 'panel-t7-view';
const docAgent = 'panel-t7-agent';
await api.seedDocs([
@@ -266,18 +271,24 @@ test.describe('Activity mode (DocPanel) — avatar drill-in, back-arrow exit', (
const panel = page.locator('[data-testid="activity-panel"]');
await expect(panel).toBeVisible({ timeout: 5_000 });
- // Expand the file row, then click Undo last.
+ // Edits are always expanded now — click the edit row to open its diff.
const row = panel.locator('[data-testid="activity-panel-file-row"]').first();
- await row.locator('[data-testid="activity-panel-file-row-carrot"]').click();
- const undoLast = panel.locator('[data-testid="activity-panel-undo-last"]');
- await expect(undoLast).toBeVisible({ timeout: 5_000 });
- await undoLast.click();
+ const burst = row.locator('[data-testid="activity-panel-burst-open"]').first();
+ await expect(burst).toBeVisible({ timeout: 5_000 });
+ await burst.click();
- // After undo dispatch, the URL hash (active doc) stays on docView.
+ // Clicking the edit opens the agent-diff pane. The pane paints over the
+ // editor slot, so EditorArea navigates the main editor to the agent's doc
+ // — the URL hash moves off docView onto docAgent.
+ await expect
+ .poll(async () => page.url(), { timeout: 5_000, intervals: [100, 250, 500] })
+ .not.toBe(urlBefore);
await expect
- .poll(async () => page.url(), { timeout: 2_000, intervals: [100, 250, 500] })
- .toBe(urlBefore);
- // DocPanel stays in agent mode across undo.
+ .poll(async () => page.url(), { timeout: 5_000, intervals: [100, 250, 500] })
+ .toContain(`/#/${docAgent}`);
+ // The staged version's diff is now painting over the editor.
+ await expect(page.locator('[data-testid="agent-diff-pane"]')).toBeVisible({ timeout: 5_000 });
+ // DocPanel stays in agent mode across the version-diff open.
const backButton = page.locator('[data-testid="docpanel-exit-agent-mode"]');
await expect(backButton).toBeVisible();
});
diff --git a/packages/core/src/schemas/api/agent-write.test.ts b/packages/core/src/schemas/api/agent-write.test.ts
index 5b45c0401..652bde179 100644
--- a/packages/core/src/schemas/api/agent-write.test.ts
+++ b/packages/core/src/schemas/api/agent-write.test.ts
@@ -210,6 +210,23 @@ describe('AgentUndoRequestSchema', () => {
});
expect(result.success).toBe(false);
});
+
+ test("parses scope 'count' with a positive count", () => {
+ const result = AgentUndoRequestSchema.safeParse({
+ connectionId: 'agent-abc',
+ scope: 'count',
+ count: 3,
+ });
+ expect(result.success).toBe(true);
+ });
+
+ test("rejects scope 'count' without a count (would silently no-op server-side)", () => {
+ const result = AgentUndoRequestSchema.safeParse({
+ connectionId: 'agent-abc',
+ scope: 'count',
+ });
+ expect(result.success).toBe(false);
+ });
});
describe('SummaryResponseFieldSchema', () => {
diff --git a/packages/core/src/schemas/api/agent-write.ts b/packages/core/src/schemas/api/agent-write.ts
index d830e893c..602275734 100644
--- a/packages/core/src/schemas/api/agent-write.ts
+++ b/packages/core/src/schemas/api/agent-write.ts
@@ -85,15 +85,30 @@ export type AgentPatchRequest = z.infer<typeof AgentPatchRequestSchema>;
* `'last'`; `'file'` is a legacy alias for `'session'` (drains the entire
* stack in one call) — the handler collapses `'file'` to `'session'` in
* the response.
+ *
+ * `'count'` pops the `count` newest stack frames atomically — the scoped
+ * "undo to edit N" range the Activity panel's undo timeline commits (drop the
+ * N newest edits, keep the rest). `count` is required with this scope; the
+ * server clamps it to the live stack depth.
*/
export const AgentUndoRequestSchema = z
.object({
docName: safeDocNameField,
connectionId: z.string().min(1),
- scope: z.enum(['last', 'session', 'file']).optional(),
+ scope: z.enum(['last', 'session', 'file', 'count']).optional(),
+ /** Number of newest stack frames to pop — only read when `scope === 'count'`. */
+ count: z.number().int().positive().optional(),
...agentIdentityFields,
})
- .loose() satisfies StandardSchemaV1;
+ .loose()
+ // `scope: 'count'` REQUIRES `count`. Without this the server clamps a missing
+ // count to 0 frames → a silent no-op that still returns success, masking a
+ // client bug. Reject at the boundary instead (the doc above says count is
+ // required with this scope). Other scopes ignore count.
+ .refine((body) => body.scope !== 'count' || body.count !== undefined, {
+ message: "count is required when scope is 'count'",
+ path: ['count'],
+ }) satisfies StandardSchemaV1;
export type AgentUndoRequest = z.infer<typeof AgentUndoRequestSchema>;
/**
@@ -410,13 +425,13 @@ export type AgentPatchSuccess = z.infer<typeof AgentPatchSuccessSchema>;
/**
* Success body for `POST /api/agent-undo`. `scope` reflects the resolved
- * scope after collapsing `'file'` → `'session'`. `undone` is `false` when
- * the UM stack was empty (a no-op undo).
+ * scope after collapsing `'file'` → `'session'` (`'count'` passes through).
+ * `undone` is `false` when the UM stack was empty (a no-op undo).
*/
export const AgentUndoSuccessSchema = z
.object({
docName: z.string().min(1),
- scope: z.enum(['last', 'session']),
+ scope: z.enum(['last', 'session', 'count']),
undone: z.boolean(),
})
.loose() satisfies StandardSchemaV1;
diff --git a/packages/core/src/schemas/api/history.ts b/packages/core/src/schemas/api/history.ts
index 107867239..9aa55c556 100644
--- a/packages/core/src/schemas/api/history.ts
+++ b/packages/core/src/schemas/api/history.ts
@@ -98,6 +98,7 @@ export const HistoryEntrySchema = z
message: z.string(),
contributors: z.array(HistoryShadowContributorSchema),
checkpoint: z.unknown().nullable(),
+ parentSha: z.string().nullable().optional(),
})
.loose() satisfies StandardSchemaV1;
export type HistoryEntry = z.infer<typeof HistoryEntrySchema>;
diff --git a/packages/core/src/schemas/api/metrics.test.ts b/packages/core/src/schemas/api/metrics.test.ts
index ea992e944..7cbd36a21 100644
--- a/packages/core/src/schemas/api/metrics.test.ts
+++ b/packages/core/src/schemas/api/metrics.test.ts
@@ -159,22 +159,36 @@ describe('AgentBurstDiffSuccessSchema', () => {
expect(
AgentBurstDiffSuccessSchema.safeParse({
diff: '@@ -1 +1 @@\n-old\n+new\n',
+ before: 'old',
+ after: 'new',
generatedAt: 1714512345000,
}).success,
).toBe(true);
});
- test('parses an empty diff string', () => {
+ test('parses an empty diff string with empty bodies', () => {
expect(
AgentBurstDiffSuccessSchema.safeParse({
diff: '',
+ before: '',
+ after: '',
generatedAt: 0,
}).success,
).toBe(true);
});
+ test('rejects a missing before/after body', () => {
+ expect(
+ AgentBurstDiffSuccessSchema.safeParse({
+ diff: '',
+ generatedAt: 0,
+ }).success,
+ ).toBe(false);
+ });
test('rejects negative generatedAt', () => {
expect(
AgentBurstDiffSuccessSchema.safeParse({
diff: '',
+ before: '',
+ after: '',
generatedAt: -1,
}).success,
).toBe(false);
diff --git a/packages/core/src/schemas/api/metrics.ts b/packages/core/src/schemas/api/metrics.ts
index 55bec9413..a836262f7 100644
--- a/packages/core/src/schemas/api/metrics.ts
+++ b/packages/core/src/schemas/api/metrics.ts
@@ -25,6 +25,9 @@ import { z } from 'zod';
/** One unified-diff burst entry on `AgentActivitySuccessSchema.files[].bursts[]`. */
export const ActivityBurstSchema = z
.object({
+ // 0-based position of this burst in the undo stack. NOTE: this is NOT the
+ // `agent-burst-diff` wire parameter — that endpoint takes `keptCount`
+ // (edits-to-keep, 1-based), which for this burst is `stackIndex + 1`.
stackIndex: z.number().int().min(0),
ts: z.number().int().min(0),
additions: z.number().int().min(0),
@@ -76,16 +79,20 @@ export type AgentActivitySuccess = z.infer<typeof AgentActivitySuccessSchema>;
/**
* Success response for
- * `GET /api/agent-burst-diff?agentId=<connId>&docName=<path>&stackIndex=<n>`.
+ * `GET /api/agent-burst-diff?agentId=<connId>&docName=<path>&keptCount=<n>`.
*
* `diff` is unified-diff text (CommonMark-style — empty string when the
- * StackItem produces a no-op diff). `generatedAt` is the server's wall
- * clock at response-emit time; clients use it for staleness detection
- * against `bursts[].ts` (already returned by `/api/agent-activity`).
+ * StackItem produces a no-op diff). `before`/`after` are the frontmatter-
+ * stripped bodies of the two versions the diff compares, so the client can
+ * render a WYSIWYG diff (via `buildRenderedDiff`) without recomputing them.
+ * `generatedAt` is the server's wall clock at response-emit time; clients use
+ * it for staleness detection against `bursts[].ts` (from `/api/agent-activity`).
*/
export const AgentBurstDiffSuccessSchema = z
.object({
diff: z.string(),
+ before: z.string(),
+ after: z.string(),
generatedAt: z.number().int().min(0),
})
.loose() satisfies StandardSchemaV1;
diff --git a/packages/core/src/types/timeline.ts b/packages/core/src/types/timeline.ts
index a98904d97..97f772203 100644
--- a/packages/core/src/types/timeline.ts
+++ b/packages/core/src/types/timeline.ts
@@ -23,4 +23,15 @@ export interface TimelineEntry {
* any checkpoint whose body line is missing or malformed.
*/
checkpoint: ParsedCheckpoint | null;
+ /**
+ * SHA of the previous VISIBLE timeline entry for this doc — list-adjacency in
+ * the assembled, ok-actor-filtered, timestamp-sorted result (`filtered[idx+1]`),
+ * NOT `git <sha>^`. The timeline is a multi-ref merge, so the git parent is
+ * usually another writer's commit or a filtered checkpoint; list-adjacency is
+ * the "previous version a reader saw." `null` for the doc's first version or an
+ * entry whose parent fell outside the depth-bounded walk. Baseline for the
+ * vs-parent ("changes in this version") diff. Populated only in the per-doc
+ * history path; absent on folder-timeline entries.
+ */
+ parentSha?: string | null;
}
diff --git a/packages/server/src/agent-activity.test.ts b/packages/server/src/agent-activity.test.ts
index 1deb59440..5f51b8e06 100644
--- a/packages/server/src/agent-activity.test.ts
+++ b/packages/server/src/agent-activity.test.ts
@@ -9,7 +9,8 @@ import * as Y from 'yjs';
import {
listAgentActivity,
synthesizeStackItemDiff,
- synthesizeStackItemDiffText,
+ synthesizeVersionDiff,
+ synthesizeVersionDiffText,
} from './agent-activity.ts';
import type { AgentSessionManager } from './agent-sessions.ts';
@@ -132,35 +133,93 @@ describe('synthesizeStackItemDiff', () => {
// synthesizeStackItemDiffText
// ---------------------------------------------------------------------------
-describe('synthesizeStackItemDiffText', () => {
- test('returns empty string when before === after', () => {
+describe('synthesizeVersionDiffText', () => {
+ test('version 0 (original) is an empty diff', () => {
const doc = new Y.Doc();
const text = doc.getText('source');
- const dummyStackItem = {
- insertions: Y.createDeleteSet(),
- deletions: Y.createDeleteSet(),
- meta: new Map(),
- // biome-ignore lint/suspicious/noExplicitAny: structural cast for test dummy
- } as any;
- const result = synthesizeStackItemDiffText(dummyStackItem, text, 'doc.md');
- expect(result).toBe('');
+ const { origin, um } = makeUMPair(doc, text);
+ doc.transact(() => text.insert(0, 'new line\n'), origin);
+
+ // keptCount 0 → original vs original → empty (the pre-edit file).
+ // biome-ignore lint/suspicious/noExplicitAny: Y.StackItem is internal to yjs
+ expect(synthesizeVersionDiffText(um.undoStack as any, 0, text, 'doc.md')).toBe('');
});
- test('returns unified diff with + lines for an insertion', () => {
+ test('version N shows the whole file with the edits as additions', () => {
const doc = new Y.Doc();
const text = doc.getText('source');
const { origin, um } = makeUMPair(doc, text);
+ doc.transact(() => text.insert(0, 'new line\n'), origin);
- doc.transact(() => {
- text.insert(0, 'new line\n');
- }, origin);
-
- const stackItem = um.undoStack[0];
- const diff = synthesizeStackItemDiffText(stackItem, text, 'doc.md');
-
+ // biome-ignore lint/suspicious/noExplicitAny: Y.StackItem is internal to yjs
+ const diff = synthesizeVersionDiffText(um.undoStack as any, 1, text, 'doc.md');
expect(diff).toContain('+');
expect(diff).toContain('new line');
});
+
+ test('is cumulative: each version shows the whole file as of that version', () => {
+ const doc = new Y.Doc();
+ const text = doc.getText('source');
+ const { origin, um } = makeUMPair(doc, text);
+
+ doc.transact(() => text.insert(0, 'one\n'), origin);
+ um.stopCapturing();
+ doc.transact(() => text.insert(text.length, 'two\n'), origin);
+ um.stopCapturing();
+ doc.transact(() => text.insert(text.length, 'three\n'), origin);
+ expect(um.undoStack.length).toBe(3);
+
+ // Version 1: whole file at edit 1 = just "one" (no later lines).
+ // biome-ignore lint/suspicious/noExplicitAny: Y.StackItem is internal to yjs
+ const v1 = synthesizeVersionDiffText(um.undoStack as any, 1, text, 'doc.md');
+ expect(v1).toContain('+one');
+ expect(v1).not.toContain('two');
+ expect(v1).not.toContain('three');
+
+ // Version 2: whole file at edit 2 = "one" + "two", not "three".
+ // biome-ignore lint/suspicious/noExplicitAny: Y.StackItem is internal to yjs
+ const v2 = synthesizeVersionDiffText(um.undoStack as any, 2, text, 'doc.md');
+ expect(v2).toContain('+one');
+ expect(v2).toContain('+two');
+ expect(v2).not.toContain('three');
+
+ // Version 3 (now): the whole current document.
+ // biome-ignore lint/suspicious/noExplicitAny: Y.StackItem is internal to yjs
+ const v3 = synthesizeVersionDiffText(um.undoStack as any, 3, text, 'doc.md');
+ expect(v3).toContain('+one');
+ expect(v3).toContain('+two');
+ expect(v3).toContain('+three');
+ });
+});
+
+describe('synthesizeVersionDiff (bodies for the WYSIWYG diff)', () => {
+ test('returns frontmatter-stripped before/after bodies alongside the diff', () => {
+ const doc = new Y.Doc();
+ const text = doc.getText('source');
+ const { origin, um } = makeUMPair(doc, text);
+ doc.transact(() => text.insert(0, '---\ntitle: T\n---\nbody line\n'), origin);
+
+ // biome-ignore lint/suspicious/noExplicitAny: Y.StackItem is internal to yjs
+ const v1 = synthesizeVersionDiff(um.undoStack as any, 1, text, 'doc.md');
+ // Frontmatter is stripped from the rendered bodies; body content remains.
+ expect(v1.after).toContain('body line');
+ expect(v1.after).not.toContain('title: T');
+ expect(v1.before).toBe('');
+ // Source `diff` still carries full content (unchanged behavior).
+ expect(v1.diff).toContain('body line');
+ });
+
+ test('version 0 → empty diff and equal (empty) bodies', () => {
+ const doc = new Y.Doc();
+ const text = doc.getText('source');
+ const { origin, um } = makeUMPair(doc, text);
+ doc.transact(() => text.insert(0, 'new line\n'), origin);
+
+ // biome-ignore lint/suspicious/noExplicitAny: Y.StackItem is internal to yjs
+ const v0 = synthesizeVersionDiff(um.undoStack as any, 0, text, 'doc.md');
+ expect(v0.diff).toBe('');
+ expect(v0.before).toBe(v0.after);
+ });
});
// ---------------------------------------------------------------------------
diff --git a/packages/server/src/agent-activity.ts b/packages/server/src/agent-activity.ts
index f8f29975a..8d336915d 100644
--- a/packages/server/src/agent-activity.ts
+++ b/packages/server/src/agent-activity.ts
@@ -19,10 +19,22 @@
* + `Item.right` — both are publicly typed in `node_modules/yjs/dist/src/**`
* and are the documented way to walk a Y.Text's Item chain.
*/
-import { AGENT_ICON_COLORS, colorFromSeed, iconFromClientName } from '@inkeep/open-knowledge-core';
+import {
+ AGENT_ICON_COLORS,
+ colorFromSeed,
+ iconFromClientName,
+ stripFrontmatter,
+} from '@inkeep/open-knowledge-core';
import { createPatch } from 'diff';
import type * as Y from 'yjs';
-import { ContentString, Item, iterateDeletedStructs } from 'yjs';
+import {
+ ContentString,
+ createID,
+ Item,
+ isDeleted,
+ iterateDeletedStructs,
+ mergeDeleteSets,
+} from 'yjs';
import type { AgentSessionManager } from './agent-sessions.ts';
// ------------------------------------------------------------------
@@ -172,19 +184,95 @@ export function synthesizeStackItemDiff(
}
/**
- * Produce a unified-diff string for a single StackItem using the `diff`
- * package's `createPatch` (±3 context lines). Returns an empty string when
- * `before === after` so callers can render a placeholder rather than an
- * empty hunk.
+ * Reconstruct the document body as it stood after the first `keptCount` bursts
+ * — i.e. with every burst at index >= `keptCount` rolled back. Walks the live
+ * Y.Text item chain and, treating those later bursts as "the future", excludes
+ * the text they inserted and restores the text they deleted. `keptCount === 0`
+ * yields the pre-agent original; `keptCount === undoStack.length` yields the
+ * current document.
+ *
+ * Point-in-time reconstruction is what lets the undo timeline scrub: sliding to
+ * edit K shows the file as it actually was at edit K, not edit K's change
+ * highlighted inside today's document.
+ *
+ * Tombstone content is readable because `Y.UndoManager.keepItem` is set at
+ * capture for every StackItem still on the stack (all of which we read here).
*/
-export function synthesizeStackItemDiffText(
- stackItem: YjsStackItemShape,
+function reconstructStateAsOf(
+ undoStack: YjsStackItemShape[],
+ keptCount: number,
+ ytext: Y.Text,
+): string {
+ // Merge the insert/delete ranges of every "future" burst (index >= keptCount)
+ // into two DeleteSets. Classification is by clock ID range, NOT Item identity:
+ // yjs merges adjacent same-client items (even across bursts), so the live item
+ // chain no longer maps 1:1 to the Items a StackItem referenced — a merged item
+ // can straddle a burst boundary. Per-character clock lookup handles that split.
+ const future = undoStack.slice(keptCount);
+ const futureInserts = mergeDeleteSets(
+ future.map((s) => s.insertions) as unknown as Parameters<typeof mergeDeleteSets>[0],
+ );
+ const futureDeletes = mergeDeleteSets(
+ future.map((s) => s.deletions) as unknown as Parameters<typeof mergeDeleteSets>[0],
+ );
+
+ let out = '';
+ for (const item of walkYTextItems(ytext)) {
+ if (!(item.content instanceof ContentString)) continue;
+ const str = item.content.str;
+ const { client, clock } = item.id;
+ for (let j = 0; j < str.length; j++) {
+ const id = createID(client, clock + j);
+ // Present at this point iff a later burst did not insert this char, and it
+ // is either still live or was only deleted by a later burst.
+ const insertedLater = isDeleted(futureInserts, id);
+ const deletedLater = isDeleted(futureDeletes, id);
+ if (!insertedLater && (!item.deleted || deletedLater)) out += str[j];
+ }
+ }
+ return out;
+}
+
+/**
+ * Produce a whole-page unified-diff string for a file *version* — the document
+ * with the first `keptCount` edits applied (`after`) vs. the pre-agent original
+ * (`before`), both point-in-time (see `reconstructStateAsOf`). So version 0 is
+ * the empty/original file (empty diff), and version N (all edits) is the whole
+ * current document. This is what the undo timeline scrubs: each stop shows the
+ * entire file as it stood at that version, not one edit's isolated change.
+ *
+ * Returns an empty string when `before === after` (e.g. version 0, or a
+ * frontmatter-only edit) so callers can render a placeholder. Whole-file context
+ * so `AgentDiffPane` shows the entire page (mirrors `computeTimelineDiff`).
+ */
+export function synthesizeVersionDiff(
+ undoStack: YjsStackItemShape[],
+ keptCount: number,
+ ytext: Y.Text,
+ docName: string,
+): { diff: string; before: string; after: string } {
+ const beforeRaw = reconstructStateAsOf(undoStack, 0, ytext);
+ const afterRaw = reconstructStateAsOf(undoStack, keptCount, ytext);
+ const diff =
+ beforeRaw === afterRaw
+ ? ''
+ : createPatch(docName, beforeRaw, afterRaw, undefined, undefined, {
+ context: Math.max(beforeRaw.split('\n').length, afterRaw.split('\n').length),
+ });
+ // Frontmatter-stripped bodies for the client's WYSIWYG diff — parity with the
+ // Timeline path (`useTimelineEntryDiff`), which strips before rendering. The
+ // unified `diff` above keeps full content, so Source mode is unchanged.
+ return { diff, before: stripFrontmatter(beforeRaw).body, after: stripFrontmatter(afterRaw).body };
+}
+
+/** Back-compat: the unified-diff string alone (the pre-WYSIWYG callers + tests). */
+export function synthesizeVersionDiffText(
+ undoStack: YjsStackItemShape[],
+ keptCount: number,
ytext: Y.Text,
docName: string,
): string {
- const { before, after } = synthesizeStackItemDiff(stackItem, ytext);
- if (before === after) return '';
- return createPatch(docName, before, after, undefined, undefined, { context: 3 });
+ return synthesizeVersionDiff(undoStack, keptCount, ytext, docName).diff;
}
// ------------------------------------------------------------------
diff --git a/packages/server/src/agent-sessions.test.ts b/packages/server/src/agent-sessions.test.ts
index 6eea4ed45..711bc185b 100644
--- a/packages/server/src/agent-sessions.test.ts
+++ b/packages/server/src/agent-sessions.test.ts
@@ -409,6 +409,47 @@ describe('applyAgentUndo — scope drain semantics (V0-14)', () => {
expect(session.um.undoStack.length).toBe(1);
});
+ test("scope='count' pops the N newest frames and keeps the rest", async () => {
+ const session = await manager.getSession('doc-count.md', 'agent-count');
+ const ytext = session.dc.document.getText('source');
+
+ // Four separate frames (a, b, c, d) — oldest → newest.
+ for (const ch of ['a', 'b', 'c', 'd']) {
+ session.dc.document.transact(() => ytext.insert(0, ch), session.origin);
+ session.um.stopCapturing();
+ }
+ expect(session.um.undoStack.length).toBe(4);
+
+ // Drop the 2 newest (keep the 2 oldest) in one atomic call.
+ const undone = applyAgentUndo(session, 'count', undefined, 2);
+ expect(undone).toBe(true);
+ expect(session.um.undoStack.length).toBe(2);
+ });
+
+ test("scope='count' clamps an over-large count to a full drain", async () => {
+ const session = await manager.getSession('doc-count-clamp.md', 'agent-count-clamp');
+ const ytext = session.dc.document.getText('source');
+
+ session.dc.document.transact(() => ytext.insert(0, 'x'), session.origin);
+ session.um.stopCapturing();
+ session.dc.document.transact(() => ytext.insert(0, 'y'), session.origin);
+ expect(session.um.undoStack.length).toBe(2);
+
+ // count larger than the stack → drains everything, no error.
+ expect(applyAgentUndo(session, 'count', undefined, 99)).toBe(true);
+ expect(session.um.undoStack.length).toBe(0);
+ });
+
+ test("scope='count' with a non-positive count is a no-op", async () => {
+ const session = await manager.getSession('doc-count-zero.md', 'agent-count-zero');
+ const ytext = session.dc.document.getText('source');
+ session.dc.document.transact(() => ytext.insert(0, 'z'), session.origin);
+ expect(session.um.undoStack.length).toBe(1);
+
+ expect(applyAgentUndo(session, 'count', undefined, 0)).toBe(false);
+ expect(session.um.undoStack.length).toBe(1);
+ });
+
test("scope='session' returns false on an empty stack (no-op)", async () => {
const session = await manager.getSession('doc-empty.md', 'agent-empty');
expect(session.um.undoStack.length).toBe(0);
diff --git a/packages/server/src/agent-sessions.ts b/packages/server/src/agent-sessions.ts
index 835a1e164..28bdfdb3f 100644
--- a/packages/server/src/agent-sessions.ts
+++ b/packages/server/src/agent-sessions.ts
@@ -383,6 +383,8 @@ function applyAgentMarkdownWriteInner(
*
* scope 'last': undo one UM stack item.
* scope 'session': undo entire UM stack.
+ * scope 'count': undo the `count` newest UM stack items (clamped to depth) —
+ * the scoped "undo to edit N" range. `count` is required for this scope.
*
* Returns `true` when at least one UM frame was popped (i.e., the undo had
* an observable effect), `false` when the stack was already empty. Callers
@@ -418,7 +420,7 @@ function applyAgentMarkdownWriteInner(
*/
export function applyAgentUndo(
session: SessionRecord,
- scope: 'last' | 'session',
+ scope: 'last' | 'session' | 'count',
/**
* Embed-resolver context for `mdManager.parseWithFallback` — same shape
* `applyAgentMarkdownWrite` accepts. Required for parity: the post-undo
@@ -431,6 +433,8 @@ export function applyAgentUndo(
resolveEmbed: (basename: string, sourcePath: string) => string | null;
sourcePath: string;
},
+ /** Frames to pop when `scope === 'count'` (clamped to stack depth). */
+ count?: number,
): boolean {
// Conflict-aware write gate — symmetric with `applyAgentMarkdownWrite`.
// Undo is also a mutation: it pops a UM frame and rewrites Y.Text. The
@@ -450,7 +454,7 @@ export function applyAgentUndo(
},
},
() => {
- const undone = applyAgentUndoInner(session, scope, embedResolver);
+ const undone = applyAgentUndoInner(session, scope, embedResolver, count);
setActiveSpanAttributes({ 'agent.undo_effective': undone });
return undone;
},
@@ -459,31 +463,36 @@ export function applyAgentUndo(
function applyAgentUndoInner(
session: SessionRecord,
- scope: 'last' | 'session',
+ scope: 'last' | 'session' | 'count',
embedResolver?: {
resolveEmbed: (basename: string, sourcePath: string) => string | null;
sourcePath: string;
},
+ count?: number,
): boolean {
const { dc, um, undoOrigin } = session;
const document = dc.document;
+ // 'count' pops the N newest frames — clamp to the live depth so an
+ // over-large request (the timeline's list can lag a just-landed burst) is a
+ // full drain, not an error. A non-positive count is a no-op.
+ const framesToPop =
+ scope === 'last'
+ ? 1
+ : scope === 'count'
+ ? Math.min(Math.max(0, count ?? 0), um.undoStack.length)
+ : um.undoStack.length;
+
let undone = false;
// Wrap undo + composition in one outer transact under undoOrigin.
// Y.js merges um.undo()'s nested transact into this outer → fires under undoOrigin.
// isPairedWriteOrigin(undoOrigin) === true → Observer A/B short-circuit on settle.
document.transact(() => {
- if (scope === 'last') {
- if (um.undoStack.length === 0) return;
+ for (let i = 0; i < framesToPop && um.undoStack.length > 0; i++) {
um.undo();
undone = true;
- } else {
- while (um.undoStack.length > 0) {
- um.undo();
- undone = true;
- }
}
- deriveFragmentFromYtext(document, embedResolver);
+ if (undone) deriveFragmentFromYtext(document, embedResolver);
}, undoOrigin);
return undone;
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 59058c720..286ce3f62 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -250,7 +250,7 @@ import { fileTypeFromBuffer } from 'file-type';
import { parse as parseYaml } from 'yaml';
import { z } from 'zod';
import { captureEffect } from './activity-log.ts';
-import { listAgentActivity, synthesizeStackItemDiffText } from './agent-activity.ts';
+import { listAgentActivity, synthesizeVersionDiff } from './agent-activity.ts';
import type { AgentFocusBroadcaster } from './agent-focus.ts';
import { type AgentPresenceBroadcaster, BROADCASTER_EVICTION_MS } from './agent-presence.ts';
import {
@@ -7269,9 +7269,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
/**
* POST /api/agent-undo — agent undo via per-session Y.UndoManager.
*
- * Body: { docName?: string, connectionId: string, scope?: 'last' | 'session' }
+ * Body: { docName?, connectionId, scope?: 'last' | 'session' | 'file' | 'count', count? }
* connectionId — the session's agentId (matches sessionManager key)
- * scope — 'last' undoes the top UM stack item; 'session' undoes all items.
+ * scope — 'last' undoes the top UM stack item; 'session'/'file' undoes all;
+ * 'count' pops the `count` newest items (scoped "undo to edit N").
*
* Fires applyAgentUndo under session.undoOrigin (paired: true) — Observer
* A/B short-circuit; XmlFragment-authoritative composition updates both CRDTs.
@@ -7306,9 +7307,19 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const { connectionId } = body;
- // 'file' scope is a thin alias for 'session' (all bursts on this file's session).
- const scope: 'last' | 'session' =
- body.scope === 'session' || body.scope === 'file' ? 'session' : 'last';
+ // 'file' scope is a thin alias for 'session' (all bursts on this file's
+ // session). 'count' pops the N newest frames — the undo-timeline's
+ // scoped "undo to edit N" range; `count` rides through to applyAgentUndo.
+ let scope: 'last' | 'session' | 'count';
+ let count: number | undefined;
+ if (body.scope === 'count') {
+ scope = 'count';
+ count = body.count;
+ } else if (body.scope === 'session' || body.scope === 'file') {
+ scope = 'session';
+ } else {
+ scope = 'last';
+ }
if (!sessionManager.hasSession(docName, connectionId)) {
errorResponse(
@@ -7351,6 +7362,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
options.resolveEmbed
? { resolveEmbed: options.resolveEmbed, sourcePath: docName }
: undefined,
+ count,
);
// Record attribution for the undo write so the shadow-repo L2 drain
// fans it out under this session's writer-id. Skip when the UM stack
@@ -7458,8 +7470,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
/**
- * GET /api/agent-burst-diff?agentId=<connId>&docName=<path>&stackIndex=<n>
- * Returns unified-diff text for one StackItem in a given session.
+ * GET /api/agent-burst-diff?agentId=<connId>&docName=<path>&keptCount=<n>
+ * Returns whole-page unified-diff text for a file *version* — the original
+ * (pre-agent) doc vs. the doc with the first `keptCount` edits applied. So
+ * keptCount 0 is the empty/original file and keptCount N is the current doc.
* Exempt from extractAgentIdentity — read-only, no CRDT mutation.
*/
const handleAgentBurstDiff = withValidation(
@@ -7469,7 +7483,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
const agentId = validateAgentId(url.searchParams.get('agentId'));
const rawDocName = url.searchParams.get('docName');
- const stackIndexStr = url.searchParams.get('stackIndex');
+ const keptCountStr = url.searchParams.get('keptCount');
if (agentId === null) {
errorResponse(
@@ -7506,19 +7520,19 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
return;
}
- if (!stackIndexStr || Number.isNaN(Number(stackIndexStr))) {
- errorResponse(res, 400, 'urn:ok:error:invalid-request', 'StackIndex must be a number.', {
+ if (!keptCountStr || Number.isNaN(Number(keptCountStr))) {
+ errorResponse(res, 400, 'urn:ok:error:invalid-request', 'keptCount must be a number.', {
handler: 'agent-burst-diff',
});
return;
}
- const stackIndex = Number(stackIndexStr);
- if (!Number.isInteger(stackIndex) || stackIndex < 0) {
+ const keptCount = Number(keptCountStr);
+ if (!Number.isInteger(keptCount) || keptCount < 0) {
errorResponse(
res,
400,
'urn:ok:error:invalid-request',
- 'stackIndex must be a non-negative integer.',
+ 'keptCount must be a non-negative integer.',
{ handler: 'agent-burst-diff' },
);
return;
@@ -7538,30 +7552,36 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
}
const um = session.um;
- if (stackIndex >= um.undoStack.length) {
+ // keptCount ranges 0 (original) .. undoStack.length (now, all edits).
+ if (keptCount > um.undoStack.length) {
errorResponse(
res,
404,
'urn:ok:error:not-found',
- `stackIndex ${stackIndex} out of range (stack has ${um.undoStack.length} items).`,
+ `keptCount ${keptCount} out of range (stack has ${um.undoStack.length} items).`,
{ handler: 'agent-burst-diff' },
);
return;
}
- // biome-ignore lint/suspicious/noExplicitAny: Y.StackItem is internal to yjs — structural shape matches YjsStackItemShape in agent-activity.ts
- const stackItem = um.undoStack[stackIndex] as any;
const ytext = session.dc.document.getText('source');
- const diff = synthesizeStackItemDiffText(stackItem, ytext, docName);
+ const { diff, before, after } = synthesizeVersionDiff(
+ // biome-ignore lint/suspicious/noExplicitAny: Y.StackItem is internal to yjs — structural shape matches YjsStackItemShape in agent-activity.ts
+ um.undoStack as any,
+ keptCount,
+ ytext,
+ docName,
+ );
// `generatedAt` is the server's wall clock at response time (used for
// client-side cache staleness). The StackItem's capture timestamp is
// already carried in `/api/agent-activity`'s `bursts[].ts` — no need
- // to duplicate it here.
+ // to duplicate it here. `before`/`after` are the frontmatter-stripped
+ // bodies for the client's WYSIWYG diff (Source mode uses `diff`).
successResponse(
res,
200,
AgentBurstDiffSuccessSchema,
- { diff, generatedAt: Date.now() },
+ { diff, before, after, generatedAt: Date.now() },
{ handler: 'agent-burst-diff' },
);
} catch (e) {
diff --git a/packages/server/src/rename-log.ts b/packages/server/src/rename-log.ts
index d3df5b663..abda1c2f9 100644
--- a/packages/server/src/rename-log.ts
+++ b/packages/server/src/rename-log.ts
@@ -900,6 +900,102 @@ export function batchCheckExistence(
});
}
+/**
+ * One-shot batched `git cat-file --batch-check` stream that resolves each
+ * `(sha, path)` probe to the blob OID of the object at `<sha>:<path>`. Same
+ * single-child-process + `OK_GIT_TIMEOUT_MS` contract as `batchCheckExistence`;
+ * returns `(string | null)[]` aligned with `probes` — the 40-hex blob OID when
+ * the path resolves in the commit's tree, `null` when it is missing.
+ *
+ * Two commits whose blob OID for the same doc is identical have byte-identical
+ * content (git content-addresses blobs), so callers can compare returned OIDs
+ * to detect a commit that did not change a document's bytes. On timeout or
+ * batch failure every probe resolves to `null` (the safe choice: a `null` makes
+ * the caller keep the entry rather than drop a live row).
+ */
+export function batchResolveBlobOids(
+ shadow: ShadowHandle,
+ probes: Array<{ sha: string; path: string }>,
+): Promise<Array<string | null>> {
+ if (probes.length === 0) return Promise.resolve([]);
+
+ const timeoutMs = parseGitTimeoutMs();
+
+ return new Promise<Array<string | null>>((resolvePromise) => {
+ const child = spawn(
+ 'git',
+ ['cat-file', '--batch-check', '--buffer'],
+ withHiddenWindowsConsole({
+ ...GIT_BATCH_CHECK_STDIO_OPTIONS,
+ env: { ...process.env, GIT_DIR: shadow.gitDir, GIT_WORK_TREE: shadow.workTree },
+ }),
+ );
+
+ const stdoutChunks: Buffer[] = [];
+ child.stdout.on('data', (chunk: Buffer) => stdoutChunks.push(chunk));
+
+ const allNull = (): Array<string | null> => probes.map(() => null);
+
+ let settled = false;
+ const settle = (result: Array<string | null>) => {
+ if (settled) return;
+ settled = true;
+ resolvePromise(result);
+ };
+
+ const timer = setTimeout(() => {
+ console.warn(
+ `[rename-log] WARN: batchResolveBlobOids timed out after ${timeoutMs}ms (${probes.length} probes); returning all-null`,
+ );
+ try {
+ child.kill('SIGKILL');
+ } catch {
+ // child may already be dead
+ }
+ settle(allNull());
+ }, timeoutMs);
+
+ child.on('error', (err) => {
+ clearTimeout(timer);
+ console.warn(`[rename-log] WARN: batchResolveBlobOids spawn error: ${err.message}`);
+ settle(allNull());
+ });
+
+ child.on('close', (code, signal) => {
+ clearTimeout(timer);
+ if ((code !== null && code !== 0) || (signal && !settled)) {
+ console.warn(
+ `[rename-log] WARN: batchResolveBlobOids exited code=${code} signal=${signal ?? 'none'}; returning all-null`,
+ );
+ settle(allNull());
+ return;
+ }
+ const stdout = Buffer.concat(stdoutChunks).toString('utf-8');
+ const lines = stdout.split('\n').filter((l) => l.length > 0);
+ // Present: `<oid> <type> <size>` (first token is the resolved blob OID).
+ // Missing: `<sha>:<path> missing`. Output order matches input order.
+ const result: Array<string | null> = probes.map((_, i) => {
+ const line = lines[i];
+ if (!line || line.endsWith(' missing')) return null;
+ const oid = line.slice(0, line.indexOf(' '));
+ return oid.length === 40 ? oid : null;
+ });
+ settle(result);
+ });
+
+ const stdin = probes.map((p) => `${p.sha}:${p.path}`).join('\n');
+ try {
+ child.stdin.end(`${stdin}\n`);
+ } catch (err) {
+ clearTimeout(timer);
+ console.warn(
+ `[rename-log] WARN: batchResolveBlobOids stdin write failed: ${(err as Error).message}`,
+ );
+ settle(allNull());
+ }
+ });
+}
+
/**
* Atomically rewrite `<shadowDir>/renames.jsonl` from the in-memory index.
* tmp+rename for POSIX atomicity. Empty index → file is truncated to zero
diff --git a/packages/server/src/timeline-query.test.ts b/packages/server/src/timeline-query.test.ts
index 49562ed54..21df0b9ce 100644
--- a/packages/server/src/timeline-query.test.ts
+++ b/packages/server/src/timeline-query.test.ts
@@ -477,6 +477,112 @@ describe('getDocumentHistory', () => {
});
});
+describe('getDocumentHistory — byte-identical no-op row filtering', () => {
+ // Distinct, strictly-increasing author dates so the newest-first sort is
+ // deterministic (git committer dates are 1-second-granular).
+ function dates() {
+ let t = Date.parse('2026-06-01T12:00:00.000Z');
+ return () => {
+ t += 1000;
+ return new Date(t).toISOString();
+ };
+ }
+
+ test('drops a fan-out commit whose doc blob is byte-identical to the adjacent-older version', async () => {
+ const { contentDir, shadow } = await setup();
+ const next = dates();
+
+ // Human writes V1 then V2 on their own WIP ref.
+ writeFileSync(resolve(contentDir, 'intro.md'), '# V1\n');
+ const h1 = await commitWip(shadow, human, 'content/docs', 'WIP: v1', 'main', {
+ date: next(),
+ });
+ writeFileSync(resolve(contentDir, 'intro.md'), '# V2\n');
+ const h2 = await commitWip(shadow, human, 'content/docs', 'WIP: v2', 'main', {
+ date: next(),
+ });
+
+ // A second writer commits WITHOUT changing intro.md. Its WIP ref is a
+ // separate chain (parentless first commit), so `buildWipTree` re-adds
+ // intro.md at the current bytes (V2) — the multi-writer fan-out that makes
+ // a byte-identical commit reach the timeline through the multi-ref merge.
+ const g1 = await commitWip(shadow, agent, 'content/docs', 'WIP: agent no-op', 'main', {
+ date: next(),
+ });
+
+ const result = await getDocumentHistory(shadow, { docName: 'intro' }, 'content/docs');
+ const shas = result.entries.map((e) => e.sha);
+
+ // The agent's commit changed nothing about intro (V2 === V2) → dropped.
+ expect(shas).not.toContain(g1);
+ // The real edits survive, newest-first.
+ expect(shas).toEqual([h2, h1]);
+ expect(result.total).toBe(2);
+ });
+
+ test('keeps a frontmatter-only edit (whole-file blob differs)', async () => {
+ const { contentDir, shadow } = await setup();
+ const next = dates();
+
+ writeFileSync(resolve(contentDir, 'intro.md'), '---\ntitle: A\n---\n# Body\n');
+ const h1 = await commitWip(shadow, human, 'content/docs', 'WIP: fm A', 'main', {
+ date: next(),
+ });
+ // Only the frontmatter changes; the body is identical. The blob still
+ // differs, so this is a real edit and must NOT be dropped.
+ writeFileSync(resolve(contentDir, 'intro.md'), '---\ntitle: B\n---\n# Body\n');
+ const h2 = await commitWip(shadow, human, 'content/docs', 'WIP: fm B', 'main', {
+ date: next(),
+ });
+
+ const result = await getDocumentHistory(shadow, { docName: 'intro' }, 'content/docs');
+ expect(result.entries.map((e) => e.sha)).toEqual([h2, h1]);
+ });
+
+ test('never drops a checkpoint even when its doc bytes are unchanged', async () => {
+ const { contentDir, shadow } = await setup();
+
+ writeFileSync(resolve(contentDir, 'intro.md'), '# V1\n');
+ const h1 = await commitWip(shadow, human, 'content/docs', 'WIP: v1');
+ // Checkpoint snapshots the same bytes → byte-identical to h1, but it is a
+ // restore-point landmark and must survive the no-op filter.
+ const { checkpointRef } = await saveVersion(shadow, 'content/docs', [human]);
+ const cp = checkpointRef.split('/').at(-1) as string;
+
+ const result = await getDocumentHistory(shadow, { docName: 'intro' }, 'content/docs');
+ const shas = result.entries.map((e) => e.sha);
+ expect(shas).toContain(cp);
+ expect(shas).toContain(h1);
+ expect(result.entries.find((e) => e.sha === cp)?.type).toBe('checkpoint');
+ });
+
+ test('a byte-identical upstream import loses to the authored row (keeps the author)', async () => {
+ const { contentDir, shadow } = await setup();
+
+ // An upstream import brings intro.md at content V; the reconcile commit that
+ // attributes the real author carries the SAME bytes. Both can share a
+ // one-second commit date, so "keep the oldest" would non-deterministically
+ // drop the author in favor of "Git (upstream)". Force the harder ordering:
+ // date the authored commit AFTER the import's real-now date so the import is
+ // the positionally-older row — the case the old keep-oldest rule got wrong.
+ writeFileSync(resolve(contentDir, 'intro.md'), '# V\n');
+ const imp = await commitUpstreamImport(shadow, 'content/docs', 'old', 'new', 'main');
+ const authored = await commitWip(shadow, human, 'content/docs', 'reconcile: intro', 'main', {
+ date: new Date(Date.now() + 60_000).toISOString(),
+ });
+
+ const result = await getDocumentHistory(shadow, { docName: 'intro' }, 'content/docs');
+ const shas = result.entries.map((e) => e.sha);
+
+ // The authored row survives the byte-identical tie; the mechanical import is
+ // the dropped duplicate — regardless of which sorted older. No `upstream`
+ // row remains to shadow the author.
+ expect(shas).toContain(authored);
+ expect(shas).not.toContain(imp);
+ expect(result.entries.map((e) => e.type)).not.toContain('upstream');
+ });
+});
+
describe('getDocumentHistory — rename-history mitigation (US-004)', () => {
afterEach(() => {
resetRenameLogIndexCache();
diff --git a/packages/server/src/timeline-query.ts b/packages/server/src/timeline-query.ts
index 0541b2e84..1af042530 100644
--- a/packages/server/src/timeline-query.ts
+++ b/packages/server/src/timeline-query.ts
@@ -28,6 +28,7 @@ import { managedArtifactTimelinePaths } from './managed-artifact-persistence.ts'
import {
type AncestorShaSetCache,
batchCheckExistence,
+ batchResolveBlobOids,
buildAncestorShaSet,
buildSeeds,
createAncestorShaSetCache,
@@ -311,6 +312,102 @@ async function filterEntriesByChain<E extends { sha: string }>(
return entries.filter((_, i) => keep.has(i));
}
+/**
+ * Drop timeline rows whose document blob is byte-identical to the adjacent-older
+ * visible version of the same document — commits that appear in the doc's
+ * history (they passed the git-log pathspec + OkActor filters) but did not
+ * change its bytes.
+ *
+ * `entries` is newest-first (the doc-timeline order used for `parentSha`). For
+ * each entry the doc blob OID is resolved by probing every chain step whose
+ * cycle bound the entry's SHA satisfies (reusing `predecessorAncestors`) and
+ * taking the first that resolves — the same path-resolution shape as
+ * `filterEntriesByChain`. Walking oldest→newest, a non-checkpoint entry is
+ * dropped when its OID equals the nearest older non-checkpoint entry's OID.
+ * Checkpoints are landmarks: never dropped, and skipped as the byte baseline
+ * (mirroring the `parentSha` walk). The oldest of a run of identical versions is
+ * kept — it is the commit that introduced that content — and a later revert back
+ * to earlier content is a real change (different from its immediate predecessor)
+ * so it survives.
+ *
+ * One exception overrides "keep the oldest": within a run of identical bytes an
+ * authored row always beats an `upstream` import row. The import is a mechanical
+ * re-encoding of content authored elsewhere, and it can share a one-second date
+ * with the reconcile commit that attributes the real author — so keeping the
+ * positionally-oldest would non-deterministically drop the author in favor of
+ * "Git (upstream)". The authored row is kept regardless of order.
+ *
+ * Unresolvable OIDs (`null` — a batch failure/timeout, or a path that no longer
+ * resolves) never trigger a drop: the entry is kept and does not update the
+ * baseline. Same single-child-process cost as the sibling filters.
+ */
+async function dropByteIdenticalRows(
+ shadow: ShadowHandle,
+ entries: ParsedEntry[],
+ chain: Array<{ path: string; renameCommit: string | null }>,
+ predecessorAncestors: Array<Set<string> | null>,
+ pathFor: (name: string) => string,
+): Promise<ParsedEntry[]> {
+ if (entries.length < 2 || chain.length === 0) return entries;
+
+ type Probe = { entryIdx: number; sha: string; path: string };
+ const probes: Probe[] = [];
+ for (let entryIdx = 0; entryIdx < entries.length; entryIdx++) {
+ // Checkpoints are never dropped and never serve as a baseline — skip them
+ // entirely so we don't spend probes resolving their blobs.
+ if (entries[entryIdx].type === 'checkpoint') continue;
+ for (let chainIdx = 0; chainIdx < chain.length; chainIdx++) {
+ const ancestors = predecessorAncestors[chainIdx];
+ if (ancestors !== null && !ancestors.has(entries[entryIdx].sha)) continue;
+ probes.push({ entryIdx, sha: entries[entryIdx].sha, path: pathFor(chain[chainIdx].path) });
+ }
+ }
+ if (probes.length === 0) return entries;
+
+ const resolved = await batchResolveBlobOids(
+ shadow,
+ probes.map((p) => ({ sha: p.sha, path: p.path })),
+ );
+
+ // First resolved OID per entry (probe order follows chain order, so the first
+ // non-null hit is the highest-priority path that exists in that entry's tree).
+ const oidByEntry: Array<string | null> = entries.map(() => null);
+ for (let i = 0; i < probes.length; i++) {
+ const idx = probes[i].entryIdx;
+ if (oidByEntry[idx] === null && resolved[i] !== null) oidByEntry[idx] = resolved[i];
+ }
+
+ const drop = new Set<number>();
+ let baselineOid: string | null = null;
+ let baselineIdx = -1;
+ for (let i = entries.length - 1; i >= 0; i--) {
+ if (entries[i].type === 'checkpoint') continue;
+ const oid = oidByEntry[i];
+ if (oid === null) continue; // unresolved: keep, and don't move the baseline
+ if (baselineOid !== null && oid === baselineOid) {
+ // Byte-identical to the retained baseline. Normally the newer row is the
+ // duplicate and is dropped. Exception: an `upstream` import row is a
+ // mechanical re-encoding of content authored elsewhere, so when an
+ // authored (non-`upstream`) row carries the same bytes it — not the
+ // import — is the meaningful version: drop the `upstream` baseline and
+ // promote this row instead. Position alone can't decide this: an import
+ // and its reconcile commit share a one-second-granular date, so their
+ // sort order is non-deterministic and would otherwise drop the author.
+ if (entries[i].type !== 'upstream' && entries[baselineIdx].type === 'upstream') {
+ drop.add(baselineIdx);
+ baselineIdx = i; // OID unchanged; the authored row becomes the baseline
+ } else {
+ drop.add(i);
+ }
+ continue;
+ }
+ baselineOid = oid;
+ baselineIdx = i;
+ }
+ if (drop.size === 0) return entries;
+ return entries.filter((_, i) => !drop.has(i));
+}
+
// ─── Main export ──────────────────────────────────────────────────────────────
/**
@@ -739,8 +836,12 @@ export async function getDocumentHistory(
// checkpoint commits declare `docs: []` and hit the `touchedNames.size
// === 0` early-return for the same reason.
let postFiltered = unique;
+ // Cycle-bound ancestor set per chain step (null = current name, unbounded).
+ // Hoisted so the byte-identity de-dup below reuses the same sets to resolve
+ // which historical path applies to each entry.
+ let filterAncestors: Array<Set<string> | null> = [];
if (unique.length > 0 && chain.length > 0) {
- const filterAncestors: Array<Set<string> | null> = await Promise.all(
+ filterAncestors = await Promise.all(
chain.map(async (step) => {
if (step.renameCommit === null) return null;
const seeds = await buildSeeds(shadow, step.renameCommit, branch, seedsCache);
@@ -772,6 +873,20 @@ export async function getDocumentHistory(
filtered = filtered.filter((e) => e.checkpoint?.kind !== 'auto-consolidation');
}
+ // Drop no-op rows: a WIP/upstream commit whose blob for this doc is
+ // byte-identical to the adjacent-older visible version didn't change the
+ // document — it is multi-writer fan-out noise (a commit built from the whole
+ // contentRoot that carries another writer's file) or an upstream import that
+ // touched other files. Both would otherwise render as a "No changes" row.
+ // Checkpoints are restore-point landmarks and are never dropped here (and,
+ // as with `parentSha`, they don't serve as the byte baseline). Gated on a
+ // single-doc query (`docPath`) so we know which blob to compare; the
+ // OkActor pre-filter already removed most fan-out noise, but imports that
+ // declare `docs: []` and any residual fan-out survive to here.
+ if (docPath && filtered.length > 1) {
+ filtered = await dropByteIdenticalRows(shadow, filtered, chain, filterAncestors, pathFor);
+ }
+
if (typeFilter.length > 0) {
filtered = filtered.filter((e) => typeFilter.includes(e.type));
}
@@ -784,8 +899,27 @@ export async function getDocumentHistory(
filtered = filtered.filter((e) => !matchesAuthor(e, excludeAuthorFilter));
}
+ // Assign `parentSha` as list-adjacency over the FULL sorted result (before
+ // pagination) so a page-edge row still gets the correct parent even though
+ // that parent row isn't in the returned slice. This is NOT `git <sha>^`:
+ // the timeline is a multi-ref merge, so the git parent is usually an
+ // unrelated writer's commit or a filtered checkpoint. The adjacent older
+ // VISIBLE entry is the "previous version a reader saw."
+ //
+ // Skip `checkpoint` entries as parents: they are restore-point landmarks,
+ // not edit history, and the Timeline panel filters them out of the rendered
+ // list — so a WIP row's parent must be the previous WIP/upstream version the
+ // user actually sees, not an interleaved checkpoint. Walk oldest→newest
+ // carrying the nearest older non-checkpoint SHA.
+ let prevNonCheckpointSha: string | null = null;
+ for (let i = filtered.length - 1; i >= 0; i--) {
+ filtered[i].parentSha = prevNonCheckpointSha;
+ if (filtered[i].type !== 'checkpoint') prevNonCheckpointSha = filtered[i].sha;
+ }
+
const total = filtered.length;
const page = filtered.slice(offset, offset + limit);
+
// Strip the internal `rawBody` before returning to API consumers.
const stripped: TimelineEntry[] = page.map(({ rawBody: _rawBody, ...rest }) => rest);
finishMetric(allStartRefs.length, unique.length);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5930e3d05..4fc14b4b1 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -362,6 +362,9 @@ importers:
'@dnd-kit/utilities':
specifier: ^3.2.2
version: 3.2.2([email protected])
+ '@fellow/prosemirror-recreate-transform':
+ specifier: ^1.2.3
+ version: 1.2.3
'@floating-ui/dom':
specifier: 1.7.6
version: 1.7.6
@@ -2297,6 +2300,10 @@ packages:
'@noble/hashes':
optional: true
+ '@fellow/[email protected]':
+ resolution: {integrity: sha512-LdvMirDXtZWNv2DSpUVh1L7OxV/8PopzCwL4XJdd8UW4MMXywlcnCUzOz2TuNTMoTNnbOPBQ2JJlaAG/hg6sdQ==}
+ engines: {node: '>=10.0.0'}
+
'@floating-ui/[email protected]':
resolution: {integrity: sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==}
@@ -7212,6 +7219,10 @@ packages:
resolution: {integrity: sha512-IayShXAgj/QMXgB0IWmKx+rOPuGMhqm5w6jvFxmVenXKIzRqTAAsbBPT3kWQeGANj3jGgvcvv4yK6SxqYmikgw==}
+ resolution: {integrity: sha512-vtcDfH3TOjP8UekytvnHH1o1P4FcUdt4eQ1Y+Abap1tk/OB2MWQvcwS2ClCd1zuIhc3JKOx6p3kod8Vfys3E+A==}
+ engines: {node: '>=0.3.1'}
+
resolution: {integrity: sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw==}
engines: {node: '>=0.3.1'}
@@ -10145,6 +10156,9 @@ packages:
resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==}
engines: {iojs: '>=1.0.0', node: '>=0.10.0'}
+ resolution: {integrity: sha512-ZNQpVnWsdLMTCcLZcUY9ZBhxWuj7/H13EM7NL2gvbAMBXfLeN3iOLi3TWT1+8Or7OTLYXRDCy7sTEStk3j4KBA==}
+
resolution: {integrity: sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==}
@@ -12451,6 +12465,13 @@ snapshots:
optionalDependencies:
'@noble/hashes': 2.2.0
+ '@fellow/[email protected]':
+ dependencies:
+ diff: 5.2.2
+ prosemirror-model: 1.25.4
+ prosemirror-transform: 1.12.0
+ rfc6902: 5.2.0
+
'@floating-ui/[email protected]':
dependencies:
'@floating-ui/utils': 0.2.11
@@ -17289,6 +17310,8 @@ snapshots:
+
@@ -21297,6 +21320,8 @@ snapshots:
+