Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(review): add native turn history and guarded file actions

new-Beginnerea89f43fe0f8
diff --git a/apps/desktop/electron/main/ipc/workspace-ipc.ts b/apps/desktop/electron/main/ipc/workspace-ipc.ts
index 0c4526614..c720b30d8 100644
--- a/apps/desktop/electron/main/ipc/workspace-ipc.ts
+++ b/apps/desktop/electron/main/ipc/workspace-ipc.ts
@@ -38,6 +38,7 @@ import {
readOpenableImage,
resolveRealOpenablePath,
} from "@pi-desktop/host-runtime";
+import { openReviewedFile } from "../reviewed-file-open";
import { openableMp4Path } from "../open-attachment-video";
import { isChatRefOutsideRoots, resolveChatFileRef } from "../chat-ref-resolve";
import { rebaseWorktreeRef, type WorktreeRefContext } from "../worktree-ref";
@@ -686,6 +687,16 @@ export function registerWorkspaceIpc({
}
return collectWorkspaceDiff(cwd);
});
+ for (const [channel, method] of [
+ [IPC.invoke.workspaceReviewTurns, "review.turns"],
+ [IPC.invoke.workspaceReviewChanges, "review.changes"],
+ [IPC.invoke.workspaceReviewContext, "review.context"],
+ ] as const) {
+ handle(channel, async (input: unknown) => {
+ if (!host) throw new Error("host unavailable");
+ return host.call(method, input);
+ });
+ }
handle(
IPC.invoke.workspaceReviewRollback,
async (input: { sessionId: string; snapshotId: string }) => {
@@ -694,6 +705,23 @@ export function registerWorkspaceIpc({
},
);
+ handle(IPC.invoke.workspaceReviewRollbackFile, async (input: unknown) => {
+ if (!host) throw new Error("host unavailable");
+ return host.call("review.rollbackFile", input);
+ });
+ handleWithEvent(IPC.invoke.workspaceReviewOpenFile, async (event, input: unknown) => {
+ assertMainWindowSender(event);
+ const owner = getHost();
+ if (!owner) throw new Error("host unavailable");
+ return openReviewedFile(input, {
+ target: (sessionId, snapshotId) => owner.call<{ path: string }>("review.fileTarget", { sessionId, snapshotId }),
+ isCurrent: () => getHost() === owner,
+ stripPrefix: stripWinLongPrefix,
+ openPath: path => shell.openPath(path),
+ reveal: path => shell.showItemInFolder(path),
+ });
+ });
+
handle(
IPC.invoke.statsGetTokenUsageHistory,
async (input?: { startDate?: number; endDate?: number; bucket?: string }) => {
diff --git a/apps/desktop/electron/main/reviewed-file-open.ts b/apps/desktop/electron/main/reviewed-file-open.ts
new file mode 100644
index 000000000..4520a69f6
--- /dev/null
+++ b/apps/desktop/electron/main/reviewed-file-open.ts
@@ -0,0 +1,34 @@
+import { realpath, stat } from "node:fs/promises";
+import { isAbsolute, resolve } from "node:path";
+
+/** Explicit reveal/open of one host-authenticated review snapshot, not a path grant. */
+export async function openReviewedFile(input: unknown, dependencies: {
+ target: (sessionId: string, snapshotId: string) => Promise<{ path: string }>;
+ isCurrent: () => boolean;
+ stripPrefix: (path: string) => string;
+ openPath: (path: string) => Promise<string>;
+ reveal: (path: string) => void;
+}): Promise<{ ok: true }> {
+ if (!input || typeof input !== "object") throw new Error("review file action required");
+ const value = input as Record<string, unknown>;
+ const { sessionId, snapshotId, action } = value;
+ if (typeof sessionId !== "string" || !sessionId || typeof snapshotId !== "string" || !snapshotId
+ || (action !== "external" && action !== "folder") || "path" in value) throw new Error("invalid review file action");
+ const target = await dependencies.target(sessionId, snapshotId);
+ if (!dependencies.isCurrent()) throw new Error("review host replaced");
+ if (!target || typeof target.path !== "string" || !isAbsolute(target.path)) throw new Error("invalid review file target");
+ const actual = await realpath(target.path);
+ const canonical = (path: string) => {
+ const normalized = resolve(dependencies.stripPrefix(path));
+ return process.platform === "win32" ? normalized.toLowerCase() : normalized;
+ };
+ if (canonical(actual) !== canonical(target.path) || !(await stat(actual)).isFile()) throw new Error("review file changed location or is unavailable");
+ if (!dependencies.isCurrent()) throw new Error("review host replaced");
+ const path = dependencies.stripPrefix(actual);
+ if (action === "folder") dependencies.reveal(path);
+ else {
+ const error = await dependencies.openPath(path);
+ if (error) throw new Error(error);
+ }
+ return { ok: true };
+}
diff --git a/apps/desktop/src/components/ContextMenu.tsx b/apps/desktop/src/components/ContextMenu.tsx
index fe69cef89..d2761d81b 100644
--- a/apps/desktop/src/components/ContextMenu.tsx
+++ b/apps/desktop/src/components/ContextMenu.tsx
@@ -29,7 +29,7 @@ import {
type ReactNode,
} from "react";
import { portalToBody } from "../lib/portal-visibility";
-import { IconChevronRight } from "./icons";
+import { IconCheck, IconChevronRight } from "./icons";
import {
placeContextMenu,
type ContextMenuPlacement,
@@ -42,6 +42,8 @@ type ContextMenuAction = {
id: string;
label: string;
icon?: ReactNode;
+ /** Opt-in toggle state, rendered as a trailing check. */
+ checked?: boolean;
disabled?: boolean;
/** Destructive item: error ink, and never adjacent to what it undoes. */
danger?: boolean;
@@ -64,6 +66,7 @@ export type ContextMenuRequest = {
* correctly unnamed; an unnamed *and* ambiguous menu is the caller's bug.
*/
label?: string;
+ density?: "compact";
items: ContextMenuItem[];
};
@@ -322,7 +325,7 @@ export function ContextMenu({
const frame = requestAnimationFrame(() => {
menuRef.current
?.querySelector<HTMLButtonElement>(
- '[role="menuitem"]:not(:disabled)',
+ '[data-context-menu-root-item]:not(:disabled)',
)
?.focus({ preventScroll: true });
});
@@ -359,7 +362,7 @@ export function ContextMenu({
return portalToBody(
<div
ref={menuRef}
- className={`context-menu${placement ? " is-open" : ""}`}
+ className={`context-menu${state.density === "compact" ? " is-compact" : ""}${placement ? " is-open" : ""}`}
role="menu"
aria-label={state.label}
onKeyDown={onMenuKeyDown}
@@ -384,7 +387,8 @@ export function ContextMenu({
<button
ref={submenuOpen ? submenuTriggerRef : undefined}
type="button"
- role="menuitem"
+ role={item.checked === undefined ? "menuitem" : "menuitemcheckbox"}
+ aria-checked={item.checked}
aria-haspopup={hasSubmenu ? "menu" : undefined}
aria-expanded={hasSubmenu ? submenuOpen : undefined}
className={`context-menu-item${item.danger ? " danger" : ""}${hasSubmenu ? " has-submenu" : ""}`}
@@ -422,6 +426,7 @@ export function ContextMenu({
</span>
) : null}
<span className="context-menu-label">{item.label}</span>
+ {item.checked !== undefined && <span className="context-menu-check" aria-hidden>{item.checked && <IconCheck size={14} />}</span>}
{hasSubmenu ? (
<span className="context-menu-submenu-chevron" aria-hidden>
<IconChevronRight size={14} />
@@ -430,6 +435,7 @@ export function ContextMenu({
</button>
{submenuOpen && item.submenu ? (
<ContextMenuSubmenu
+ compact={state.density === "compact"}
anchorRef={submenuTriggerRef}
menuRef={submenuRef}
label={item.label}
@@ -454,6 +460,7 @@ function ContextMenuSubmenu({
selection,
onClose,
onCloseSubmenu,
+ compact,
}: {
anchorRef: RefObject<HTMLButtonElement | null>;
menuRef: RefObject<HTMLDivElement | null>;
@@ -462,9 +469,9 @@ function ContextMenuSubmenu({
selection: string;
onClose: () => void;
onCloseSubmenu: () => void;
+ compact: boolean;
}) {
const [placement, setPlacement] = useState<ContextMenuPlacement | null>(null);
-
const measure = useCallback(() => {
const anchor = anchorRef.current?.getBoundingClientRect();
const menu = menuRef.current;
@@ -529,7 +536,7 @@ function ContextMenuSubmenu({
return portalToBody(
<div
ref={menuRef}
- className={`context-menu context-menu-submenu${placement ? " is-open" : ""}`}
+ className={`context-menu context-menu-submenu${compact ? " is-compact" : ""}${placement ? " is-open" : ""}`}
role="menu"
aria-label={label}
onKeyDown={onMenuKeyDown}
@@ -548,7 +555,8 @@ function ContextMenuSubmenu({
) : null}
<button
type="button"
- role="menuitem"
+ role={item.checked === undefined ? "menuitem" : "menuitemcheckbox"}
+ aria-checked={item.checked}
className={`context-menu-item${item.danger ? " danger" : ""}`}
data-context-menu-item={item.id}
data-context-menu-submenu-item
@@ -564,6 +572,7 @@ function ContextMenuSubmenu({
</span>
) : null}
<span className="context-menu-label">{item.label}</span>
+ {item.checked !== undefined && <span className="context-menu-check" aria-hidden>{item.checked && <IconCheck size={14} />}</span>}
</button>
</Fragment>
))}
diff --git a/apps/desktop/src/components/ReviewChangeCard.tsx b/apps/desktop/src/components/ReviewChangeCard.tsx
index 4a754c0ed..f4a501741 100644
--- a/apps/desktop/src/components/ReviewChangeCard.tsx
+++ b/apps/desktop/src/components/ReviewChangeCard.tsx
@@ -5,7 +5,11 @@ import type {
ReviewChange,
ReviewChangeStatus,
UiMessage,
+ ReviewContextLines,
+ ReviewContextResult,
} from "@pi-desktop/shared";
+import { api } from "../lib/api";
+import { numberedReviewHunks, reviewFilePathLabel } from "../lib/review-history";
import { reviewChangeFromMessage } from "../lib/workspace-review";
import { useAppStore } from "../stores/app-store";
import { useCopy } from "./Markdown";
@@ -20,7 +24,7 @@ const STATUS_MARKS: Record<ReviewChangeStatus, string> = {
deleted: "D",
};
-function reviewDiffText(change: ReviewChange): string {
+export function reviewDiffText(change: Pick<ReviewChange, "hunks">): string {
return change.hunks
.map((hunk) =>
[
@@ -33,7 +37,10 @@ function reviewDiffText(change: ReviewChange): string {
.join("\n");
}
-function DiffBody({ message, compact }: { message: UiMessage; compact: boolean }) {
+export function ReviewChangeDetails({ message, compact = false, contextLines = 3, sessionId, onChanged, numbered = false, actions = true }: {
+ message: UiMessage; compact?: boolean; contextLines?: ReviewContextLines;
+ sessionId?: string; onChanged?: () => void; numbered?: boolean; actions?: boolean;
+}) {
const { t } = useTranslation();
const change = reviewChangeFromMessage(message);
const localToolsAllowed = useChatSessionCapability("canUseLocalTools");
@@ -41,34 +48,57 @@ function DiffBody({ message, compact }: { message: UiMessage; compact: boolean }
const { copied, copy } = useCopy();
const [rollingBack, setRollingBack] = useState(false);
+ const [expanded, setExpanded] = useState<{ key: string; result?: ReviewContextResult; error?: boolean } | null>(null);
+ const contextKey = `${sessionId}:${change?.snapshotId}:${contextLines}`;
+ useEffect(() => {
+ if (!sessionId || !change) return;
+ let active = true;
+ api.workspaceReviewContext({ sessionId, snapshotId: change.snapshotId, context: contextLines })
+ .then(result => { if (active) setExpanded({ key: contextKey, result }); })
+ .catch(() => { if (active) setExpanded({ key: contextKey, error: true }); });
+ return () => { active = false; };
+ }, [sessionId, change?.snapshotId, contextLines, contextKey]);
if (!change) return null;
-
- const diffText = reviewDiffText(change);
+ const contextResult = expanded?.key === contextKey ? expanded : null;
+ const pending = !!sessionId && !contextResult;
+ const unavailable = contextResult?.result?.unavailable;
+ const displayChange = contextResult?.result && !unavailable
+ ? { ...change, hunks: contextResult.result.hunks, truncated: false } : change;
+ const hunks = numberedReviewHunks(displayChange.hunks);
+ const diffText = reviewDiffText(displayChange);
const runRollback = async () => {
if (!localToolsAllowed || !change.reversible || change.state === "rolledBack" || rollingBack) return;
setRollingBack(true);
// A conflict or an unavailable snapshot is already reported through the
// store's toast; this card owns the rollback action only.
- await rollback(message.id, change.snapshotId);
+ const result = await rollback(message.id, change.snapshotId);
+ if (result?.status === "rolledBack" || result?.status === "alreadyRolledBack") onChanged?.();
setRollingBack(false);
};
return (
<div className="review-change-card-body-content">
+ {pending && <div className="review-change-note" role="status">{t("panel.review.loadingHistory")}</div>}
+ {contextResult?.error && <div className="review-change-note" role="alert">{t("panel.review.contextError")}</div>}
+ {unavailable && (contextLines !== 3 || change.truncated) && <div className="review-change-note" role="status">{t(`panel.review.contextUnavailable.${unavailable}`)}</div>}
{change.binary ? (
<div className="review-change-note">{t("panel.review.binary")}</div>
- ) : change.truncated ? (
+ ) : displayChange.truncated ? (
<div className="review-change-note">{t("panel.review.tooLarge")}</div>
- ) : change.hunks.length > 0 ? (
+ ) : displayChange.hunks.length > 0 ? (
<div className="review-change-diff">
- {change.hunks.map((hunk, hunkIndex) => (
+ {hunks.map((hunk, hunkIndex) => (
<div className="diff-hunk" key={`${hunk.header}-${hunkIndex}`}>
<div className="diff-line hunk">
<span className="diff-line-text">{hunk.header}</span>
</div>
{hunk.lines.map((line, lineIndex) => (
<div className={cx("diff-line", line.type)} key={lineIndex}>
+ {numbered && <>
+ <span className="review-line-number" data-side="old" aria-label={line.oldLine === null ? undefined : t("panel.review.oldLine", { line: line.oldLine })}>{line.oldLine}</span>
+ <span className="review-line-number" data-side="new" aria-label={line.newLine === null ? undefined : t("panel.review.newLine", { line: line.newLine })}>{line.newLine}</span>
+ </>}
<span className="diff-line-sign" aria-hidden>
{line.type === "add" ? "+" : line.type === "del" ? "−" : " "}
</span>
@@ -82,7 +112,7 @@ function DiffBody({ message, compact }: { message: UiMessage; compact: boolean }
<div className="review-change-note">{t("panel.review.noLineDetails")}</div>
)}
- <div className={cx("review-change-card-actions", compact && "is-compact")}>
+ {actions && <div className={cx("review-change-card-actions", compact && "is-compact")}>
{change.state === "rolledBack" ? (
<span className="review-change-state is-rolled-back">
<IconCheck size={13} />
@@ -115,7 +145,7 @@ function DiffBody({ message, compact }: { message: UiMessage; compact: boolean }
{copied ? <IconCheck size={13} /> : <IconCopy size={13} />}
{copied ? t("chat.copied") : t("chat.copy")}
</button>
- </div>
+ </div>}
</div>
);
}
@@ -188,8 +218,8 @@ export const ReviewChangeCard = memo(function ReviewChangeCard({
>
{STATUS_MARKS[change.status]}
</span>
- <span className="review-change-card-path" title={change.path}>
- {change.path}
+ <span className="review-change-card-path" data-outside-path={reviewFilePathLabel(change.path) !== change.path || undefined} title={change.path}>
+ {reviewFilePathLabel(change.path)}
</span>
<span
className="review-change-card-counts diff-counts"
@@ -205,7 +235,7 @@ export const ReviewChangeCard = memo(function ReviewChangeCard({
</button>
{open ? (
<div className="review-change-card-body" id={detailsId}>
- <DiffBody message={message} compact={compact} />
+ <ReviewChangeDetails message={message} compact={compact} />
</div>
) : null}
</section>
diff --git a/apps/desktop/src/components/workpanel/ReviewFileActions.tsx b/apps/desktop/src/components/workpanel/ReviewFileActions.tsx
new file mode 100644
index 000000000..62ce0c75d
--- /dev/null
+++ b/apps/desktop/src/components/workpanel/ReviewFileActions.tsx
@@ -0,0 +1,68 @@
+import { useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type { ReviewContextLines } from "@pi-desktop/shared";
+import { api } from "../../lib/api";
+import type { ReviewFileGroup } from "../../lib/review-history";
+import { withReviewChangeState } from "../../lib/workspace-review";
+import { useAppStore } from "../../stores/app-store";
+import { useChatSessionCapability } from "../../hooks/use-chat-session-capability";
+import { useCopy } from "../Markdown";
+import { reviewDiffText } from "../ReviewChangeCard";
+import { Button, cx } from "../ui";
+import { IconCheck, IconCopy, IconSnapshot } from "../icons";
+
+export function ReviewFileActions({ file, sessionId, context, disabled, onChanged }: {
+ file: ReviewFileGroup; sessionId: string; context: ReviewContextLines; disabled: boolean; onChanged: () => void;
+}) {
+ const { t } = useTranslation();
+ const { copied, copy } = useCopy();
+ const localToolsAllowed = useChatSessionCapability("canUseLocalTools");
+ const running = useAppStore(state => state.isRunning);
+ const workspace = useAppStore(state => state.workspace);
+ const [rollingBack, setRollingBack] = useState(false);
+ const latest = useRef({ file, context }); latest.current = { file, context };
+ const active = file.entries.filter(entry => entry.change.state !== "rolledBack");
+ const canRollback = active.length > 0 && active.every(entry => entry.change.reversible) && localToolsAllowed;
+ const current = () => useAppStore.getState().activeSessionId === sessionId && useAppStore.getState().workspace === workspace;
+ const rollback = async () => {
+ if (!current() || disabled || !canRollback || rollingBack || useAppStore.getState().isRunning) return;
+ setRollingBack(true);
+ try {
+ const result = await api.workspaceReviewRollbackFile({ sessionId, snapshotId: file.entries[0].change.snapshotId });
+ if (!current()) return;
+ if (result.status === "rolledBack" || result.status === "alreadyRolledBack") {
+ const ids = new Set(file.entries.map(entry => entry.change.snapshotId));
+ useAppStore.setState(state => ({ messages: state.messages.map(message => {
+ const row = file.entries.find(entry => entry.message.id === message.id);
+ return row && ids.has(row.change.snapshotId) ? withReviewChangeState(message, "rolledBack") : message;
+ }) }));
+ onChanged();
+ } else {
+ useAppStore.getState().showToast(t(result.status === "conflict" ? "panel.review.rollbackConflict" : "panel.review.rollbackUnavailable"), { variant: "warning" });
+ }
+ } catch {
+ if (current()) useAppStore.getState().showToast(t("panel.review.rollbackError"), { variant: "error" });
+ } finally { setRollingBack(false); }
+ };
+ const copyFile = async () => {
+ try {
+ const hunks = await Promise.all(file.entries.map(async ({ change }) => {
+ try {
+ const saved = await api.workspaceReviewContext({ sessionId, snapshotId: change.snapshotId, context });
+ return saved.unavailable ? change.hunks : saved.hunks;
+ } catch { return change.hunks; }
+ }));
+ if (!current() || latest.current.file !== file || latest.current.context !== context) return;
+ const text = reviewDiffText({ hunks: hunks.flat() });
+ await copy(text);
+ } catch {
+ if (current()) useAppStore.getState().showToast(t("panel.review.contextError"), { variant: "error" });
+ }
+ };
+ return <div className="review-change-card-actions is-compact">
+ {!active.length ? <span className="review-change-state is-rolled-back"><IconCheck size={13} />{t("panel.review.rolledBack")}</span>
+ : canRollback ? <Button variant="ghost" size="sm" className="review-change-rollback" disabled={disabled || rollingBack || running} onClick={() => void rollback()}><IconSnapshot size={13} />{t(rollingBack ? "panel.review.rollingBack" : "panel.review.rollback")}</Button>
+ : <span className="review-change-rollback-note">{t("panel.review.rollbackUnavailable")}</span>}
+ <Button variant="ghost" size="sm" className={cx("review-change-copy", copied && "copied")} disabled={disabled || !file.entries.some(entry => entry.change.hunks.length)} title={t("chat.copy")} onClick={() => void copyFile()}>{copied ? <IconCheck size={13} /> : <IconCopy size={13} />}{t(copied ? "chat.copied" : "chat.copy")}</Button>
+ </div>;
+}
diff --git a/apps/desktop/src/components/workpanel/ReviewHistoryFile.tsx b/apps/desktop/src/components/workpanel/ReviewHistoryFile.tsx
new file mode 100644
index 000000000..45939d79a
--- /dev/null
+++ b/apps/desktop/src/components/workpanel/ReviewHistoryFile.tsx
@@ -0,0 +1,45 @@
+import { useEffect, useId, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type { ReviewContextLines } from "@pi-desktop/shared";
+import { reviewFilePathLabel, type ReviewFileGroup } from "../../lib/review-history";
+import { ReviewChangeDetails } from "../ReviewChangeCard";
+import { Button, TooltipButton, cx } from "../ui";
+import { ContextMenu, useContextMenu } from "../ContextMenu";
+import { useReviewFileOpen } from "../../hooks/use-review-file-open";
+import { IconChevronRight, IconMore } from "../icons";
+import { ReviewFileActions } from "./ReviewFileActions";
+
+export function ReviewHistoryFile({ file, sessionId, context, focusSeq, focusSnapshots, expandFocus, disabled, onChanged }: {
+ file: ReviewFileGroup; sessionId: string; context: ReviewContextLines;
+ focusSeq?: number; focusSnapshots?: readonly string[]; expandFocus?: boolean;
+ disabled: boolean; onChanged: () => void;
+}) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const detailsId = useId();
+ const menu = useContextMenu();
+ const { canOpenInternal, canOpenFile, openFile, outside } = useReviewFileOpen(file, sessionId);
+ useEffect(() => {
+ if (focusSeq && expandFocus && file.entries.some(entry => focusSnapshots?.includes(entry.change.snapshotId))) setOpen(true);
+ }, [focusSeq, expandFocus, file, focusSnapshots]);
+ return <section className={cx("review-history-file", open && "open")} data-review-snapshots={file.entries.map(entry => entry.change.snapshotId).join(" ")}>
+ <div className="review-history-file-heading">
+ <Button variant="ghost" className="review-history-file-header" aria-expanded={open} aria-controls={detailsId} disabled={disabled} title={/^(?:[a-z]:[\\/]|[\\/])/i.test(file.path) || !file.root ? file.path : `${file.root}/${file.path}`} onClick={() => setOpen(value => !value)}>
+ <IconChevronRight size={11} /><span className="review-change-card-path" data-outside-path={reviewFilePathLabel(file.path) !== file.path || undefined}>{reviewFilePathLabel(file.path)}</span>
+ <span className="diff-counts"><span className="diff-count-add">+{file.additions}</span><span className="diff-count-del">−{file.deletions}</span></span>
+ </Button>
+ <TooltipButton className="icon-btn review-file-menu-button" tooltip={t("panel.review.fileActions")} disabled={disabled} aria-haspopup="menu" aria-expanded={!!menu.contextMenu} onClick={event => menu.openContextMenu(event, { label: t("panel.review.fileActions"), density: "compact", items: [
+ ...(!outside ? [{ id: "review-open-internal", label: t("panel.review.openInternal"), disabled: !canOpenInternal, onSelect: () => void openFile("internal") }] : []),
+ { id: "review-open-external", label: t("panel.review.openExternal"), disabled: !canOpenFile, onSelect: () => void openFile("external") },
+ { id: "review-open-folder", label: t("panel.review.openFolder"), disabled: !canOpenFile, onSelect: () => void openFile("folder") },
+ ] })}><IconMore size={14} /></TooltipButton>
+ </div>
+ <ContextMenu state={menu.contextMenu} onClose={menu.closeContextMenu} />
+ {open && <div className="review-history-file-body" id={detailsId}>
+ {file.entries.map(entry => <div className="review-history-record" key={entry.change.snapshotId} data-snapshot-id={entry.change.snapshotId}>
+ <ReviewChangeDetails message={entry.message} compact numbered actions={false} sessionId={sessionId} contextLines={context} />
+ </div>)}
+ <ReviewFileActions file={file} sessionId={sessionId} context={context} disabled={disabled} onChanged={onChanged} />
+ </div>}
+ </section>;
+}
diff --git a/apps/desktop/src/components/workpanel/ReviewHistoryPanel.tsx b/apps/desktop/src/components/workpanel/ReviewHistoryPanel.tsx
new file mode 100644
index 000000000..0bc62dd84
--- /dev/null
+++ b/apps/desktop/src/components/workpanel/ReviewHistoryPanel.tsx
@@ -0,0 +1,96 @@
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type { ReviewChangesPage, ReviewContextLines, ReviewTurnsPage } from "@pi-desktop/shared";
+import { api } from "../../lib/api";
+import { groupReviewFiles, readReviewPages } from "../../lib/review-history";
+import { useReviewFocusRequest } from "../../lib/review-focus-request";
+import { readReviewContextLines, rememberReviewContextLines } from "../../lib/review-preferences";
+import { useAppStore } from "../../stores/app-store";
+import { Button, Select } from "../ui";
+import { ReviewHistoryFile } from "./ReviewHistoryFile";
+import { ReviewHistoryToolbar } from "./ReviewHistoryToolbar";
+
+type Selection = { turnId?: string; snapshotId?: string; focusSeq?: number };
+
+/** Browsing review history never replaces the chat's bounded message window. */
+export function ReviewHistoryPanel({ sessionId }: { sessionId: string }) {
+ const { t } = useTranslation();
+ const messages = useAppStore(state => state.messages);
+ const running = useAppStore(state => state.isRunning);
+ const focus = useReviewFocusRequest();
+ const [selection, setSelection] = useState<Selection>({});
+ const [catalog, setCatalog] = useState<ReviewTurnsPage>({ turns: [] });
+ const [result, setResult] = useState<ReviewChangesPage>({ turnId: null, changes: [] });
+ const [context, setContext] = useState<ReviewContextLines>(readReviewContextLines);
+ const [history, setHistory] = useState(false), [wrap, setWrap] = useState(true);
+ const [loading, setLoading] = useState(true), [error, setError] = useState(false);
+ const [reload, setReload] = useState(0), [paging, setPaging] = useState(false);
+ const generation = useRef(0), handledFocus = useRef(0), scroller = useRef<HTMLDivElement>(null);
+ // Review facts refresh independently of streamed text, including late delegates.
+ const revision = useMemo(() => messages.filter(message => message.role === "tool")
+ .map(message => `${message.id}:${message.toolStatus}:${JSON.stringify((message.toolResult as { details?: { review?: unknown } } | undefined)?.details?.review ?? null)}`).join("|"), [messages]);
+ useEffect(() => {
+ if (!focus || focus.seq === handledFocus.current || (focus.sessionId && focus.sessionId !== sessionId)) return;
+ handledFocus.current = focus.seq;
+ setHistory(true);
+ setSelection({ snapshotId: focus.snapshotIds[0], focusSeq: focus.seq });
+ }, [focus, sessionId]);
+ useEffect(() => {
+ let active = true;
+ const version = ++generation.current;
+ setLoading(true); setError(false); setPaging(false);
+ Promise.all([
+ api.workspaceReviewTurns({ sessionId, limit: 50 }),
+ readReviewPages(api.workspaceReviewChanges, { sessionId, turnId: selection.turnId, snapshotId: selection.snapshotId, limit: 50 }, () => active),
+ ]).then(([turns, changes]) => {
+ if (!active) return;
+ setCatalog(turns); setResult(changes); setLoading(false);
+ }).catch(() => { if (active) { setError(true); setLoading(false); } });
+ return () => { active = false; if (generation.current === version) generation.current++; };
+ }, [sessionId, selection, revision, running, reload]);
+ const files = useMemo(() => groupReviewFiles(result.changes), [result]);
+ useEffect(() => {
+ if (loading || !selection.snapshotId) return;
+ scroller.current?.querySelector<HTMLElement>(`[data-review-snapshots~="${CSS.escape(selection.snapshotId)}"]`)
+ ?.scrollIntoView({ block: "start" });
+ }, [files, loading, selection]);
+ const older = async () => {
+ if (catalog.nextBefore === undefined || paging) return;
+ const version = generation.current;
+ setPaging(true);
+ try {
+ const page = await api.workspaceReviewTurns({ sessionId, before: catalog.nextBefore, limit: 50 });
+ if (generation.current === version) setCatalog(current => ({
+ turns: [...current.turns, ...page.turns.filter(turn => !current.turns.some(old => old.id === turn.id))], nextBefore: page.nextBefore,
+ }));
+ } catch { if (generation.current === version) setError(true); }
+ finally { if (generation.current === version) setPaging(false); }
+ };
+ const selectedId = selection.turnId ?? (selection.snapshotId ? result.turnId ?? "" : "");
+ const count = files.reduce((sum, file) => sum + file.entries.length, 0);
+ return <div className={`review-tab review-history${wrap ? "" : " is-nowrap"}`} aria-busy={loading}>
+ <ReviewHistoryToolbar history={history} onHistory={value => {
+ setHistory(value); setSelection(value && result.turnId ? { turnId: result.turnId } : {});
+ }} count={count} additions={files.reduce((sum, file) => sum + file.additions, 0)}
+ deletions={files.reduce((sum, file) => sum + file.deletions, 0)} context={context} onContext={value => {
+ rememberReviewContextLines(value); setContext(value);
+ }} wrap={wrap} onWrap={() => setWrap(value => !value)} />
+ {history && <div className="review-history-selector">
+ <span className="review-history-label">{t("panel.review.historyTitle")}</span>
+ <Select className="review-select review-history-round-select" value={selectedId || result.turnId || ""} aria-label={t("panel.review.historyTitle")}
+ onChange={event => { setSelection({ turnId: event.target.value }); scroller.current?.scrollTo({ top: 0 }); }}>
+ {selectedId && !catalog.turns.some(turn => turn.id === selectedId) && <option value={selectedId}>{selectedId}</option>}
+ {catalog.turns.map(turn => <option key={turn.id} value={turn.id}>{new Date(turn.createdAt).toLocaleString()}</option>)}
+ </Select>
+ {catalog.nextBefore !== undefined && <Button size="sm" disabled={paging} onClick={() => void older()}>{t("panel.review.moreHistory")}</Button>}
+ </div>}
+ <div className="review-scroll" ref={scroller}>
+ {loading && <div className="review-change-note" role="status">{t("panel.review.loadingHistory")}</div>}
+ {error && <div className="review-change-note" role="alert">{t("panel.review.historyError")} <Button size="sm" onClick={() => setReload(value => value + 1)}>{t("panel.review.retryHistory")}</Button></div>}
+ {!loading && !error && !files.length && <div className="review-change-note">{t("panel.review.noChanges")}</div>}
+ {!error && files.map(file => <ReviewHistoryFile key={`${result.turnId}:${file.id}`} file={file} sessionId={sessionId} context={context}
+ focusSeq={selection.focusSeq} focusSnapshots={focus?.snapshotIds} expandFocus={focus?.expand}
+ disabled={loading} onChanged={() => setReload(value => value + 1)} />)}
+ </div>
+ </div>;
+}
diff --git a/apps/desktop/src/components/workpanel/ReviewHistoryToolbar.tsx b/apps/desktop/src/components/workpanel/ReviewHistoryToolbar.tsx
new file mode 100644
index 000000000..d33708491
--- /dev/null
+++ b/apps/desktop/src/components/workpanel/ReviewHistoryToolbar.tsx
@@ -0,0 +1,37 @@
+import type { ReviewContextLines } from "@pi-desktop/shared";
+import { useTranslation } from "react-i18next";
+import { ContextMenu, useContextMenu } from "../ContextMenu";
+import { Select, TooltipButton } from "../ui";
+import { IconMore } from "../icons";
+
+export function ReviewHistoryToolbar({ history, onHistory, count, additions, deletions, context, onContext, wrap, onWrap }: {
+ history: boolean; onHistory: (history: boolean) => void;
+ count: number; additions: number; deletions: number;
+ context: ReviewContextLines; onContext: (context: ReviewContextLines) => void;
+ wrap: boolean; onWrap: () => void;
+}) {
+ const { t } = useTranslation();
+ const settingsMenu = useContextMenu();
+ return <>
+ <div className="review-toolbar review-round-toolbar">
+ <Select className="review-select review-round-scope" aria-label={t("panel.review.reviewScope")} value={history ? "history" : "last"}
+ onChange={event => { settingsMenu.closeContextMenu(); onHistory(event.target.value === "history"); }}>
+ <option value="last">{t("panel.review.previousRound")}</option>
+ <option value="history">{t("panel.review.historyMode")}</option>
+ </Select>
+ <span className="review-summary">{t("panel.review.changes", { count })}</span>
+ <span className="diff-counts review-toolbar-counts" aria-label={t("chat.reviewChangeCounts", { additions, deletions })}>
+ <span className="diff-count-add">+{additions}</span><span className="diff-count-del">−{deletions}</span>
+ </span>
+ <TooltipButton className="icon-btn review-settings-button" tooltip={t("panel.review.reviewSettings")} aria-haspopup="menu" aria-expanded={!!settingsMenu.contextMenu} onClick={event => {
+ settingsMenu.openContextMenu(event, { label: t("panel.review.reviewSettings"), items: [
+ { id: "review-wrap", label: t("panel.review.wordWrap"), checked: wrap, onSelect: onWrap },
+ { id: "review-context", label: t("panel.review.contextDisplay"), submenu: ([1, 3, 5] as const).map(lines => ({
+ id: `review-context-${lines}`, label: t("panel.review.contextLineOption", { count: lines }), checked: context === lines, onSelect: () => onContext(lines),
+ })) },
+ ] });
+ }}><IconMore size={16} /></TooltipButton>
+ </div>
+ <ContextMenu state={settingsMenu.contextMenu} onClose={settingsMenu.closeContextMenu} />
+ </>;
+}
diff --git a/apps/desktop/src/components/workpanel/ReviewTab.tsx b/apps/desktop/src/components/workpanel/ReviewTab.tsx
index b7f5e7d82..aaae9f596 100644
--- a/apps/desktop/src/components/workpanel/ReviewTab.tsx
+++ b/apps/desktop/src/components/workpanel/ReviewTab.tsx
@@ -1,3 +1,4 @@
+import { ReviewHistoryPanel } from "./ReviewHistoryPanel";
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useReviewFocusRequest } from "../../lib/review-focus-request";
@@ -20,6 +21,14 @@ type AppliedFocus = {
};
export function ReviewTab() {
+ const sessionId = useAppStore(state => state.activeSessionId);
+ const session = useAppStore(state => state.sessions.find(item => item.id === sessionId));
+ return sessionId && !sessionId.startsWith("remote:") && !session?.remoteWorkspace && session?.source !== "pi-native"
+ ? <ReviewHistoryPanel key={sessionId} sessionId={sessionId} />
+ : <LegacyReviewTab />;
+}
+
+function LegacyReviewTab() {
const { t } = useTranslation();
const messages = useAppStore((state) => state.messages);
const entries = useMemo(() => reviewChangesFromMessages(messages), [messages]);
diff --git a/apps/desktop/src/features/chat/transcript/TurnChangesCard.tsx b/apps/desktop/src/features/chat/transcript/TurnChangesCard.tsx
index f36dbe019..398433453 100644
--- a/apps/desktop/src/features/chat/transcript/TurnChangesCard.tsx
+++ b/apps/desktop/src/features/chat/transcript/TurnChangesCard.tsx
@@ -2,6 +2,7 @@ import { memo, useMemo } from "react";
import { useTranslation } from "react-i18next";
import type { ReviewChangeStatus, UiMessage } from "@pi-desktop/shared";
import { cx } from "../../../components/ui";
+import { reviewFilePathLabel } from "../../../lib/review-history";
import { requestReviewFocus } from "../../../lib/review-focus-request";
import {
summarizeTurnChanges,
@@ -54,7 +55,7 @@ export const TurnChangesCard = memo(function TurnChangesCard({
const hidden = files.length - visible.length;
const openReview = (snapshotIds: readonly string[], expand: boolean) => {
- requestReviewFocus(snapshotIds, { expand });
+ requestReviewFocus(snapshotIds, { expand, sessionId: sessionId ?? undefined });
const tab = toolWorkPanelTab("review");
if (sessionId) openTabForSession(sessionId, tab);
else openTab(tab);
@@ -102,7 +103,7 @@ export const TurnChangesCard = memo(function TurnChangesCard({
<span className="turn-changes-mark" aria-hidden>
{STATUS_MARKS[file.status]}
</span>
- <span className="turn-changes-path">{file.path}</span>
+ <span className="turn-changes-path" data-outside-path={reviewFilePathLabel(file.path) !== file.path || undefined}>{reviewFilePathLabel(file.path)}</span>
<Counts additions={file.additions} deletions={file.deletions} />
</button>
</li>
diff --git a/apps/desktop/src/hooks/use-review-file-open.ts b/apps/desktop/src/hooks/use-review-file-open.ts
new file mode 100644
index 000000000..9bc52d408
--- /dev/null
+++ b/apps/desktop/src/hooks/use-review-file-open.ts
@@ -0,0 +1,59 @@
+import { useTranslation } from "react-i18next";
+import { api } from "../lib/api";
+import type { ReviewFileGroup } from "../lib/review-history";
+import { FILE_MANAGER_PLUGIN_TAB, fileManagerPluginTab, hasPluginView } from "../lib/work-panel-tabs";
+import { useAppStore } from "../stores/app-store";
+
+/** Review opens the current authorized file, never a historical snapshot export. */
+export function useReviewFileOpen(file: ReviewFileGroup, sessionId: string) {
+ const { t } = useTranslation();
+ const views = useAppStore(state => state.pluginViews);
+ const workspace = useAppStore(state => state.workspace);
+ // Legacy delegates without execution-root provenance cannot name a safe target.
+ const canOpenFile = !workspace?.remote && Boolean(file.root || !file.entries.some(entry => entry.message.parentToolCallId));
+ const outside = /^(?:[a-z]:[\\/]|[\\/])/i.test(file.path) || file.path.split(/[\\/]/).includes("..");
+ const canOpenInternal = !outside && canOpenFile && hasPluginView(views, FILE_MANAGER_PLUGIN_TAB);
+ const openFile = async (destination: "internal" | "external" | "folder") => {
+ const current = () => {
+ const state = useAppStore.getState();
+ return state.activeSessionId === sessionId && state.workspace === workspace;
+ };
+ if (!canOpenFile || !current()) return;
+ try {
+ if (destination === "internal" && (outside || !hasPluginView(useAppStore.getState().pluginViews, FILE_MANAGER_PLUGIN_TAB))) return;
+ if (outside && destination !== "internal") {
+ const snapshotId = file.entries.at(-1)?.change.snapshotId;
+ if (!snapshotId) throw new Error("Native review snapshot unavailable");
+ await api.workspaceReviewOpenFile({ sessionId, snapshotId, action: destination });
+ return;
+ }
+ const absolute = /^(?:[a-z]:[\\/]|[\\/])/i.test(file.path);
+ let ref = absolute || !file.root ? file.path : file.root.replace(/[\\/]+$/, "") + "/" + file.path;
+ // Normalize Windows captured spellings, without changing host authorization.
+ if (/^[a-z]:[\\/]/i.test(ref) || ref.startsWith("\\\\") || ref.startsWith("//?/")) {
+ ref = ref.replaceAll("\\", "/").replace(/^\/\/\?\/UNC\//i, "//").replace(/^\/\/\?\/(?=[a-z]:\/)/i, "");
+ }
+ const { match } = await api.fsResolveRef(ref, sessionId);
+ if (!current()) return;
+ // Review paths are exact identities, not chat shorthands. Never fall back
+ // to a same-named file when a historical file has been removed.
+ if (!match || !["exact-absolute", "exact-relative"].includes(match.matchedBy)) throw new Error("Review file unavailable");
+ if (destination === "external") {
+ await api.fsOpen(match.absolutePath, undefined, sessionId);
+ } else if (destination === "folder") {
+ await api.fsReveal(match.absolutePath, sessionId);
+ } else {
+ const loaded = await api.listPluginViews();
+ if (!current()) return;
+ const state = useAppStore.getState();
+ if (!hasPluginView(loaded, FILE_MANAGER_PLUGIN_TAB) || !hasPluginView(state.pluginViews, FILE_MANAGER_PLUGIN_TAB)) throw new Error("File manager unavailable");
+ const session = state.sessions.find(item => item.id === sessionId);
+ const location = match.root === "workspace" && match.projectRoot?.primary !== false && !session?.worktree ? match.relativePath : match.absolutePath;
+ state.openWorkPanelTab(fileManagerPluginTab(location));
+ }
+ } catch {
+ if (current()) useAppStore.getState().showToast(t("panel.review.openError"), { variant: "error" });
+ }
+ };
+ return { canOpenFile, canOpenInternal, openFile, outside };
+}
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index cc02ff60c..a13c7a332 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -1,3 +1,4 @@
+import type { ReviewContextLines, ReviewContextResult, ReviewTurnsPage, ReviewChangesPage } from "@pi-desktop/shared";
import { projectPlanHistory } from "./plan-history";
import { guardRemoteInvocation } from "./remote-ipc-safety";
import { isRemoteSession, safeSessionSummary } from "./remote-session-safety";
@@ -1608,6 +1609,16 @@ export const api = {
toggleDevTools: (open?: boolean) =>
invoke<{ open: boolean }>(IPC.invoke.devtoolsToggle, { open }),
workspaceDiff: (sessionId?: string) => invoke<WorkspaceDiff>(IPC.invoke.workspaceDiff, { ...(sessionId ? { sessionId } : {}) }),
+ workspaceReviewTurns: (input: { sessionId: string; before?: number; limit?: number }) =>
+ invoke<ReviewTurnsPage>(IPC.invoke.workspaceReviewTurns, input),
+ workspaceReviewChanges: (input: { sessionId: string; turnId?: string; snapshotId?: string; offset?: number; limit?: number }) =>
+ invoke<ReviewChangesPage>(IPC.invoke.workspaceReviewChanges, input),
+ workspaceReviewContext: (input: { sessionId: string; snapshotId: string; context: ReviewContextLines }) =>
+ invoke<ReviewContextResult>(IPC.invoke.workspaceReviewContext, input),
+ workspaceReviewOpenFile: (input: { sessionId: string; snapshotId: string; action: "external" | "folder" }) =>
+ invoke(IPC.invoke.workspaceReviewOpenFile, input),
+ workspaceReviewRollbackFile: (input: { sessionId: string; snapshotId: string }) =>
+ invoke<import("@pi-desktop/shared").ReviewFileRollbackResult>(IPC.invoke.workspaceReviewRollbackFile, input),
workspaceReviewRollback: (input: {
sessionId: string;
snapshotId: string;
diff --git a/apps/desktop/src/lib/remote-ipc-safety.ts b/apps/desktop/src/lib/remote-ipc-safety.ts
index 6fcae20ec..0ad338332 100644
--- a/apps/desktop/src/lib/remote-ipc-safety.ts
+++ b/apps/desktop/src/lib/remote-ipc-safety.ts
@@ -9,6 +9,8 @@ const localOnly = new Set<string>([
IPC.invoke.sessionGetScratchPath, IPC.invoke.sessionOpenScratchPath,
IPC.invoke.agentSteer, IPC.invoke.agentQueuePush, IPC.invoke.agentQueueList,
IPC.invoke.agentStopSubagents, IPC.invoke.workspaceReviewRollback,
+ IPC.invoke.workspaceReviewTurns, IPC.invoke.workspaceReviewChanges, IPC.invoke.workspaceReviewContext,
+ IPC.invoke.workspaceReviewOpenFile, IPC.invoke.workspaceReviewRollbackFile,
IPC.invoke.extensionsCommandRun, IPC.invoke.browserNavigate,
IPC.invoke.fsResolveRef,
]);
diff --git a/apps/desktop/src/lib/review-focus-request.ts b/apps/desktop/src/lib/review-focus-request.ts
index 0cdea569d..ffe79d011 100644
--- a/apps/desktop/src/lib/review-focus-request.ts
+++ b/apps/desktop/src/lib/review-focus-request.ts
@@ -10,6 +10,7 @@ import { useSyncExternalStore } from "react";
export type ReviewFocusRequest = {
/** Scrolled into view in order; the first one found becomes the anchor. */
snapshotIds: readonly string[];
+ sessionId?: string;
/** Open each named change's diff, or only reveal the rows. */
expand: boolean;
seq: number;
@@ -21,11 +22,11 @@ const listeners = new Set<() => void>();
export function requestReviewFocus(
snapshotIds: readonly string[],
- { expand }: { expand: boolean },
+ { expand, sessionId }: { expand: boolean; sessionId?: string },
): void {
if (snapshotIds.length === 0) return;
sequence += 1;
- current = { snapshotIds: [...snapshotIds], expand, seq: sequence };
+ current = { snapshotIds: [...snapshotIds], expand, seq: sequence, ...(sessionId ? { sessionId } : {}) };
for (const listener of listeners) listener();
}
diff --git a/apps/desktop/src/lib/review-history.ts b/apps/desktop/src/lib/review-history.ts
new file mode 100644
index 000000000..82f03d12f
--- /dev/null
+++ b/apps/desktop/src/lib/review-history.ts
@@ -0,0 +1,74 @@
+import type { DiffHunk, DiffLine, ReviewChangesPage, ReviewHistoryChange } from "@pi-desktop/shared";
+import { reviewChangeFromMessage, type ReviewChangeEntry } from "./workspace-review.ts";
+
+export type NumberedReviewLine = DiffLine & { oldLine: number | null; newLine: number | null };
+export function numberedReviewHunks(hunks: readonly DiffHunk[]): { header: string; lines: NumberedReviewLine[] }[] {
+ return hunks.map(hunk => {
+ const coordinates = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(hunk.header);
+ let old = Number(coordinates?.[1]), next = Number(coordinates?.[2]);
+ return { header: hunk.header, lines: hunk.lines.map(line => {
+ const marker = line.text === "\\ No newline at end of file";
+ const oldLine = coordinates && !marker && line.type !== "add" ? old++ : null;
+ const newLine = coordinates && !marker && line.type !== "del" ? next++ : null;
+ return { ...line, oldLine, newLine };
+ }) };
+ });
+}
+
+export type ReviewFileGroup = {
+ id: string; path: string; root?: string; entries: ReviewChangeEntry[];
+ additions: number; deletions: number;
+};
+
+/** Compact outside-root spellings for display only; keep snapshot paths intact. */
+export function reviewFilePathLabel(path: string): string {
+ const posix = path.replaceAll("\\", "/");
+ let outside = posix.startsWith("/") || /^[a-z]:\//i.test(posix);
+ let depth = 0;
+ for (const segment of posix.split("/")) {
+ if (segment === "..") { if (--depth < 0) outside = true; }
+ else if (segment && segment !== ".") depth++;
+ }
+ return outside ? `.../${posix.split("/").filter(Boolean).at(-1) ?? path}` : path;
+}
+
+/** Presentation grouping only: never changes snapshot identity or operation order. */
+export function groupReviewFiles(rows: readonly ReviewHistoryChange[]): ReviewFileGroup[] {
+ const groups = new Map<string, ReviewFileGroup>(), seen = new Set<string>();
+ for (const row of rows) {
+ const change = reviewChangeFromMessage(row.message);
+ if (!change || seen.has(change.snapshotId)) continue;
+ seen.add(change.snapshotId);
+ const root = row.root ?? change.root;
+ // Missing legacy worktree provenance must not collapse into the parent root.
+ const identity = root ?? (row.message.parentToolCallId ? `unknown:${row.message.parentToolCallId}` : "workspace");
+ const id = JSON.stringify([identity, change.path]);
+ let group = groups.get(id);
+ if (!group) {
+ group = { id, path: change.path, root, entries: [], additions: 0, deletions: 0 };
+ groups.set(id, group);
+ }
+ group.entries.push({ message: row.message, change });
+ group.additions += change.additions; group.deletions += change.deletions;
+ }
+ return [...groups.values()];
+}
+
+export type ReviewReadRequest = { sessionId: string; turnId?: string; snapshotId?: string; offset?: number; limit?: number };
+export async function readReviewPages(
+ read: (input: ReviewReadRequest) => Promise<ReviewChangesPage>,
+ input: ReviewReadRequest,
+ active: () => boolean,
+): Promise<ReviewChangesPage> {
+ let page = await read(input);
+ const changes = [...page.changes];
+ let offset = input.offset ?? 0;
+ while (true) {
+ if (!active()) throw new DOMException("Review selection changed", "AbortError");
+ if (page.nextOffset === undefined) return { turnId: page.turnId, changes };
+ if (!Number.isSafeInteger(page.nextOffset) || page.nextOffset <= offset) throw new Error("Invalid review cursor");
+ offset = page.nextOffset;
+ page = await read({ sessionId: input.sessionId, turnId: page.turnId ?? undefined, offset, limit: input.limit });
+ changes.push(...page.changes);
+ }
+}
diff --git a/apps/desktop/src/lib/review-preferences.ts b/apps/desktop/src/lib/review-preferences.ts
new file mode 100644
index 000000000..e4a09cac4
--- /dev/null
+++ b/apps/desktop/src/lib/review-preferences.ts
@@ -0,0 +1,22 @@
+import type { ReviewContextLines } from "@pi-desktop/shared";
+
+/** Profile-wide display preference, never session data or snapshot evidence. */
+export const REVIEW_CONTEXT_STORAGE_KEY = "pi.desktop.reviewContextLines";
+
+export function readReviewContextLines(): ReviewContextLines {
+ try {
+ const value = globalThis.localStorage?.getItem(REVIEW_CONTEXT_STORAGE_KEY);
+ return value === "1" ? 1 : value === "5" ? 5 : 3;
+ } catch {
+ // Missing, blocked or malformed preferences retain the default display.
+ return 3;
+ }
+}
+
+export function rememberReviewContextLines(lines: ReviewContextLines): void {
+ try {
+ globalThis.localStorage?.setItem(REVIEW_CONTEXT_STORAGE_KEY, String(lines));
+ } catch {
+ // Best-effort UI persistence must not prevent changing the current view.
+ }
+}
diff --git a/apps/desktop/src/lib/workspace-review.ts b/apps/desktop/src/lib/workspace-review.ts
index 60ea4beb9..fb70bae9c 100644
--- a/apps/desktop/src/lib/workspace-review.ts
+++ b/apps/desktop/src/lib/workspace-review.ts
@@ -89,7 +89,7 @@ export function reviewChangeFromMessage(message: UiMessage): ReviewChange | null
}
const details = toolResultDetails(message);
- if (details?.root !== "workspace") return null;
+ if (!details || !["workspace", "scratch", "external", "visualization"].includes(String(details.root))) return null;
const review = recordValue(details.review);
if (!review || review.version !== 1) return null;
@@ -131,6 +131,7 @@ export function reviewChangeFromMessage(message: UiMessage): ReviewChange | null
...(review.binary === true ? { binary: true } : {}),
...(review.truncated === true ? { truncated: true } : {}),
reversible: review.reversible === true,
+ ...(typeof review.root === "string" ? { root: review.root } : {}),
};
}
diff --git a/apps/desktop/src/styles/messages.css b/apps/desktop/src/styles/messages.css
index 2dc30dc58..e8a37f727 100644
--- a/apps/desktop/src/styles/messages.css
+++ b/apps/desktop/src/styles/messages.css
@@ -917,6 +917,14 @@
text-align: left;
}
+/* Keep the explicit outside-workspace prefix before the filename, even when
+ the normal path row uses RTL to preserve its basename on overflow. */
+.review-change-card-path[data-outside-path],
+.turn-changes-path[data-outside-path] {
+ direction: ltr;
+ unicode-bidi: isolate;
+}
+
.review-change-card-header:hover .review-change-card-path {
color: var(--ds-text-primary);
}
diff --git a/apps/desktop/src/styles/ui-kit.css b/apps/desktop/src/styles/ui-kit.css
index 4468a5978..ac7d85d15 100644
--- a/apps/desktop/src/styles/ui-kit.css
+++ b/apps/desktop/src/styles/ui-kit.css
@@ -280,6 +280,10 @@
visibility: visible;
}
+.context-menu.is-compact { min-width: 156px; padding: 4px; }
+.context-menu.is-compact .context-menu-item { min-height: 28px; padding: 4px 8px; font-size: var(--text-xs-plus); outline: none; }
+.context-menu.is-compact .context-menu-item:focus-visible { box-shadow: inset 0 0 0 1px var(--ds-border-default); }
+
.context-menu-item {
display: flex;
width: 100%;
@@ -348,6 +352,13 @@
text-overflow: ellipsis;
}
+.context-menu-check {
+ display: inline-flex;
+ flex: 0 0 14px;
+ margin-left: auto;
+ color: var(--ds-text-muted);
+}
+
.context-menu-separator {
height: 1px;
margin: 5px 6px;
diff --git a/apps/desktop/src/styles/work-panel.css b/apps/desktop/src/styles/work-panel.css
index 5e2a61a94..ce15aa2d1 100644
--- a/apps/desktop/src/styles/work-panel.css
+++ b/apps/desktop/src/styles/work-panel.css
@@ -906,3 +906,71 @@
max-height: 100%;
border-radius: var(--radius-sm);
}
+
+/* Round review has one vertical scroll owner, not nested diff viewports. */
+.review-round-toolbar { gap: 6px; }
+.review-select.review-round-scope { flex: 0 0 auto; width: auto; height: 24px; min-height: 24px; padding: 1px 8px; }
+/* Keep native selection behavior; only review opts into the CSS-styled picker. */
+.review-select {
+ appearance: base-select;
+ align-items: center;
+ height: 28px; min-height: 28px; gap: 12px;
+ font-size: var(--text-xs-plus);
+}
+.review-select::picker(select) {
+ appearance: base-select;
+ margin-block: 4px;
+ padding: 0;
+ border: 1px solid var(--ds-border-default);
+ border-radius: var(--radius-sm);
+ background: var(--ds-bg-sidebar);
+ color: var(--ds-text-primary);
+ box-shadow: var(--ds-shadow-dialog);
+ max-height: 320px;
+ overflow: auto;
+}
+.review-select option {
+ padding: 6px 10px;
+ gap: 12px;
+ border-radius: 0;
+ background: var(--ds-bg-sidebar);
+ color: var(--ds-text-primary);
+ font-size: var(--text-xs-plus);
+}
+.review-select option:first-child { border-start-start-radius: var(--radius-sm); border-start-end-radius: var(--radius-sm); }
+.review-select option:last-child { border-end-start-radius: var(--radius-sm); border-end-end-radius: var(--radius-sm); }
+.review-select option:hover,
+.review-select option:focus-visible {
+ background: color-mix(in oklab, var(--ds-bg-sidebar) 92%, var(--ds-text-primary));
+}
+.review-select option:checked {
+ background: color-mix(in oklab, var(--ds-bg-sidebar) 86%, var(--ds-text-primary));
+}
+.review-select option:focus-visible { outline: 1px solid var(--ds-text-muted); outline-offset: -1px; }
+.review-select option::checkmark { order: 1; margin-inline-start: auto; }
+.review-settings-button, .review-file-menu-button { flex: 0 0 24px; width: 24px; height: 24px; padding: 0; border: 0; border-radius: var(--radius-sm); background: transparent; }
+.review-history-selector { display: flex; flex: 0 0 auto; align-items: center; gap: 12px; padding: 4px 10px 10px; }
+.review-history-label { flex: 0 0 auto; white-space: nowrap; color: var(--ds-text-muted); font-size: var(--text-xs-plus); }
+.review-history-round-select { flex: 1; min-width: 0; padding: 3px 10px; }
+.review-history .review-scroll { overflow-y: auto; overflow-x: auto; scroll-padding-top: 36px; }
+.review-history-file { position: relative; min-width: 0; scroll-margin-top: 4px; }
+.review-history-file-heading { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 4px; background: var(--ds-bg-dock); }
+.review-history-file-header {
+ display: flex; align-items: center;
+ justify-content: flex-start; gap: 6px; flex: 1; min-width: 0;
+ padding: 5px 6px; border: 0; border-radius: var(--radius-sm); background: transparent;
+ color: var(--ds-text-primary); text-align: left; font-size: var(--text-xs-plus);
+}
+.review-history-file.open > .review-history-file-heading > .review-history-file-header > svg { transform: rotate(90deg); }
+.review-history-file-header > svg, .review-history-file-header .diff-counts { flex-shrink: 0; }
+.review-history-file-header .review-change-card-path { flex: 1; min-width: 0; }
+.review-history-file-body { margin: 2px 0 8px 6px; border-radius: var(--radius-sm); background: var(--ds-tile); }
+.review-history-record { min-width: 0; }
+.review-history .review-change-card-body-content { overflow: visible; max-height: none; }
+.review-line-number {
+ flex: 0 0 4ch; padding: 3px 4px; color: var(--ds-text-faint); text-align: right;
+ font-family: var(--font-mono); font-size: var(--text-2xs); user-select: none;
+}
+
+.review-history.is-nowrap .review-change-diff .diff-line { min-width: max-content; }
+.review-history.is-nowrap .diff-line-text { white-space: pre; overflow-wrap: normal; }
diff --git a/apps/desktop/test/chat-context-menu-surface.test.mjs b/apps/desktop/test/chat-context-menu-surface.test.mjs
index cc810e0de..18fa1c825 100644
--- a/apps/desktop/test/chat-context-menu-surface.test.mjs
+++ b/apps/desktop/test/chat-context-menu-surface.test.mjs
@@ -24,7 +24,7 @@ const assistantTurnSource = await readFile(
test("the pointer-anchored menu portals, measures, and closes without trapping focus", () => {
assert.match(menuSource, /portalToBody\(/);
assert.match(menuSource, /placeContextMenu\(/);
- assert.match(menuSource, /className=\{`context-menu\$\{placement \? " is-open" : ""\}`\}/);
+ assert.match(menuSource, /className=\{`context-menu[^\n]*\$\{placement \? " is-open" : ""\}`\}/);
assert.match(menuSource, /window\.addEventListener\("pointerdown", onOutside, true\)/);
assert.match(menuSource, /window\.addEventListener\("keydown", onKeyDown, true\)/);
assert.match(menuSource, /if \(event\.key === "Tab"\)/);
diff --git a/apps/desktop/test/chat-review-entry.test.mjs b/apps/desktop/test/chat-review-entry.test.mjs
index 0c325b322..450828dac 100644
--- a/apps/desktop/test/chat-review-entry.test.mjs
+++ b/apps/desktop/test/chat-review-entry.test.mjs
@@ -145,12 +145,12 @@ test("review evidence is read from the successful message, not Git", () => {
});
});
-test("failed and scratch tool rows cannot manufacture review evidence", () => {
+test("failed and unknown-root tool rows cannot manufacture review evidence", () => {
assert.equal(reviewChangeFromMessage(message({ toolStatus: "error" })), null);
assert.equal(
reviewChangeFromMessage(
message({
- toolResult: { details: { root: "scratch", review: baseReview } },
+ toolResult: { details: { root: "unknown", review: baseReview } },
}),
),
null,
@@ -163,6 +163,14 @@ test("failed and scratch tool rows cannot manufacture review evidence", () => {
);
});
+test("successful Write/Edit review evidence accepts every supported execution root", () => {
+ for (const root of ["workspace", "scratch", "external", "visualization"]) {
+ const path = root === "workspace" ? "src/a.ts" : "/outside/a.ts";
+ const row = message({ toolResult: { details: { root, review: { ...baseReview, path } } } });
+ assert.equal(reviewChangeFromMessage(row)?.path, path);
+ }
+});
+
test("a review-backed edit renders only the two-level review row", () => {
assert.equal(transcriptSource.includes("<WorkspaceChangesEntry />"), false);
assert.equal(transcriptSource.includes("review-changes-entry"), false);
@@ -190,7 +198,7 @@ test("a review-backed edit renders only the two-level review row", () => {
assert.doesNotMatch(transcriptSource, /workspaceDiff|findWorkspaceChange/);
assert.match(cardSource, /aria-expanded=\{open\}/);
assert.match(cardSource, /chat\.reviewChangeShow/);
- assert.match(cardSource, /change\.hunks\.map/);
+ assert.match(cardSource, /numberedReviewHunks\(displayChange\.hunks\)/);
assert.match(cardSource, /workspaceReviewRollback|rollbackWorkspaceChange/);
assert.match(
storeSource,
diff --git a/apps/desktop/test/review-file-open.test.mjs b/apps/desktop/test/review-file-open.test.mjs
new file mode 100644
index 000000000..65b18e1d0
--- /dev/null
+++ b/apps/desktop/test/review-file-open.test.mjs
@@ -0,0 +1,140 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import ts from "typescript";
+
+function load(relative, imports) {
+ const source = readFileSync(new URL(relative, import.meta.url), "utf8");
+ const { outputText } = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } });
+ const module = { exports: {} };
+ new Function("require", "exports", "module", outputText)(id => { assert.ok(Object.hasOwn(imports, id), id); return imports[id]; }, module.exports, module);
+ return module.exports;
+}
+const tabs = load("../src/lib/work-panel-tabs.ts", {});
+const manager = { pluginId: "pi.file-manager", viewId: "manager" };
+function fixture() {
+ const calls = { opened: [], revealed: [], reviewed: [], tabs: [], toasts: [], refs: [] };
+ const state = { activeSessionId: "s", workspace: { path: "D:/project" }, sessions: [{ id: "s" }], pluginViews: [manager],
+ openWorkPanelTab: tab => calls.tabs.push(tab), showToast: (...args) => calls.toasts.push(args) };
+ const host = {
+ match: { root: "workspace", relativePath: "src/a.ts", absolutePath: "D:/project/src/a.ts", matchedBy: "exact-absolute", projectRoot: { primary: true } },
+ loaded: [manager], onResolve: () => {},
+ };
+ const useAppStore = Object.assign(selector => selector(state), { getState: () => state });
+ const { useReviewFileOpen } = load("../src/hooks/use-review-file-open.ts", {
+ "react-i18next": { useTranslation: () => ({ t: key => key }) },
+ "../stores/app-store": { useAppStore }, "../lib/work-panel-tabs": tabs,
+ "../lib/api": { api: {
+ fsResolveRef: async (...args) => { calls.refs.push(args); await host.onResolve(); return { match: host.match }; },
+ fsOpen: async (...args) => { calls.opened.push(args); if (host.failOpen) throw Error("OS failure"); },
+ fsReveal: async (...args) => { calls.revealed.push(args); if (host.failReveal) throw Error("OS reveal failure"); },
+ workspaceReviewOpenFile: async input => { calls.reviewed.push(input); if (host.failReviewed) throw Error("OS open failure"); },
+ listPluginViews: async () => host.loaded,
+ } },
+ });
+ const file = { root: "D:/project", path: "src/a.ts", entries: [{ message: {}, change: { snapshotId: "native-snapshot" } }] };
+ return { calls, state, host, file, hook: () => useReviewFileOpen(file, "s") };
+}
+test("disabled/missing file manager cannot open or silently enable a plugin", async () => {
+ const f = fixture(); f.state.pluginViews = [];
+ assert.equal(f.hook().canOpenInternal, false);
+ await f.hook().openFile("internal");
+ assert.deepEqual(f.calls.tabs, []); assert.deepEqual(f.calls.refs, []);
+});
+test("review opens an exact current file in the loaded file manager", async () => {
+ const f = fixture(); assert.equal(f.hook().canOpenInternal, true);
+ await f.hook().openFile("internal");
+ assert.deepEqual(f.calls.refs, [["D:/project/src/a.ts", "s"]]);
+ assert.deepEqual(f.calls.tabs, [tabs.fileManagerPluginTab("src/a.ts")]);
+});
+test("worktree and secondary project files keep their absolute identity", async () => {
+ for (const isolated of [true, false]) {
+ const f = fixture();
+ if (isolated) f.state.sessions[0].worktree = { path: "D:/branch" };
+ else f.host.match.projectRoot.primary = false;
+ f.host.match.absolutePath = "D:/branch/src/a.ts";
+ await f.hook().openFile("internal");
+ assert.equal(f.calls.tabs[0].location, "D:/branch/src/a.ts");
+ }
+});
+test("external open passes the resolved path and owning session to the OS boundary", async () => {
+ const f = fixture(); f.state.pluginViews = [];
+ f.host.match.absolutePath = "D:/branch/src/a.ts";
+ await f.hook().openFile("external");
+ assert.deepEqual(f.calls.opened, [["D:/branch/src/a.ts", undefined, "s"]]);
+});
+test("missing, forbidden and fuzzy same-named matches never open another file", async () => {
+ for (const matchedBy of [null, "basename", "path-suffix"]) {
+ const f = fixture(); if (matchedBy) f.host.match.matchedBy = matchedBy; else f.host.match = null;
+ await f.hook().openFile("external");
+ assert.deepEqual(f.calls.opened, []); assert.equal(f.calls.toasts.length, 1);
+ }
+});
+test("plugin unloading during lookup cannot open a stale plugin tab", async () => {
+ const f = fixture(); f.host.loaded = [];
+ await f.hook().openFile("internal");
+ assert.deepEqual(f.calls.tabs, []); assert.equal(f.calls.toasts.length, 1);
+});
+test("session/project switching while lookup is in flight discards the result", async () => {
+ for (const destination of ["internal", "external", "folder"]) {
+ for (const changed of ["session", "workspace"]) {
+ const f = fixture();
+ f.host.onResolve = () => { if (changed === "session") f.state.activeSessionId = "other"; else f.state.workspace = { path: "D:/other" }; };
+ await f.hook().openFile(destination);
+ assert.deepEqual(f.calls.tabs, []); assert.deepEqual(f.calls.opened, []); assert.deepEqual(f.calls.revealed, []); assert.deepEqual(f.calls.toasts, []);
+ }
+ }
+});
+test("unknown legacy delegate provenance and remote workspaces are disabled", async () => {
+ const f = fixture(); delete f.file.root; f.file.entries[0].message.parentToolCallId = "task";
+ assert.equal(f.hook().canOpenFile, false); await f.hook().openFile("external");
+ assert.deepEqual(f.calls.opened, []);
+ f.file.root = "D:/project"; f.state.workspace.remote = {};
+ assert.equal(f.hook().canOpenFile, false);
+});
+test("Windows review roots become canonical file references before authorized lookup", async () => {
+ const cases = [
+ ["\\\\?\\D:\\project", "D:/project/src/a.ts"],
+ ["D:\\project", "D:/project/src/a.ts"],
+ ["\\\\?\\UNC\\server\\share\\project", "//server/share/project/src/a.ts"],
+ ["/project", "/project/src/a.ts"],
+ ];
+ for (const [root, expected] of cases) {
+ const f = fixture(); f.file.root = root;
+ await f.hook().openFile("external");
+ assert.equal(f.calls.refs[0][0], expected);
+ }
+});
+test("OS failures remain visible to the owning session", async () => {
+ const f = fixture(); f.host.failOpen = true;
+ await f.hook().openFile("external");
+ assert.equal(f.calls.toasts[0][0], "panel.review.openError");
+});
+test("absolute outside-workspace paths are resolved directly, never appended to the workspace", async () => {
+ for (const path of ["D:/outside/file.txt", "/tmp/file.txt", "\\\\?\\D:\\outside\\file.txt"]) {
+ const f = fixture(); f.file.path = path;
+ await f.hook().openFile("folder");
+ assert.equal(f.hook().outside, true);
+ assert.equal(f.hook().canOpenInternal, false);
+ assert.deepEqual(f.calls.refs, []);
+ assert.deepEqual(f.calls.reviewed, [{ sessionId: "s", snapshotId: "native-snapshot", action: "folder" }]);
+ await f.hook().openFile("internal"); assert.deepEqual(f.calls.tabs, []);
+ }
+});
+test("open folder reveals the exact resolved file in the system file manager without a plugin", async () => {
+ const f = fixture(); f.state.pluginViews = [];
+ f.host.match.absolutePath = "D:/branch/src/a.ts";
+ await f.hook().openFile("folder");
+ assert.deepEqual(f.calls.revealed, [["D:/branch/src/a.ts", "s"]]);
+ assert.deepEqual(f.calls.opened, []); assert.deepEqual(f.calls.tabs, []);
+});
+test("folder action rejects unavailable/fuzzy paths and reports OS failures", async () => {
+ for (const match of [null, { matchedBy: "basename" }, { matchedBy: "path-suffix" }]) {
+ const f = fixture(); f.host.match = match;
+ await f.hook().openFile("folder");
+ assert.deepEqual(f.calls.revealed, []); assert.equal(f.calls.toasts.length, 1);
+ }
+ const f = fixture(); f.host.failReveal = true;
+ await f.hook().openFile("folder");
+ assert.equal(f.calls.toasts[0][0], "panel.review.openError");
+});
diff --git a/apps/desktop/test/review-history.test.mjs b/apps/desktop/test/review-history.test.mjs
new file mode 100644
index 000000000..d8178a1c3
--- /dev/null
+++ b/apps/desktop/test/review-history.test.mjs
@@ -0,0 +1,55 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { numberedReviewHunks, groupReviewFiles, readReviewPages, reviewFilePathLabel } from "../src/lib/review-history.ts";
+
+function entry(id, path = "a.ts", root) {
+ return { root, message: { id, role: "tool", content: "", createdAt: "2026-10-30", toolName: "Edit", toolStatus: "success", toolResult: { details: { root: "workspace", review: { version: 1, snapshotId: id, messageId: id, path, operation: "edit", status: "modified", state: "active", additions: 1, deletions: 1, hunks: [], reversible: true } } } } };
+}
+test("groups only the same execution root and path, deduplicating snapshots", () => {
+ const a = entry("one", "src/a.ts", "D:/main"), b = entry("two", "src/a.ts", "D:/main");
+ b.message.parentToolCallId = "task";
+ const groups = groupReviewFiles([a, b, a, entry("child", "src/a.ts", "D:/delegate"), entry("other", "b.ts", "D:/main")]);
+ assert.equal(groups.length, 3);
+ assert.deepEqual(groups[0].entries.map(e => e.change.snapshotId), ["one", "two"]);
+ assert.equal(groups[0].additions, 2);
+ assert.equal(groups[1].root, "D:/delegate");
+});
+test("unknown legacy delegate roots are never merged with the parent", () => {
+ const child = entry("child"); child.message.parentToolCallId = "task";
+ assert.equal(groupReviewFiles([entry("main"), child]).length, 2);
+});
+test("numbers additions, deletions, context, empty ranges, separate hunks and EOF markers", () => {
+ const hunks = numberedReviewHunks([
+ { header: "@@ -0,0 +1,2 @@", lines: [{ type: "add", text: "a" }, { type: "add", text: "b" }] },
+ { header: "@@ -10,3 +12,2 @@", lines: [{ type: "context", text: "x" }, { type: "del", text: "old" }, { type: "del", text: "last" }, { type: "add", text: "new" }] },
+ { header: "@@ -20 +21 @@", lines: [{ type: "del", text: "a" }, { type: "context", text: "\\ No newline at end of file" }, { type: "add", text: "b" }] },
+ ]);
+ assert.deepEqual(hunks[0].lines.map(l => [l.oldLine, l.newLine]), [[null, 1], [null, 2]]);
+ assert.deepEqual(hunks[1].lines.map(l => [l.oldLine, l.newLine]), [[10, 12], [11, null], [12, null], [null, 13]]);
+ assert.deepEqual(hunks[2].lines.map(l => [l.oldLine, l.newLine]), [[20, null], [null, null], [null, 21]]);
+});
+test("invalid headers do not fabricate line numbers", () => {
+ assert.deepEqual(numberedReviewHunks([{ header: "unknown", lines: [{ type: "add", text: "a" }] }])[0].lines[0], { type: "add", text: "a", oldLine: null, newLine: null });
+});
+test("reads every history page using resolved turn identity, without touching chat state", async () => {
+ const calls = [];
+ const page = await readReviewPages(async input => {
+ calls.push(input);
+ return input.offset ? { turnId: "user1", changes: [entry("two") ] } : { turnId: "user1", changes: [entry("one")], nextOffset: 1 };
+ }, { sessionId: "session", snapshotId: "one" }, () => true);
+ assert.equal(page.changes.length, 2);
+ assert.equal(calls[1].turnId, "user1");
+ assert.equal(calls[1].snapshotId, undefined);
+});
+test("switching session cancels pagination and repeated cursors are errors", async () => {
+ let active = true;
+ await assert.rejects(readReviewPages(async () => { active = false; return { turnId: "u", changes: [], nextOffset: 1 }; }, { sessionId: "s" }, () => active), { name: "AbortError" });
+ await assert.rejects(readReviewPages(async () => ({ turnId: "u", changes: [], nextOffset: 0 }), { sessionId: "s" }, () => true), /cursor/i);
+});
+test("outside-workspace path labels keep only three dots, slash and basename", () => {
+ for (const path of ["/tmp/deep/review-open-tests-source.mjs", "D:/tmp/review-open-tests-source.mjs", "D:\\tmp\\review-open-tests-source.mjs", "\\\\server\\share\\review-open-tests-source.mjs", "../other/review-open-tests-source.mjs", "src/../../review-open-tests-source.mjs"]) {
+ assert.equal(reviewFilePathLabel(path), ".../review-open-tests-source.mjs");
+ }
+ assert.equal(reviewFilePathLabel("src/local.ts"), "src/local.ts");
+ assert.equal(reviewFilePathLabel("src/../local.ts"), "src/../local.ts");
+});
diff --git a/apps/desktop/test/review-preferences.test.mjs b/apps/desktop/test/review-preferences.test.mjs
new file mode 100644
index 000000000..b22bb9f7d
--- /dev/null
+++ b/apps/desktop/test/review-preferences.test.mjs
@@ -0,0 +1,58 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ readReviewContextLines,
+ rememberReviewContextLines,
+ REVIEW_CONTEXT_STORAGE_KEY,
+} from "../src/lib/review-preferences.ts";
+
+function storageFixture(t, store) {
+ const original = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
+ Object.defineProperty(globalThis, "localStorage", { configurable: true, get: () => store });
+ t.after(() => {
+ if (original) Object.defineProperty(globalThis, "localStorage", original);
+ else delete globalThis.localStorage;
+ });
+}
+
+test("missing or invalid context preferences use three lines without writing", t => {
+ let value = null;
+ storageFixture(t, {
+ getItem: key => { assert.equal(key, REVIEW_CONTEXT_STORAGE_KEY); return value; },
+ setItem: () => assert.fail("Reading preferences must not write"),
+ });
+ for (value of [null, "", "0", "2", "20", "-1", "null", "{}", "true", "1.0", " 1 ", '"5"']) {
+ assert.equal(readReviewContextLines(), 3, String(value));
+ }
+});
+
+test("all supported context values round-trip through one profile-wide key", t => {
+ const values = new Map();
+ storageFixture(t, {
+ getItem: key => values.get(key) ?? null,
+ setItem: (key, value) => values.set(key, value),
+ });
+ for (const lines of [1, 3, 5]) {
+ rememberReviewContextLines(lines);
+ assert.equal(readReviewContextLines(), lines);
+ assert.deepEqual([...values], [[REVIEW_CONTEXT_STORAGE_KEY, String(lines)]]);
+ }
+});
+
+test("unavailable storage preserves the default and never blocks a choice", t => {
+ storageFixture(t, undefined);
+ assert.equal(readReviewContextLines(), 3);
+ assert.doesNotThrow(() => rememberReviewContextLines(1));
+});
+
+test("storage access, read and quota failures do not escape to review UI", t => {
+ storageFixture(t, {
+ getItem: () => { throw new Error("Storage blocked"); },
+ setItem: () => { throw new Error("Quota exceeded"); },
+ });
+ assert.equal(readReviewContextLines(), 3);
+ assert.doesNotThrow(() => rememberReviewContextLines(5));
+ Object.defineProperty(globalThis, "localStorage", { configurable: true, get: () => { throw new Error("Access denied"); } });
+ assert.equal(readReviewContextLines(), 3);
+ assert.doesNotThrow(() => rememberReviewContextLines(1));
+});
diff --git a/apps/desktop/test/reviewed-file-open.test.mjs b/apps/desktop/test/reviewed-file-open.test.mjs
new file mode 100644
index 000000000..1354c4b79
--- /dev/null
+++ b/apps/desktop/test/reviewed-file-open.test.mjs
@@ -0,0 +1,41 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { mkdtemp, writeFile, mkdir, rm } from "node:fs/promises";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import { openReviewedFile } from "../electron/main/reviewed-file-open.ts";
+
+async function fixture(t) {
+ const dir = await mkdtemp(join(process.env.PI_SCRATCH_DIR || tmpdir(), "review-open-boundary-"));
+ t.after(() => rm(dir, { recursive: true, force: true }));
+ const path = join(dir,"outside.txt"); await writeFile(path,"controlled test\n");
+ const calls = { opened: [], revealed: [], targets: [] };
+ let current = true;
+ const deps = { target: async (...args) => { calls.targets.push(args); return {path}; }, isCurrent: () => current,
+ stripPrefix: path => path.replace(/^\\\\\?\\(?=[A-Za-z]:\\)/,""),
+ openPath: async path => { calls.opened.push(path); return ""; }, reveal: path => calls.revealed.push(path) };
+ return {path,calls,deps,setCurrent:value=>{current=value;}};
+}
+test("review external open and folder reveal use only host-authenticated snapshot target",async t=>{
+ const f=await fixture(t);
+ await openReviewedFile({sessionId:"s",snapshotId:"snapshot",action:"external"},f.deps);
+ await openReviewedFile({sessionId:"s",snapshotId:"snapshot",action:"folder"},f.deps);
+ assert.deepEqual(f.calls.targets,[["s","snapshot"],["s","snapshot"]]);
+ assert.deepEqual(f.calls.opened,[f.path]);assert.deepEqual(f.calls.revealed,[f.path]);
+});
+test("raw paths, invalid actions, missing snapshots and replaced hosts cannot reach the shell",async t=>{
+ const f=await fixture(t);
+ for(const value of [{sessionId:"s",snapshotId:"x",action:"external",path:f.path},{sessionId:"s",snapshotId:"x",action:"internal"},{sessionId:"s",action:"folder"}]) await assert.rejects(openReviewedFile(value,f.deps));
+ f.setCurrent(false);await assert.rejects(openReviewedFile({sessionId:"s",snapshotId:"x",action:"external"},f.deps),/replaced/);
+ assert.deepEqual(f.calls.opened,[]);assert.deepEqual(f.calls.revealed,[]);
+});
+test("removed files and directories are not openable review files",async t=>{
+ const f=await fixture(t);await rm(f.path);await mkdir(f.path);
+ await assert.rejects(openReviewedFile({sessionId:"s",snapshotId:"x",action:"folder"},f.deps));
+ await rm(f.path,{recursive:true});await assert.rejects(openReviewedFile({sessionId:"s",snapshotId:"x",action:"external"},f.deps));
+ assert.deepEqual(f.calls.opened,[]);assert.deepEqual(f.calls.revealed,[]);
+});
+test("OS open failure is observable",async t=>{
+ const f=await fixture(t);f.deps.openPath=async()=>"No default application";
+ await assert.rejects(openReviewedFile({sessionId:"s",snapshotId:"x",action:"external"},f.deps),/No default application/);
+});
diff --git a/crates/host-core/src/review.rs b/crates/host-core/src/review.rs
index 7004b2c9e..56e0425e0 100644
--- a/crates/host-core/src/review.rs
+++ b/crates/host-core/src/review.rs
@@ -16,6 +16,14 @@ use uuid::Uuid;
use crate::workspace::{self, ContainedRoots, ToolRoot};
+mod context;
+#[cfg(test)]
+mod context_tests;
+pub(crate) mod file_actions;
+pub(crate) mod query;
+#[cfg(test)]
+mod trim_tests;
+
const REVIEW_DIR: &str = "review-changes";
const MAX_SNAPSHOT_BYTES: u64 = 16 * 1024 * 1024;
const MAX_DIFF_BYTES: u64 = 512 * 1024;
@@ -68,15 +76,17 @@ pub struct ReviewChange {
pub snapshot_id: String,
pub message_id: String,
pub path: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub root: Option<String>,
pub operation: ReviewChangeOperation,
pub status: ReviewChangeStatus,
pub state: ReviewChangeState,
pub additions: usize,
pub deletions: usize,
pub hunks: Vec<ReviewDiffHunk>,
- #[serde(skip_serializing_if = "std::ops::Not::not")]
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub binary: bool,
- #[serde(skip_serializing_if = "std::ops::Not::not")]
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub truncated: bool,
pub reversible: bool,
}
@@ -97,6 +107,12 @@ struct SnapshotMeta {
session_id: String,
message_id: String,
path: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ root: Option<String>,
+ #[serde(default)]
+ context_saved: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ context_unavailable: Option<String>,
operation: ReviewChangeOperation,
before_exists: bool,
#[serde(skip_serializing_if = "Option::is_none")]
@@ -117,6 +133,8 @@ pub struct PendingChange {
message_id: String,
snapshot_id: String,
path: String,
+ root: String,
+ within_workspace: bool,
operation: ReviewChangeOperation,
before_exists: bool,
before_hash: Option<String>,
@@ -220,6 +238,7 @@ pub fn prepare_change(
roots: &ContainedRoots,
tool_name: &str,
args: &Value,
+ allow_external_paths: bool,
) -> Result<Option<PendingChange>> {
let Some(operation) = tool_operation(tool_name) else {
return Ok(None);
@@ -230,10 +249,12 @@ pub fn prepare_change(
let Some(input) = args.get("path").and_then(Value::as_str) else {
return Ok(None);
};
- let Ok((resolved, root_kind)) = workspace::resolve_tool_path(root, roots, input) else {
+ let Ok((resolved, root_kind)) =
+ workspace::resolve_tool_path_with_external(root, roots, input, allow_external_paths)
+ else {
return Ok(None);
};
- if root_kind != ToolRoot::Workspace {
+ if crate::tools::ignore_rules::is_sensitive_path(&resolved) {
return Ok(None);
}
@@ -253,7 +274,12 @@ pub fn prepare_change(
.as_ref()
.is_some_and(|value| value.len() <= MAX_SNAPSHOT_BYTES)
&& fs::copy(&resolved, &before_path).is_ok();
- let path = relative_path(root, &resolved);
+ let within_workspace = root_kind == ToolRoot::Workspace;
+ let path = if within_workspace {
+ relative_path(root, &resolved)
+ } else {
+ resolved.to_string_lossy().replace('\\', "/")
+ };
Ok(Some(PendingChange {
snapshot_dir,
@@ -263,6 +289,8 @@ pub fn prepare_change(
message_id: message_id.to_string(),
snapshot_id,
path,
+ root: root.canonicalize()?.to_string_lossy().into_owned(),
+ within_workspace,
operation,
before_exists,
before_hash,
@@ -285,10 +313,44 @@ fn read_preview(path: Option<&Path>, exists: bool) -> Result<Option<Vec<u8>>> {
if !metadata.is_file() || metadata.len() > MAX_DIFF_BYTES {
return Ok(None);
}
- Ok(Some(fs::read(path)?))
+ let mut bytes = Vec::new();
+ fs::File::open(path)?
+ .take(MAX_DIFF_BYTES + 1)
+ .read_to_end(&mut bytes)?;
+ Ok((bytes.len() as u64 <= MAX_DIFF_BYTES).then_some(bytes))
}
fn diff_ops(before: &[String], after: &[String]) -> Option<Vec<DiffOp>> {
+ let prefix = before
+ .iter()
+ .zip(after)
+ .take_while(|(old, new)| old == new)
+ .count();
+ let suffix = before[prefix..]
+ .iter()
+ .rev()
+ .zip(after[prefix..].iter().rev())
+ .take_while(|(old, new)| old == new)
+ .count();
+ // Unchanged edges are linear work, not part of the quadratic LCS budget.
+ // Reattach them so hunk coordinates and finite context stay file-relative.
+ let middle = diff_middle(
+ &before[prefix..before.len() - suffix],
+ &after[prefix..after.len() - suffix],
+ )?;
+ let mut ops = Vec::with_capacity(prefix + middle.len() + suffix);
+ ops.extend(before[..prefix].iter().cloned().map(DiffOp::Equal));
+ ops.extend(middle);
+ ops.extend(
+ before[before.len() - suffix..]
+ .iter()
+ .cloned()
+ .map(DiffOp::Equal),
+ );
+ Some(ops)
+}
+
+fn diff_middle(before: &[String], after: &[String]) -> Option<Vec<DiffOp>> {
if (before.len() + 1).saturating_mul(after.len() + 1) > MAX_DIFF_CELLS {
return None;
}
@@ -346,6 +408,10 @@ fn new_line_count(op: &DiffOp) -> usize {
}
fn make_hunks(ops: &[DiffOp]) -> Vec<ReviewDiffHunk> {
+ make_hunks_with_context(ops, CONTEXT_LINES)
+}
+
+fn make_hunks_with_context(ops: &[DiffOp], context: usize) -> Vec<ReviewDiffHunk> {
let changed: Vec<usize> = ops
.iter()
.enumerate()
@@ -357,8 +423,11 @@ fn make_hunks(ops: &[DiffOp]) -> Vec<ReviewDiffHunk> {
let mut ranges: Vec<(usize, usize)> = Vec::new();
for index in changed {
- let start = index.saturating_sub(CONTEXT_LINES);
- let end = (index + CONTEXT_LINES + 1).min(ops.len());
+ let start = index.saturating_sub(context);
+ let end = index
+ .saturating_add(context)
+ .saturating_add(1)
+ .min(ops.len());
if let Some((_, previous_end)) = ranges.last_mut() {
if start <= *previous_end {
*previous_end = (*previous_end).max(end);
@@ -437,11 +506,17 @@ fn make_preview(
pub fn finalize_change(pending: &PendingChange) -> Result<ReviewChange> {
let after_exists = pending.resolved.is_file();
+ // Read a bounded after image only while capturing the finite context hunks.
+ let after = read_preview(Some(&pending.resolved), after_exists)?;
let after_hash = if after_exists {
- Some(hash_file(&pending.resolved)?)
+ Some(match &after {
+ Some(bytes) => hex::encode(Sha256::digest(bytes)),
+ None => hash_file(&pending.resolved)?,
+ })
} else {
None
};
+ let context_unavailable = context::save(pending, after.as_deref())?;
let (binary, truncated, additions, deletions, hunks) = make_preview(
pending
.before_copied
@@ -457,16 +532,21 @@ pub fn finalize_change(pending: &PendingChange) -> Result<ReviewChange> {
};
// Existing files remain reversible even when the tool deleted them; new
// files need to exist after the tool so rollback can remove them.
- let reversible = if pending.before_exists {
- pending.before_copied
- } else {
- after_exists
- };
+ // Capture is not a persistent grant to write outside the current workspace.
+ let reversible = pending.within_workspace
+ && if pending.before_exists {
+ pending.before_copied
+ } else {
+ after_exists
+ };
let meta = SnapshotMeta {
version: 1,
session_id: pending.session_id.clone(),
message_id: pending.message_id.clone(),
path: pending.path.clone(),
+ root: Some(pending.root.clone()),
+ context_saved: context_unavailable.is_none(),
+ context_unavailable,
operation: pending.operation,
before_exists: pending.before_exists,
before_hash: pending.before_hash.clone(),
@@ -481,6 +561,7 @@ pub fn finalize_change(pending: &PendingChange) -> Result<ReviewChange> {
snapshot_id: pending.snapshot_id.clone(),
message_id: pending.message_id.clone(),
path: pending.path.clone(),
+ root: Some(pending.root.clone()),
operation: pending.operation,
status,
state: ReviewChangeState::Active,
@@ -533,6 +614,15 @@ pub fn rollback_change(
let Some(root) = workspace_root else {
return Ok(unavailable());
};
+ // Snapshot roots are evidence, never an authorization to access a path.
+ // Delegate worktrees must not be rolled back into the session checkout.
+ if meta
+ .root
+ .as_deref()
+ .is_some_and(|captured| root.canonicalize().ok().as_deref() != Some(Path::new(captured)))
+ {
+ return Ok(unavailable());
+ }
let Ok(target) = workspace::resolve_in_workspace(root, &meta.path) else {
return Ok(unavailable());
};
@@ -617,9 +707,70 @@ mod tests {
&ContainedRoots::new(),
"Edit",
&json!({ "path": path }),
+ false,
+ )
+ .unwrap()
+ .unwrap()
+ }
+
+ #[test]
+ fn outside_capture_requires_approval_and_skips_sensitive_paths() {
+ let data = tempdir().unwrap();
+ let workspace = tempdir().unwrap();
+ let outside = tempdir().unwrap();
+ let target = outside.path().join("file.txt");
+ fs::write(&target, "fixture before\n").unwrap();
+ let args = json!({"path": target.to_string_lossy()});
+ assert!(prepare_change(
+ data.path(),
+ "s",
+ "m",
+ Some(workspace.path()),
+ &ContainedRoots::new(),
+ "Write",
+ &args,
+ false
)
.unwrap()
+ .is_none());
+ assert!(!data.path().join(REVIEW_DIR).exists());
+ let pending = prepare_change(
+ data.path(),
+ "s",
+ "m",
+ Some(workspace.path()),
+ &ContainedRoots::new(),
+ "Write",
+ &args,
+ true,
+ )
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ fs::read_to_string(&pending.before_path).unwrap(),
+ "fixture before\n"
+ );
+ discard_change(pending);
+ let sensitive = outside.path().join(".env");
+ fs::write(&sensitive, "NON_SECRET_TEST_FIXTURE=1\n").unwrap();
+ assert!(prepare_change(
+ data.path(),
+ "s",
+ "sensitive",
+ Some(workspace.path()),
+ &ContainedRoots::new(),
+ "Write",
+ &json!({"path": sensitive.to_string_lossy()}),
+ true
+ )
.unwrap()
+ .is_none());
+ assert_eq!(
+ fs::read_dir(data.path().join(REVIEW_DIR).join("s"))
+ .unwrap()
+ .count(),
+ 0
+ );
}
#[test]
diff --git a/crates/host-core/src/review/context.rs b/crates/host-core/src/review/context.rs
new file mode 100644
index 000000000..25b0ed407
--- /dev/null
+++ b/crates/host-core/src/review/context.rs
@@ -0,0 +1,104 @@
+//! Bounded 1/3/5-line context, captured once; no complete after-image cache.
+use super::*;
+use serde_json::json;
+
+const MAX_CONTEXT_BYTES: usize = 2 * MAX_DIFF_BYTES as usize;
+
+pub(super) fn save(pending: &PendingChange, after: Option<&[u8]>) -> Result<Option<String>> {
+ let Ok(Some(before)) = read_preview(
+ pending
+ .before_copied
+ .then_some(pending.before_path.as_path()),
+ pending.before_exists,
+ ) else {
+ return Ok(Some("tooLarge".into()));
+ };
+ let Some(after) = after else {
+ return Ok(Some("tooLarge".into()));
+ };
+ if before.contains(&0) || after.contains(&0) {
+ return Ok(Some("binary".into()));
+ }
+ let (Ok(before), Ok(after)) = (String::from_utf8(before), std::str::from_utf8(after)) else {
+ return Ok(Some("binary".into()));
+ };
+ // Terminators are part of identity, so newline-only edits remain visible.
+ let before: Vec<String> = before.split_inclusive('\n').map(str::to_owned).collect();
+ let after: Vec<String> = after.split_inclusive('\n').map(str::to_owned).collect();
+ if before.len() > MAX_DIFF_LINES || after.len() > MAX_DIFF_LINES {
+ return Ok(Some("tooLarge".into()));
+ }
+ let Some(ops) = diff_ops(&before, &after) else {
+ return Ok(Some("tooLarge".into()));
+ };
+ let mut contexts = serde_json::Map::new();
+ for radius in [1, 3, 5] {
+ let mut hunks = make_hunks_with_context(&ops, radius);
+ for hunk in &mut hunks {
+ let mut lines = Vec::new();
+ for mut line in std::mem::take(&mut hunk.lines) {
+ let terminated = line.text.ends_with('\n');
+ if terminated {
+ line.text.pop();
+ if line.text.ends_with('\r') {
+ line.text.pop();
+ }
+ }
+ lines.push(line);
+ if !terminated {
+ lines.push(ReviewDiffLine {
+ line_type: "context".into(),
+ text: "\\ No newline at end of file".into(),
+ });
+ }
+ }
+ hunk.lines = lines;
+ }
+ contexts.insert(radius.to_string(), serde_json::to_value(hunks)?);
+ }
+ let encoded = serde_json::to_vec(&json!({"version":1,"contexts":contexts}))?;
+ if encoded.len() > MAX_CONTEXT_BYTES {
+ return Ok(Some("tooLarge".into()));
+ }
+ fs::write(pending.snapshot_dir.join("contexts.json"), encoded)?;
+ Ok(None)
+}
+
+pub(super) fn load(
+ data_dir: &Path,
+ session_id: &str,
+ snapshot_id: &str,
+ context: i64,
+) -> Result<Value> {
+ let meta = read_meta(data_dir, session_id, snapshot_id)?;
+ let unavailable = |reason: &str| json!({ "hunks": [], "unavailable": reason });
+ if let Some(reason) = &meta.context_unavailable {
+ return Ok(unavailable(reason));
+ }
+ if !meta.context_saved {
+ return Ok(unavailable("legacy"));
+ }
+ let file = snapshot_dir(data_dir, session_id, snapshot_id)?.join("contexts.json");
+ let metadata = fs::symlink_metadata(&file)?;
+ if !metadata.is_file() || metadata.file_type().is_symlink() {
+ return Err(anyhow!("invalid review context file"));
+ }
+ if metadata.len() > MAX_CONTEXT_BYTES as u64 {
+ return Ok(unavailable("tooLarge"));
+ }
+ let mut encoded = Vec::new();
+ fs::File::open(file)?
+ .take(MAX_CONTEXT_BYTES as u64 + 1)
+ .read_to_end(&mut encoded)?;
+ if encoded.len() > MAX_CONTEXT_BYTES {
+ return Ok(unavailable("tooLarge"));
+ }
+ let saved: Value = serde_json::from_slice(&encoded)?;
+ let hunks = saved
+ .get("contexts")
+ .and_then(|v| v.get(context.to_string()));
+ if saved.get("version") != Some(&json!(1)) || !hunks.is_some_and(Value::is_array) {
+ return Err(anyhow!("invalid review context record"));
+ }
+ Ok(json!({"hunks":hunks}))
+}
diff --git a/crates/host-core/src/review/context_tests.rs b/crates/host-core/src/review/context_tests.rs
new file mode 100644
index 000000000..ee70ff610
--- /dev/null
+++ b/crates/host-core/src/review/context_tests.rs
@@ -0,0 +1,199 @@
+use super::*;
+use serde_json::json;
+use tempfile::tempdir;
+
+fn capture(data: &Path, root: &Path, before: Option<&[u8]>, after: Option<&[u8]>) -> ReviewChange {
+ let target = root.join("file.txt");
+ if let Some(bytes) = before {
+ fs::write(&target, bytes).unwrap();
+ } else if target.exists() {
+ fs::remove_file(&target).unwrap();
+ }
+ let pending = prepare_change(
+ data,
+ "session",
+ "message",
+ Some(root),
+ &ContainedRoots::new(),
+ "Write",
+ &json!({"path":"file.txt"}),
+ false,
+ )
+ .unwrap()
+ .unwrap();
+ if let Some(bytes) = after {
+ fs::write(&target, bytes).unwrap();
+ } else {
+ fs::remove_file(&target).unwrap();
+ }
+ finalize_change(&pending).unwrap()
+}
+
+fn load(data: &Path, snapshot: &str, radius: i64) -> Value {
+ // Exercise the public domain request interface, including validation.
+ let params = json!({"sessionId":"session", "snapshotId":snapshot, "context":radius});
+ let request = query::Request::parse("review.context", params).unwrap();
+ let db = crate::db::Database::open_in_dir(data).unwrap();
+ query::execute(&db, "review.context", request, None).unwrap()
+}
+
+#[test]
+fn finite_context_radii_survive_workspace_removal_without_full_after_cache() {
+ let data = tempdir().unwrap();
+ let root = tempdir().unwrap();
+ let before: String = (0..80).map(|i| format!("line {i}\n")).collect();
+ let after = before.replace("line 40\n", "replacement\n");
+ let change = capture(
+ data.path(),
+ root.path(),
+ Some(before.as_bytes()),
+ Some(after.as_bytes()),
+ );
+ let default_preview = serde_json::to_value(&change.hunks).unwrap();
+ let dir = snapshot_dir(data.path(), "session", &change.snapshot_id).unwrap();
+ assert!(!dir.join("after").exists(), "No full after-image cache");
+ let saved = fs::read_to_string(dir.join("contexts.json")).unwrap();
+ assert!(
+ !saved.contains("\"line 0\""),
+ "Far-away unchanged text is not cached"
+ );
+ for removed in [-1, 20] {
+ assert!(query::Request::parse(
+ "review.context",
+ json!({"sessionId":"session", "snapshotId":change.snapshot_id,"context":removed})
+ )
+ .is_err());
+ }
+
+ fs::remove_dir_all(root.path()).unwrap();
+ let mut sizes = Vec::new();
+ for radius in [1, 3, 5] {
+ let result = load(data.path(), &change.snapshot_id, radius);
+ assert!(result.get("unavailable").is_none());
+ assert!(result.to_string().contains("replacement"));
+ sizes.push(result["hunks"][0]["lines"].as_array().unwrap().len());
+ if radius == 3 {
+ assert_eq!(result["hunks"], default_preview);
+ }
+ }
+ assert_eq!(sizes, vec![4, 8, 12]);
+}
+
+#[test]
+fn context_added_deleted_and_newline_only_edits() {
+ let data = tempdir().unwrap();
+ let root = tempdir().unwrap();
+ for (before, after, kind) in [
+ (None, Some(&b"new\n"[..]), "add"),
+ (Some(&b"old\n"[..]), None, "del"),
+ (Some(&b"same"[..]), Some(&b"same\n"[..]), "add"),
+ (Some(&b"same\n"[..]), Some(&b"same"[..]), "del"),
+ ] {
+ let change = capture(data.path(), root.path(), before, after);
+ let result = load(data.path(), &change.snapshot_id, 5);
+ assert!(result["hunks"][0]["lines"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|line| line["type"] == kind));
+ if before.is_some() && after.is_some() {
+ assert!(result.to_string().contains("No newline"));
+ }
+ }
+}
+
+#[test]
+fn context_legacy_binary_and_each_resource_budget_are_explicit() {
+ let data = tempdir().unwrap();
+ let root = tempdir().unwrap();
+ let change = capture(data.path(), root.path(), Some(b"old\n"), Some(b"new\n"));
+ let dir = snapshot_dir(data.path(), "session", &change.snapshot_id).unwrap();
+ let mut meta: Value = serde_json::from_slice(&fs::read(metadata_path(&dir)).unwrap()).unwrap();
+ for key in ["root", "contextSaved", "contextUnavailable"] {
+ meta.as_object_mut().unwrap().remove(key);
+ }
+ fs::write(metadata_path(&dir), serde_json::to_vec(&meta).unwrap()).unwrap();
+ fs::remove_file(dir.join("contexts.json")).unwrap();
+ assert_eq!(
+ load(data.path(), &change.snapshot_id, 3),
+ json!({"hunks":[],"unavailable":"legacy"})
+ );
+ // Legacy metadata also remains readable by the existing rollback path.
+ assert_eq!(
+ rollback_change(
+ data.path(),
+ "session",
+ &change.snapshot_id,
+ Some(root.path())
+ )
+ .unwrap()
+ .status,
+ "rolledBack"
+ );
+ let cases = [
+ (b"binary\0".to_vec(), "binary"),
+ (vec![b'x'; MAX_DIFF_BYTES as usize + 1], "tooLarge"),
+ ("line\n".repeat(MAX_DIFF_LINES + 1).into_bytes(), "tooLarge"),
+ (
+ (0..1600)
+ .map(|i| format!("line {i}\n"))
+ .collect::<String>()
+ .into_bytes(),
+ "tooLarge",
+ ),
+ ];
+ for (bytes, reason) in cases {
+ // The final case exceeds the LCS cell budget while staying under the
+ // individual byte and line limits on both sides.
+ let before = if bytes.starts_with(b"line 0") {
+ (0..1600)
+ .map(|i| format!("other {i}\n"))
+ .collect::<String>()
+ .into_bytes()
+ } else {
+ b"before\n".to_vec()
+ };
+ let change = capture(data.path(), root.path(), Some(&before), Some(&bytes));
+ assert_eq!(
+ load(data.path(), &change.snapshot_id, 5),
+ json!({"hunks":[],"unavailable":reason})
+ );
+ }
+}
+
+#[test]
+fn snapshot_root_never_authorizes_rollback_into_another_checkout() {
+ let data = tempdir().unwrap();
+ let first = tempdir().unwrap();
+ let second = tempdir().unwrap();
+ let change = capture(
+ data.path(),
+ first.path(),
+ Some(b"before\n"),
+ Some(b"after\n"),
+ );
+ fs::write(second.path().join("file.txt"), b"after\n").unwrap();
+ let outcome = rollback_change(
+ data.path(),
+ "session",
+ &change.snapshot_id,
+ Some(second.path()),
+ )
+ .unwrap();
+ assert_eq!(outcome.status, "unavailable");
+ assert_eq!(
+ fs::read(second.path().join("file.txt")).unwrap(),
+ b"after\n"
+ );
+ assert_eq!(
+ rollback_change(
+ data.path(),
+ "session",
+ &change.snapshot_id,
+ Some(first.path())
+ )
+ .unwrap()
+ .status,
+ "rolledBack"
+ );
+}
diff --git a/crates/host-core/src/review/file_actions.rs b/crates/host-core/src/review/file_actions.rs
new file mode 100644
index 000000000..2b3ece748
--- /dev/null
+++ b/crates/host-core/src/review/file_actions.rs
@@ -0,0 +1,179 @@
+//! Explicit user actions on one persisted file in a review round.
+use super::*;
+use crate::db::Database;
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct FileRollbackOutcome {
+ pub status: &'static str,
+ pub changes: Vec<RollbackOutcome>,
+}
+
+/// Resolve only an exact native snapshot owned by this session. This is not a
+/// general external-path resolver or a grant to read/write its parent directory.
+pub(crate) fn file_target(
+ db: &Database,
+ session: &str,
+ snapshot: &str,
+ root: Option<&Path>,
+) -> Result<Value> {
+ let evidence = query::file_evidence(db, session, snapshot, root)?;
+ if !evidence.iter().any(|change| change.snapshot_id == snapshot) {
+ return Err(anyhow!("review snapshot is not in the session transcript"));
+ }
+ let meta = read_meta(db.data_dir(), session, snapshot)?;
+ let path = Path::new(&meta.path);
+ let expected = if path.is_absolute() {
+ path.to_path_buf()
+ } else {
+ let captured = meta
+ .root
+ .as_deref()
+ .ok_or_else(|| anyhow!("review execution root unavailable"))?;
+ let captured = Path::new(captured);
+ if path
+ .components()
+ .any(|component| !matches!(component, std::path::Component::Normal(_)))
+ {
+ return Err(anyhow!("invalid captured review path"));
+ }
+ captured.join(path)
+ };
+ let canonical = workspace::simple_canonicalize(&expected)?;
+ // Capture already resolved symlinks. A later replacement must not redirect
+ // an explicit click to a different file, even within an otherwise allowed root.
+ if comparable(&canonical) != comparable(&expected)
+ || !canonical.is_file()
+ || crate::tools::ignore_rules::is_sensitive_path(&canonical)
+ {
+ return Err(anyhow!("review file changed location or is unavailable"));
+ }
+ Ok(serde_json::json!({"path": canonical.to_string_lossy()}))
+}
+
+fn comparable(path: &Path) -> String {
+ let text = path.to_string_lossy().replace('\\', "/");
+ #[cfg(windows)]
+ {
+ let text = if let Some(rest) = text.strip_prefix("//?/UNC/") {
+ format!("//{rest}")
+ } else {
+ text.strip_prefix("//?/").unwrap_or(&text).to_owned()
+ };
+ text.to_lowercase()
+ }
+ #[cfg(not(windows))]
+ {
+ text
+ }
+}
+
+pub(crate) fn rollback_file(
+ db: &Database,
+ session: &str,
+ snapshot: &str,
+ root: Option<&Path>,
+) -> Result<FileRollbackOutcome> {
+ let evidence = query::file_evidence(db, session, snapshot, root)?;
+ let outcome = |status| FileRollbackOutcome {
+ status,
+ changes: Vec::new(),
+ };
+ if evidence.is_empty() || evidence.len() > 1000 {
+ return Ok(outcome("unavailable"));
+ }
+ let active: Vec<_> = evidence
+ .iter()
+ .filter(|change| change.state != ReviewChangeState::RolledBack)
+ .collect();
+ if active.is_empty() {
+ return Ok(outcome("alreadyRolledBack"));
+ }
+ if active.iter().any(|change| !change.reversible) {
+ return Ok(outcome("unavailable"));
+ }
+ let Some(root) = root else {
+ return Ok(outcome("unavailable"));
+ };
+ let canonical_root = root.canonicalize()?;
+ let mut metas = Vec::new();
+ for change in active {
+ let meta = read_meta(db.data_dir(), session, &change.snapshot_id)?;
+ if !meta.reversible
+ || meta
+ .root
+ .as_deref()
+ .is_some_and(|captured| Path::new(captured) != canonical_root)
+ || meta.path != evidence[0].path
+ || meta.root != evidence[0].root
+ {
+ return Ok(outcome("unavailable"));
+ }
+ metas.push((change.snapshot_id.clone(), meta));
+ }
+ for pair in metas.windows(2) {
+ if pair[0].1.after_exists != pair[1].1.before_exists
+ || pair[0].1.after_hash != pair[1].1.before_hash
+ {
+ return Ok(outcome("conflict"));
+ }
+ }
+ let (Some((first_id, first)), Some((_, last))) = (metas.first(), metas.last()) else {
+ return Ok(outcome("unavailable"));
+ };
+ let target = match workspace::resolve_in_workspace(root, &first.path) {
+ Ok(target) => target,
+ Err(_) => return Ok(outcome("unavailable")),
+ };
+ let current_exists = target.is_file();
+ let current_hash = if current_exists {
+ Some(hash_file(&target)?)
+ } else {
+ None
+ };
+ if current_exists != last.after_exists || current_hash != last.after_hash {
+ return Ok(outcome("conflict"));
+ }
+ // Validate every link and the restoration source before the single write.
+ let before = if first.before_exists {
+ let source = before_path(&snapshot_dir(db.data_dir(), session, first_id)?);
+ if fs::metadata(&source)?.len() > MAX_SNAPSHOT_BYTES {
+ return Ok(outcome("unavailable"));
+ }
+ let bytes = fs::read(source)?;
+ if bytes.len() as u64 > MAX_SNAPSHOT_BYTES
+ || Some(hex::encode(Sha256::digest(&bytes))) != first.before_hash
+ {
+ return Ok(outcome("unavailable"));
+ }
+ Some(bytes)
+ } else {
+ None
+ };
+ if let Some(bytes) = before {
+ if let Some(parent) = target.parent() {
+ fs::create_dir_all(parent)?;
+ }
+ fs::write(&target, bytes).context("restore file review snapshot chain")?;
+ } else if target.exists() {
+ fs::remove_file(&target).context("remove file created in review round")?;
+ }
+ let mut changes = Vec::new();
+ for (id, mut meta) in metas {
+ meta.state = ReviewChangeState::RolledBack;
+ write_meta(
+ &metadata_path(&snapshot_dir(db.data_dir(), session, &id)?),
+ &meta,
+ )?;
+ changes.push(RollbackOutcome {
+ status: "rolledBack",
+ snapshot_id: id,
+ message_id: meta.message_id,
+ path: meta.path,
+ });
+ }
+ Ok(FileRollbackOutcome {
+ status: "rolledBack",
+ changes,
+ })
+}
diff --git a/crates/host-core/src/review/query.rs b/crates/host-core/src/review/query.rs
new file mode 100644
index 000000000..4117f195d
--- /dev/null
+++ b/crates/host-core/src/review/query.rs
@@ -0,0 +1,419 @@
+//! Durable review discovery and bounded transport projections.
+use super::*;
+use crate::db::Database;
+use crate::sessions;
+use crate::transcripts::{self, MessageRecord};
+use serde_json::json;
+use std::collections::{HashMap, HashSet};
+
+const MAX_CHANGE_BYTES: usize = 16 * 1024;
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct Request {
+ pub session_id: String,
+ before: Option<i64>,
+ limit: Option<i64>,
+ turn_id: Option<String>,
+ snapshot_id: Option<String>,
+ offset: Option<i64>,
+ context: Option<i64>,
+}
+
+impl Request {
+ pub fn parse(method: &str, params: Value) -> Result<Self> {
+ let request: Self = serde_json::from_value(params)?;
+ if !safe_component(&request.session_id)
+ || request.before.is_some_and(|value| value < 0)
+ || request.offset.is_some_and(|value| value < 0)
+ || request
+ .turn_id
+ .as_ref()
+ .is_some_and(|value| value.is_empty())
+ || request
+ .snapshot_id
+ .as_ref()
+ .is_some_and(|value| !safe_component(value))
+ {
+ return Err(anyhow!("invalid review parameters"));
+ }
+ if method == "review.context"
+ && (request.snapshot_id.is_none() || !matches!(request.context, Some(1 | 3 | 5)))
+ {
+ return Err(anyhow!("snapshotId and context (1, 3, 5) required"));
+ }
+ Ok(request)
+ }
+}
+
+struct Turn {
+ position: usize,
+ id: String,
+ created_at: String,
+ title: String,
+ changes: Vec<Value>,
+ snapshots: HashSet<String>,
+}
+
+fn field<'a>(value: &'a Value, name: &str) -> Option<&'a str> {
+ value.get(name).and_then(Value::as_str)
+}
+
+fn tool_block(record: &MessageRecord) -> Option<&Value> {
+ record
+ .blocks
+ .as_array()?
+ .iter()
+ .find(|block| field(block, "type") == Some("tool_call"))
+}
+
+fn reviews(block: &Value) -> Vec<&Value> {
+ let Some(review) = block.pointer("/result/details/review") else {
+ return Vec::new();
+ };
+ match review {
+ Value::Array(items) => items.iter().collect(),
+ Value::Object(_) => vec![review],
+ _ => Vec::new(),
+ }
+}
+
+fn parent(record: &MessageRecord) -> Option<&str> {
+ record
+ .meta
+ .as_ref()
+ .and_then(|meta| field(meta, "parentToolCallId"))
+}
+
+// A parent Task owns its descendants even when their terminal results arrive
+// after a new prompt, or the descendant has a separate runtime turn id.
+fn owner(
+ index: usize,
+ records: &[MessageRecord],
+ calls: &HashMap<String, usize>,
+ indexed: &HashMap<String, String>,
+ turn_users: &HashMap<String, usize>,
+ fallback: &[Option<usize>],
+) -> Option<usize> {
+ let mut cursor = index;
+ let mut visited = HashSet::new();
+ while let Some(call) = parent(&records[cursor]) {
+ if !visited.insert(cursor) {
+ return None;
+ }
+ let Some(parent_index) = calls.get(call) else {
+ // An incomplete legacy transcript can lack the spawning Task.
+ // Preserve its evidence using the index/order fallback below.
+ break;
+ };
+ cursor = *parent_index;
+ }
+ indexed
+ .get(&records[cursor].id)
+ .and_then(|turn| turn_users.get(turn).copied())
+ .or(fallback[cursor])
+}
+
+fn project(
+ db: &Database,
+ session_id: &str,
+ record: &MessageRecord,
+ block: &Value,
+ raw: &Value,
+ workspace_root: Option<&Path>,
+) -> Result<Option<(String, Value)>> {
+ let Ok(mut review) = serde_json::from_value::<ReviewChange>(raw.clone()) else {
+ return Ok(None);
+ };
+ if review.version != 1 || !safe_component(&review.snapshot_id) || review.path.is_empty() {
+ return Ok(None);
+ }
+ // The native snapshot's execution root wins over transcript annotations.
+ match read_meta(db.data_dir(), session_id, &review.snapshot_id) {
+ Ok(meta) => {
+ review.root = meta.root.or(review.root);
+ review.reversible &= meta.reversible;
+ review.state = meta.state;
+ }
+ Err(error)
+ if error
+ .downcast_ref::<std::io::Error>()
+ .is_some_and(|error| error.kind() == std::io::ErrorKind::NotFound) =>
+ {
+ // Forked transcripts retain evidence, not ownership of snapshots.
+ review.reversible = false;
+ }
+ Err(error) => return Err(error),
+ }
+ if let Some(root) = &review.root {
+ if workspace_root
+ .and_then(|path| path.canonicalize().ok())
+ .as_deref()
+ != Some(Path::new(root))
+ {
+ review.reversible = false;
+ }
+ } else if parent(record).is_some() {
+ review.reversible = false;
+ }
+ // Keep every change, including oversized individual hunks. Truncation is
+ // explicit and only removes the tail of the preview, not the whole card.
+ while serde_json::to_vec(&review)?.len() > MAX_CHANGE_BYTES && !review.hunks.is_empty() {
+ review.truncated = true;
+ let last = review
+ .hunks
+ .last_mut()
+ .ok_or_else(|| anyhow!("missing review hunk"))?;
+ if last.lines.len() > 1 {
+ last.lines.truncate(last.lines.len() / 2);
+ } else {
+ review.hunks.pop();
+ }
+ }
+ // Host-generated identity/path metadata is naturally bounded by filesystem
+ // limits. Corrupt oversized metadata is an error, never a silent omission.
+ if serde_json::to_vec(&review)?.len() > MAX_CHANGE_BYTES {
+ return Err(anyhow!("review metadata exceeds transport budget"));
+ }
+ let snapshot = review.snapshot_id.clone();
+ let root = review.root.clone();
+ let mut message = json!({
+ "id": record.id, "role": "tool", "content": "", "createdAt": record.created_at,
+ "toolName": record.tool_name.as_deref().or_else(|| field(block, "name")),
+ "toolCallId": field(block, "callId"), "status": "complete", "toolStatus": "success",
+ "toolResult": { "details": { "root": block.pointer("/result/details/root"), "review": review } }
+ });
+ for key in ["parentToolCallId", "nestedParentToolCallId", "agentName"] {
+ if let Some(value) = record.meta.as_ref().and_then(|meta| meta.get(key)) {
+ message[key] = value.clone();
+ }
+ }
+ let mut result = json!({ "message": message });
+ if let Some(root) = root {
+ result["root"] = json!(root);
+ }
+ if serde_json::to_vec(&result)?.len() > 2 * MAX_CHANGE_BYTES {
+ return Err(anyhow!("review message exceeds transport budget"));
+ }
+ Ok(Some((snapshot, result)))
+}
+
+fn collect(db: &Database, session_id: &str, workspace_root: Option<&Path>) -> Result<Vec<Turn>> {
+ let records =
+ sessions::dedupe_records(transcripts::read_transcript(db.data_dir(), session_id)?);
+ let mut stmt = db.conn().prepare(
+ "SELECT id, turn_id FROM messages WHERE session_id = ?1 AND turn_id IS NOT NULL",
+ )?;
+ let indexed: HashMap<String, String> = stmt
+ .query_map([session_id], |row| Ok((row.get(0)?, row.get(1)?)))?
+ .collect::<rusqlite::Result<_>>()?;
+ let mut turns: Vec<Turn> = Vec::new();
+ let mut turn_users = HashMap::new();
+ let mut fallback = Vec::with_capacity(records.len());
+ let mut current = None;
+ let mut calls = HashMap::new();
+ for (index, record) in records.iter().enumerate() {
+ let meta = record.meta.as_ref();
+ if record.role == "user"
+ && parent(record).is_none()
+ && meta.and_then(|value| value.get("modelSystem")).is_none()
+ && meta.and_then(|value| value.get("sessionMessage")).is_none()
+ {
+ current = Some(turns.len());
+ let title: String = record
+ .blocks
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter(|block| field(block, "type") == Some("text"))
+ .filter_map(|block| field(block, "text"))
+ .flat_map(str::chars)
+ .take(80)
+ .collect();
+ turns.push(Turn {
+ position: index,
+ id: record.id.clone(),
+ created_at: record.created_at.clone(),
+ title,
+ changes: Vec::new(),
+ snapshots: HashSet::new(),
+ });
+ if let Some(turn) = indexed.get(&record.id) {
+ turn_users.entry(turn.clone()).or_insert(turns.len() - 1);
+ }
+ }
+ fallback.push(current);
+ if let Some(call) = tool_block(record).and_then(|block| field(block, "callId")) {
+ calls.entry(call.to_owned()).or_insert(index);
+ }
+ }
+ let mut seen = HashSet::new();
+ for (index, record) in records.iter().enumerate() {
+ if record.role != "tool" || record.is_error {
+ continue;
+ }
+ let Some(block) = tool_block(record) else {
+ continue;
+ };
+ if !matches!(
+ record.tool_name.as_deref().or_else(|| field(block, "name")),
+ Some("Write" | "Edit")
+ ) || field(block, "status") != Some("success")
+ || block.get("isError").and_then(Value::as_bool) == Some(true)
+ || block.pointer("/result/isError").and_then(Value::as_bool) == Some(true)
+ || block
+ .pointer("/result/details/root")
+ .and_then(Value::as_str)
+ .is_none_or(|root| {
+ !matches!(root, "workspace" | "scratch" | "external" | "visualization")
+ })
+ {
+ continue;
+ }
+ let Some(turn) = owner(index, &records, &calls, &indexed, &turn_users, &fallback) else {
+ continue;
+ };
+ for raw in reviews(block) {
+ if let Some((snapshot, projected)) =
+ project(db, session_id, record, block, raw, workspace_root)?
+ {
+ if seen.insert(snapshot.clone()) {
+ turns[turn].snapshots.insert(snapshot);
+ turns[turn].changes.push(projected);
+ }
+ }
+ }
+ }
+ Ok(turns
+ .into_iter()
+ .filter(|turn| !turn.changes.is_empty())
+ .collect())
+}
+
+pub(crate) fn execute(
+ db: &Database,
+ method: &str,
+ request: Request,
+ workspace_root: Option<&Path>,
+) -> Result<Value> {
+ if method == "review.context" {
+ return context::load(
+ db.data_dir(),
+ &request.session_id,
+ request
+ .snapshot_id
+ .as_deref()
+ .ok_or_else(|| anyhow!("snapshotId required"))?,
+ request.context.ok_or_else(|| anyhow!("context required"))?,
+ );
+ }
+ let turns = collect(db, &request.session_id, workspace_root)?;
+ let limit = request.limit.unwrap_or(50).clamp(1, 100) as usize;
+ if method == "review.turns" {
+ let eligible: Vec<_> = turns
+ .iter()
+ .rev()
+ .filter(|turn| {
+ request
+ .before
+ .is_none_or(|before| (turn.position as i64) < before)
+ })
+ .collect();
+ let page: Vec<_> = eligible
+ .iter()
+ .take(limit)
+ .map(|turn| {
+ json!({
+ "id": turn.id, "userMessageId": turn.id, "createdAt": turn.created_at,
+ "title": turn.title, "changeCount": turn.changes.len()
+ })
+ })
+ .collect();
+ let mut result = json!({ "turns": page });
+ if eligible.len() > limit {
+ result["nextBefore"] = json!(eligible[limit - 1].position);
+ }
+ return Ok(result);
+ }
+ let selected = turns.iter().rev().find(|turn| {
+ request.turn_id.as_ref().is_none_or(|id| id == &turn.id)
+ && request
+ .snapshot_id
+ .as_ref()
+ .is_none_or(|id| turn.snapshots.contains(id))
+ });
+ let Some(turn) = selected else {
+ return Ok(json!({ "turnId": null, "changes": [] }));
+ };
+ let offset = request.offset.unwrap_or(0) as usize;
+ let changes: Vec<_> = turn.changes.iter().skip(offset).take(limit).collect();
+ let mut result = json!({ "turnId": turn.id, "changes": changes });
+ if offset.saturating_add(limit) < turn.changes.len() {
+ result["nextOffset"] = json!(offset + limit);
+ }
+ Ok(result)
+}
+
+/// Select an entire file from the anchor's owning round using authoritative evidence.
+pub(super) fn file_evidence(
+ db: &Database,
+ session_id: &str,
+ snapshot: &str,
+ workspace_root: Option<&Path>,
+) -> Result<Vec<ReviewChange>> {
+ for turn in collect(db, session_id, workspace_root)? {
+ let reviews: Vec<ReviewChange> = turn
+ .changes
+ .iter()
+ .map(|row| {
+ serde_json::from_value(
+ row.pointer("/message/toolResult/details/review")
+ .cloned()
+ .unwrap_or(Value::Null),
+ )
+ })
+ .collect::<std::result::Result<_, _>>()?;
+ if let Some(anchor) = reviews.iter().find(|change| change.snapshot_id == snapshot) {
+ let path = anchor.path.clone();
+ let root = anchor.root.clone();
+ return Ok(reviews
+ .into_iter()
+ .filter(|change| change.path == path && change.root == root)
+ .collect());
+ }
+ }
+ Err(anyhow!("review snapshot is not in the session transcript"))
+}
+
+/// Legacy delegate records have no trustworthy execution root. Keep the card
+/// readable, but never restore those bytes into the parent session workspace.
+pub(crate) fn rollback(
+ db: &Database,
+ session_id: &str,
+ snapshot_id: &str,
+ workspace_root: Option<&Path>,
+) -> Result<RollbackOutcome> {
+ let meta = read_meta(db.data_dir(), session_id, snapshot_id)?;
+ if meta.root.is_none() {
+ let records = transcripts::read_transcript(db.data_dir(), session_id)?;
+ if records
+ .iter()
+ .filter(|record| parent(record).is_some())
+ .any(|record| {
+ tool_block(record).is_some_and(|block| {
+ reviews(block)
+ .iter()
+ .any(|review| field(review, "snapshotId") == Some(snapshot_id))
+ })
+ })
+ {
+ return Ok(RollbackOutcome {
+ status: "unavailable",
+ snapshot_id: snapshot_id.into(),
+ message_id: meta.message_id,
+ path: meta.path,
+ });
+ }
+ }
+ rollback_change(db.data_dir(), session_id, snapshot_id, workspace_root)
+}
diff --git a/crates/host-core/src/review/trim_tests.rs b/crates/host-core/src/review/trim_tests.rs
new file mode 100644
index 000000000..1b4437937
--- /dev/null
+++ b/crates/host-core/src/review/trim_tests.rs
@@ -0,0 +1,134 @@
+use super::*;
+use serde_json::json;
+use tempfile::tempdir;
+
+#[test]
+fn trimmed_large_file_local_edit_preserves_context_coordinates_and_snapshot() {
+ let data = tempdir().unwrap();
+ let root = tempdir().unwrap();
+ let target = root.path().join("large.ts");
+ let before: String = (0..3100)
+ .map(|i| format!("const line_{i} = {i};\n"))
+ .collect();
+ let after = before.replace("const line_2200 = 2200;\n", "const line_2200 = 9999;\n");
+ fs::write(&target, &before).unwrap();
+ let pending = prepare_change(
+ data.path(),
+ "session",
+ "message",
+ Some(root.path()),
+ &ContainedRoots::new(),
+ "Edit",
+ &json!({"path":"large.ts"}),
+ false,
+ )
+ .unwrap()
+ .unwrap();
+ fs::write(&target, &after).unwrap();
+ let change = finalize_change(&pending).unwrap();
+ assert!(
+ !change.truncated,
+ "unchanged file head/tail must not consume quadratic budget"
+ );
+ assert_eq!((change.additions, change.deletions), (1, 1));
+ assert_eq!(change.hunks[0].header, "@@ -2198,7 +2198,7 @@");
+ fs::remove_file(&target).unwrap();
+ for radius in [1, 3, 5] {
+ let saved = context::load(data.path(), "session", &change.snapshot_id, radius).unwrap();
+ assert!(saved.get("unavailable").is_none());
+ assert_eq!(
+ saved["hunks"][0]["header"],
+ format!(
+ "@@ -{},{} +{},{} @@",
+ 2201 - radius,
+ 2 * radius + 1,
+ 2201 - radius,
+ 2 * radius + 1
+ )
+ );
+ assert!(saved.to_string().contains("9999"));
+ assert!(!saved.to_string().contains("line_0 ="));
+ }
+ assert!(!pending.snapshot_dir.join("after").exists());
+}
+
+#[test]
+fn trimmed_edges_empty_and_repeated_lines_reconstruct_exact_inputs() {
+ let base = vec!["same".to_owned(); 3000];
+ let mut cases = vec![
+ (base.clone(), base.clone()),
+ (Vec::new(), base.clone()),
+ (base.clone(), Vec::new()),
+ ];
+ for position in [0, 1500, 3000] {
+ let mut added = base.clone();
+ added.insert(position, "inserted".into());
+ cases.push((base.clone(), added.clone()));
+ cases.push((added, base.clone()));
+ }
+ for (before, after) in cases {
+ let ops =
+ diff_ops(&before, &after).expect("small changed middle fits the unchanged budget");
+ let restored_before: Vec<_> = ops
+ .iter()
+ .filter_map(|op| match op {
+ DiffOp::Equal(text) | DiffOp::Del(text) => Some(text.clone()),
+ _ => None,
+ })
+ .collect();
+ let restored_after: Vec<_> = ops
+ .iter()
+ .filter_map(|op| match op {
+ DiffOp::Equal(text) | DiffOp::Add(text) => Some(text.clone()),
+ _ => None,
+ })
+ .collect();
+ assert_eq!(restored_before, before);
+ assert_eq!(restored_after, after);
+ let (adds, dels) = line_counts(&ops);
+ assert_eq!(adds, after.len().saturating_sub(before.len()));
+ assert_eq!(dels, before.len().saturating_sub(after.len()));
+ }
+}
+
+#[test]
+fn trimmed_small_sequences_preserve_minimal_change_counts() {
+ let sequences: Vec<Vec<String>> = (0..5)
+ .flat_map(|len| {
+ (0..1_usize << len).map(move |bits| {
+ (0..len)
+ .map(|index| {
+ if bits & (1 << index) == 0 {
+ "a".into()
+ } else {
+ "b".into()
+ }
+ })
+ .collect()
+ })
+ })
+ .collect();
+ for before in &sequences {
+ for after in &sequences {
+ let trimmed = diff_ops(before, after).unwrap();
+ assert_eq!(
+ line_counts(&trimmed),
+ line_counts(&diff_middle(before, after).unwrap())
+ );
+ }
+ }
+}
+
+#[test]
+fn trimmed_middle_still_obeys_original_cell_budget() {
+ let before: Vec<_> = (0..1600).map(|i| format!("before {i}")).collect();
+ let after: Vec<_> = (0..1600).map(|i| format!("after {i}")).collect();
+ assert!(diff_ops(&before, &after).is_none());
+ let mut padded_before = vec!["common head".into(); 1000];
+ padded_before.extend(before);
+ padded_before.extend(vec!["common tail".into(); 1000]);
+ let mut padded_after = vec!["common head".into(); 1000];
+ padded_after.extend(after);
+ padded_after.extend(vec!["common tail".into(); 1000]);
+ assert!(diff_ops(&padded_before, &padded_after).is_none());
+}
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 49958a549..b2aec4b9a 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -3,6 +3,7 @@ mod file_batches;
mod gen_ui;
mod plugin_reviews_rpc;
mod remote_tools;
+mod review_actions_rpc;
mod scheduled_rpc;
mod scheduled_tools;
mod todos;
@@ -12,6 +13,8 @@ mod worktree_rpc;
#[cfg(test)]
mod plugin_reviews_rpc_tests;
#[cfg(test)]
+mod review_rpc_tests;
+#[cfg(test)]
mod visualization_tests;
use std::io::{self, BufRead, BufReader as StdBufReader, Read, Write};
@@ -2353,6 +2356,24 @@ async fn handle_request(
.map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
Ok(json!({ "ok": true }))
}
+ "review.turns" | "review.changes" | "review.context" => {
+ let request = review::query::Request::parse(method, params)
+ .map_err(|error| rpc_err(1002, error.to_string(), "INVALID_PARAMS"))?;
+ let st = state.lock().await;
+ if remote_tools::session_remote_workspace(&st, &request.session_id)?.is_some() {
+ return Err(rpc_err(
+ 1002,
+ "remote workspace review is unavailable",
+ "CAPABILITY_UNAVAILABLE",
+ ));
+ }
+ let root = resolve_tool_workspace(&st, &request.session_id)?;
+ review::query::execute(&st.db, method, request, root.as_deref().map(Path::new))
+ .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))
+ }
+ "review.fileTarget" | "review.rollbackFile" => {
+ review_actions_rpc::handle(&state, method, params).await
+ }
"review.rollback" => {
let session_id = params
.get("sessionId")
@@ -2362,54 +2383,23 @@ async fn handle_request(
.get("snapshotId")
.and_then(|value| value.as_str())
.ok_or_else(|| rpc_err(1002, "snapshotId required", "INVALID_PARAMS"))?;
- let budget = {
- let st = state.lock().await;
- if remote_tools::session_remote_workspace(&st, session_id)?.is_some() {
- return Err(rpc_err(
- 1002,
- "remote workspace rollback is unavailable",
- "CAPABILITY_UNAVAILABLE",
- ));
- }
- st.tool_budget.clone()
- };
- let permit = Arc::new(
- budget
- .acquire_files(
- session_id,
- "Write",
- false,
- crate::file_resources::FileResources::fence(true),
- None,
- )
- .await
- .map_err(|e| rpc_err(1000, e.message(), e.code()))?,
- );
- let _rollback_lease = permit.clone();
- let (data_dir, workspace_root) = {
- let st = state.lock().await;
- // Session/worktree state may have changed while admission waited.
- (
- st.data_dir.clone(),
- resolve_tool_workspace(&st, session_id)?,
- )
- };
- let session = session_id.to_string();
- let snapshot = snapshot_id.to_string();
- let root = workspace_root.clone();
- let outcome = tokio::task::spawn_blocking(move || {
- let _permit = permit;
- review::rollback_change(
- &data_dir,
- &session,
- &snapshot,
- root.as_deref().map(Path::new),
- )
- })
- .await
- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
+ let _rollback_lease = review_actions_rpc::rollback_permit(&state, session_id).await?;
let st = state.lock().await;
+ if remote_tools::session_remote_workspace(&st, session_id)?.is_some() {
+ return Err(rpc_err(
+ 1002,
+ "remote workspace rollback is unavailable",
+ "CAPABILITY_UNAVAILABLE",
+ ));
+ }
+ let workspace_root = resolve_tool_workspace(&st, session_id)?;
+ let outcome = review::query::rollback(
+ &st.db,
+ session_id,
+ snapshot_id,
+ workspace_root.as_deref().map(Path::new),
+ )
+ .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?;
if matches!(outcome.status, "rolledBack" | "alreadyRolledBack") {
if let Some(root) = workspace_root.as_deref() {
let resolved = std::path::Path::new(root).join(&outcome.path);
@@ -4651,6 +4641,7 @@ async fn handle_request(
&local_contained_roots(&data_dir, &p.session_id, false),
&p.tool_name,
&p.args,
+ external_path_permission,
)
.unwrap_or_else(|error| {
tracing::warn!(
diff --git a/crates/host-core/src/rpc/review_actions_rpc.rs b/crates/host-core/src/rpc/review_actions_rpc.rs
new file mode 100644
index 000000000..c095d61c3
--- /dev/null
+++ b/crates/host-core/src/rpc/review_actions_rpc.rs
@@ -0,0 +1,97 @@
+//! Session-owned explicit file actions, separate from read projections.
+use super::*;
+
+pub(super) async fn handle(
+ state: &Arc<Mutex<AppState>>,
+ method: &str,
+ params: Value,
+) -> Result<Value, JsonRpcError> {
+ let session = params
+ .get("sessionId")
+ .and_then(Value::as_str)
+ .filter(|id| !id.is_empty())
+ .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
+ let snapshot = params
+ .get("snapshotId")
+ .and_then(Value::as_str)
+ .filter(|id| !id.is_empty())
+ .ok_or_else(|| rpc_err(1002, "snapshotId required", "INVALID_PARAMS"))?;
+ let _rollback_lease = if method == "review.rollbackFile" {
+ Some(rollback_permit(state, session).await?)
+ } else {
+ None
+ };
+ let st = state.lock().await;
+ if remote_tools::session_remote_workspace(&st, session)?.is_some() {
+ return Err(rpc_err(
+ 1002,
+ "remote review file actions are unavailable",
+ "CAPABILITY_UNAVAILABLE",
+ ));
+ }
+ let root = resolve_tool_workspace(&st, session)?;
+ if method == "review.fileTarget" {
+ return review::file_actions::file_target(
+ &st.db,
+ session,
+ snapshot,
+ root.as_deref().map(Path::new),
+ )
+ .map_err(|error| rpc_err(1002, error.to_string(), "INVALID_ARGUMENT"));
+ }
+ let result = review::file_actions::rollback_file(
+ &st.db,
+ session,
+ snapshot,
+ root.as_deref().map(Path::new),
+ )
+ .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?;
+ if result.status == "rolledBack" {
+ for change in &result.changes {
+ if let Some(root) = &root {
+ let target = Path::new(root).join(&change.path);
+ st.hashline
+ .invalidate_path(session, &crate::tools::hashline::canonical_key(&target));
+ }
+ sessions::update_tool_review_state(
+ &st.db,
+ session,
+ &change.message_id,
+ &change.snapshot_id,
+ "rolledBack",
+ )
+ .map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))?;
+ }
+ }
+ serde_json::to_value(result).map_err(|error| rpc_err(1000, error.to_string(), "INTERNAL"))
+}
+
+/// Rollback participates in the same Host file resource exclusion as tools.
+/// Never hold AppState while waiting; roots are resolved again after admission.
+pub(super) async fn rollback_permit(
+ state: &Arc<Mutex<AppState>>,
+ session: &str,
+) -> Result<Arc<crate::tool_budget::ToolPermit>, JsonRpcError> {
+ let budget = {
+ let st = state.lock().await;
+ if remote_tools::session_remote_workspace(&st, session)?.is_some() {
+ return Err(rpc_err(
+ 1002,
+ "remote workspace rollback is unavailable",
+ "CAPABILITY_UNAVAILABLE",
+ ));
+ }
+ st.tool_budget.clone()
+ };
+ budget
+ .acquire_files(
+ session,
+ "Write",
+ false,
+ crate::file_resources::FileResources::fence(true),
+ None,
+ )
+ .await
+ .map(Arc::new)
+ .map_err(|error| rpc_err(1000, error.message(), error.code()))
+}
diff --git a/crates/host-core/src/rpc/review_rpc_tests.rs b/crates/host-core/src/rpc/review_rpc_tests.rs
new file mode 100644
index 000000000..d633a056b
--- /dev/null
+++ b/crates/host-core/src/rpc/review_rpc_tests.rs
@@ -0,0 +1,774 @@
+use super::*;
+use crate::review::{finalize_change, prepare_change, ReviewChange};
+use tempfile::{tempdir, TempDir};
+
+struct Fixture {
+ data: TempDir,
+ root: TempDir,
+ session: String,
+ state: Arc<Mutex<AppState>>,
+}
+
+impl Fixture {
+ async fn new() -> Self {
+ let data = tempdir().unwrap();
+ let root = tempdir().unwrap();
+ let mut app = AppState::open(data.path()).unwrap();
+ app.handshook = true;
+ let state = Arc::new(Mutex::new(app));
+ let result = handle_request(
+ state.clone(),
+ "session.create",
+ json!({"mode":"agent", "projectPath":root.path().to_string_lossy()}),
+ mpsc::unbounded_channel().0,
+ )
+ .await
+ .unwrap();
+ let session = result["id"]
+ .as_str()
+ .or_else(|| result["session"]["id"].as_str())
+ .unwrap()
+ .to_owned();
+ Self {
+ data,
+ root,
+ session,
+ state,
+ }
+ }
+
+ async fn call(&self, method: &str, mut params: Value) -> Value {
+ params["sessionId"] = json!(self.session);
+ handle_request(
+ self.state.clone(),
+ method,
+ params,
+ mpsc::unbounded_channel().0,
+ )
+ .await
+ .unwrap()
+ }
+
+ async fn append(&self, message: Value, turn: Option<&str>) {
+ self.call(
+ "session.appendMessage",
+ json!({"message":message, "turnId":turn}),
+ )
+ .await;
+ }
+
+ async fn user(&self, id: &str, turn: Option<&str>) {
+ self.append(
+ json!({"id":id,"role":"user","content":format!("Prompt {id} {}", "界".repeat(90)),
+ "createdAt":"2026-10-20T00:00:00Z"}),
+ turn,
+ )
+ .await;
+ }
+
+ fn capture(&self, root: &Path, id: &str, text: &str) -> ReviewChange {
+ let target = root.join("file.txt");
+ let pending = prepare_change(
+ self.data.path(),
+ &self.session,
+ id,
+ Some(root),
+ &ContainedRoots::new(),
+ "Write",
+ &json!({"path":"file.txt"}),
+ false,
+ )
+ .unwrap()
+ .unwrap();
+ std::fs::write(target, text).unwrap();
+ finalize_change(&pending).unwrap()
+ }
+
+ async fn tool(&self, id: &str, review: Value, parent: Option<&str>, turn: Option<&str>) {
+ self.append(json!({"id":id,"role":"tool","content":"large tool body must not cross IPC",
+ "createdAt":"2026-10-20T00:00:01Z", "toolName":"Write", "toolCallId":format!("call-{id}"),
+ "toolStatus":"success", "toolArgs":{"path":"file.txt","content":"private input body"},
+ "parentToolCallId":parent, "toolResult":{"content":[{"type":"text","text":"raw result body"}],
+ "details":{"root":"workspace", "review":review}}}), turn).await;
+ }
+
+ async fn indexed_turn(&self, id: &str) {
+ self.state.lock().await.db.conn().execute(
+ "INSERT INTO turns (id, session_id, status, started_at) VALUES (?1, ?2, 'completed', 1)",
+ rusqlite::params![id, self.session]).unwrap();
+ }
+}
+
+#[tokio::test]
+async fn review_rpc_latest_turn_late_delegate_dedup_roots_and_restart() {
+ let mut f = Fixture::new().await;
+ f.indexed_turn("turn-one").await;
+ f.indexed_turn("turn-two").await;
+ f.user("u1", Some("turn-one")).await;
+ f.append(
+ json!({"id":"task","role":"tool","content":"","createdAt":"2026-10-20T00:00:00Z",
+ "toolName":"Task","toolCallId":"task-call","toolStatus":"success"}),
+ Some("turn-one"),
+ )
+ .await;
+ let first = f.capture(f.root.path(), "first", "one\n");
+ f.tool("first", json!(first), None, Some("turn-one")).await;
+ f.user("u2", Some("turn-two")).await;
+ let second = f.capture(f.root.path(), "second", "two\n");
+ f.tool("second", json!(second), None, Some("turn-two"))
+ .await;
+ // A different checkout, same relative path; parent Task, not arrival time
+ // or the accidentally inherited turn-two index, owns this late result.
+ let delegate = tempdir().unwrap();
+ let late = f.capture(delegate.path(), "late", "delegate\n");
+ f.tool("late", json!(late), Some("task-call"), Some("turn-two"))
+ .await;
+ f.tool("duplicate", json!(late), Some("task-call"), None)
+ .await;
+ // Non-delegate terminal results also honor their durable turn_id index.
+ let old = f.capture(f.root.path(), "old-result", "old result\n");
+ f.tool("old-result", json!(old), None, Some("turn-one"))
+ .await;
+ f.user("no-changes", None).await;
+ assert_eq!(f.call("review.changes", json!({})).await["turnId"], "u2");
+ let page = f.call("review.turns", json!({"limit":1})).await;
+ assert_eq!(page["turns"][0]["id"], "u2");
+ assert_eq!(page["turns"][0]["userMessageId"], "u2");
+ assert_eq!(
+ page["turns"][0]["title"].as_str().unwrap().chars().count(),
+ 80
+ );
+ let older = f
+ .call(
+ "review.turns",
+ json!({"before":page["nextBefore"],"limit":1}),
+ )
+ .await;
+ assert_eq!(older["turns"][0]["id"], "u1");
+ assert_eq!(older["turns"][0]["changeCount"], 3);
+ assert!(older.get("nextBefore").is_none());
+ let changes = f
+ .call("review.changes", json!({"snapshotId":late.snapshot_id}))
+ .await;
+ assert_eq!(changes["turnId"], "u1");
+ assert_eq!(changes["changes"].as_array().unwrap().len(), 3);
+ assert_ne!(changes["changes"][0]["root"], changes["changes"][1]["root"]);
+ assert_eq!(
+ changes["changes"][1]["message"]["parentToolCallId"],
+ "task-call"
+ );
+ assert_eq!(
+ changes["changes"][1]["message"]["toolResult"]["details"]["review"]["reversible"],
+ false
+ );
+ assert!(!changes.to_string().contains("private input body"));
+ assert!(!changes.to_string().contains("raw result body"));
+ assert!(!changes.to_string().contains("large tool body"));
+ assert_eq!(
+ f.call("review.changes", json!({"snapshotId":"absent"}))
+ .await,
+ json!({"turnId":null,"changes":[]})
+ );
+ assert_eq!(
+ f.call("review.changes", json!({"turnId":"no-changes"}))
+ .await,
+ json!({"turnId":null,"changes":[]})
+ );
+ assert_eq!(
+ f.call("review.rollback", json!({"snapshotId":late.snapshot_id}))
+ .await["status"],
+ "unavailable"
+ );
+ let previous = f.call("review.turns", json!({})).await;
+ let mut app = AppState::open(f.data.path()).unwrap();
+ app.handshook = true;
+ f.state = Arc::new(Mutex::new(app));
+ assert_eq!(f.call("review.turns", json!({})).await, previous);
+ assert_eq!(
+ f.call("review.changes", json!({"snapshotId":late.snapshot_id}))
+ .await,
+ changes
+ );
+ assert!(f
+ .call(
+ "review.context",
+ json!({"snapshotId":second.snapshot_id,"context":3})
+ )
+ .await["hunks"]
+ .is_array());
+}
+
+#[tokio::test]
+async fn review_rpc_pages_over_a_hundred_turns_and_changes_without_tool_bodies() {
+ let f = Fixture::new().await;
+ for i in 0..105 {
+ f.user(&format!("u{i}"), None).await;
+ let review = f.capture(f.root.path(), &format!("m{i}"), &format!("version {i}\n"));
+ f.tool(&format!("m{i}"), json!(review), None, None).await;
+ }
+ let page = f.call("review.turns", json!({"limit":999})).await;
+ assert_eq!(page["turns"].as_array().unwrap().len(), 100);
+ assert_eq!(page["turns"][0]["id"], "u104");
+ let tail = f
+ .call(
+ "review.turns",
+ json!({"before":page["nextBefore"],"limit":100}),
+ )
+ .await;
+ assert_eq!(tail["turns"].as_array().unwrap().len(), 5);
+ assert_eq!(tail["turns"][4]["id"], "u0");
+ f.user("many", None).await;
+ for i in 0..105 {
+ let id = format!("many-{i}");
+ let review = f.capture(f.root.path(), &id, &format!("many {i}\n"));
+ f.tool(&id, json!(review), None, None).await;
+ }
+ let page = f.call("review.changes", json!({"limit":999})).await;
+ assert_eq!(page["turnId"], "many");
+ assert_eq!(page["changes"].as_array().unwrap().len(), 100);
+ assert_eq!(page["nextOffset"], 100);
+ let tail = f
+ .call(
+ "review.changes",
+ json!({"turnId":"many","offset":page["nextOffset"],"limit":100}),
+ )
+ .await;
+ assert_eq!(tail["changes"].as_array().unwrap().len(), 5);
+ assert_eq!(tail["changes"][4]["message"]["id"], "many-104");
+ assert!(tail.get("nextOffset").is_none());
+ assert_eq!(
+ f.call("review.changes", json!({"limit":0})).await["changes"]
+ .as_array()
+ .unwrap()
+ .len(),
+ 1
+ );
+}
+
+#[tokio::test]
+async fn review_rpc_filters_invalid_evidence_and_marks_oversized_hunks() {
+ let f = Fixture::new().await;
+ f.user("u", None).await;
+ let review = f.capture(f.root.path(), "valid", "changed\n");
+ for (id, patch) in [
+ ("failed", json!({"toolStatus":"error"})),
+ (
+ "unknown-root",
+ json!({"toolResult":{"details":{"root":"unknown","review":review}}}),
+ ),
+ ("read", json!({"toolName":"Read"})),
+ (
+ "invalid",
+ json!({"toolResult":{"details":{"root":"workspace","review":{"snapshotId":"bad"}}}}),
+ ),
+ ] {
+ let mut message = json!({"id":id,"role":"tool","content":"","createdAt":"2026-10-20T00:00:00Z",
+ "toolName":"Write","toolStatus":"success","toolCallId":id,
+ "toolResult":{"details":{"root":"workspace","review":review}}});
+ for (key, value) in patch.as_object().unwrap() {
+ message[key] = value.clone();
+ }
+ f.append(message, None).await;
+ }
+ assert_eq!(f.call("review.turns", json!({})).await, json!({"turns":[]}));
+ let mut large = json!(review);
+ large["hunks"] =
+ json!([{"header":"@@ -1,1 +1,1 @@","lines":[{"type":"add","text":"x".repeat(100_000)}]}]);
+ f.tool("valid", large, None, None).await;
+ let result = f.call("review.changes", json!({})).await;
+ assert_eq!(result["changes"].as_array().unwrap().len(), 1);
+ assert_eq!(
+ result["changes"][0]["message"]["toolResult"]["details"]["review"]["truncated"],
+ true
+ );
+ assert!(serde_json::to_vec(&result).unwrap().len() < 32 * 1024);
+ let orphan = f.capture(f.root.path(), "orphan", "orphan result\n");
+ f.tool("orphan", json!(orphan), Some("missing-legacy-task"), None)
+ .await;
+ let result = f.call("review.changes", json!({})).await;
+ assert_eq!(result["changes"].as_array().unwrap().len(), 2);
+ let path = f
+ .data
+ .path()
+ .join("review-changes")
+ .join(&f.session)
+ .join(&orphan.snapshot_id)
+ .join("meta.json");
+ std::fs::remove_file(&path).unwrap();
+ let result = f.call("review.changes", json!({})).await;
+ assert_eq!(result["changes"].as_array().unwrap().len(), 2);
+ assert_eq!(
+ result["changes"][1]["message"]["toolResult"]["details"]["review"]["reversible"],
+ false
+ );
+ std::fs::write(path, b"corrupt metadata").unwrap();
+ let error = handle_request(
+ f.state.clone(),
+ "review.changes",
+ json!({"sessionId":f.session}),
+ mpsc::unbounded_channel().0,
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(error.data.unwrap()["errorCode"], "INTERNAL");
+}
+
+#[tokio::test]
+async fn review_rpc_legacy_delegate_is_read_only_but_parent_rollback_still_works() {
+ let f = Fixture::new().await;
+ f.user("u", None).await;
+ f.append(
+ json!({"id":"task","role":"tool","content":"","createdAt":"2026-10-20T00:00:00Z",
+ "toolName":"Task","toolCallId":"task-call","toolStatus":"success"}),
+ None,
+ )
+ .await;
+ let review = f.capture(f.root.path(), "legacy", "legacy\n");
+ let path = f
+ .data
+ .path()
+ .join("review-changes")
+ .join(&f.session)
+ .join(&review.snapshot_id)
+ .join("meta.json");
+ let mut meta: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
+ meta.as_object_mut().unwrap().remove("root");
+ std::fs::write(&path, serde_json::to_vec(&meta).unwrap()).unwrap();
+ let mut legacy = json!(review);
+ legacy.as_object_mut().unwrap().remove("root");
+ f.tool("legacy", legacy, Some("task-call"), None).await;
+ let result = f.call("review.changes", json!({})).await;
+ assert_eq!(result["turnId"], "u");
+ assert_eq!(
+ result["changes"][0]["message"]["toolResult"]["details"]["review"]["reversible"],
+ false
+ );
+ assert_eq!(
+ f.call("review.rollback", json!({"snapshotId":review.snapshot_id}))
+ .await["status"],
+ "unavailable"
+ );
+ let normal = f.capture(f.root.path(), "normal", "normal\n");
+ f.tool("normal", json!(normal), None, None).await;
+ for expected in ["rolledBack", "alreadyRolledBack"] {
+ assert_eq!(
+ f.call("review.rollback", json!({"snapshotId":normal.snapshot_id}))
+ .await["status"],
+ expected
+ );
+ }
+ assert_eq!(
+ std::fs::read_to_string(f.root.path().join("file.txt")).unwrap(),
+ "legacy\n"
+ );
+ let result = f
+ .call("review.changes", json!({"snapshotId":normal.snapshot_id}))
+ .await;
+ assert_eq!(
+ result["changes"][1]["message"]["toolResult"]["details"]["review"]["state"],
+ "rolledBack"
+ );
+}
+
+#[tokio::test]
+async fn review_rpc_rejects_invalid_parameters_and_missing_sessions() {
+ let f = Fixture::new().await;
+ for (method, params) in [
+ (
+ "review.context",
+ json!({"sessionId":f.session,"snapshotId":"snapshot","context":0}),
+ ),
+ (
+ "review.context",
+ json!({"sessionId":f.session,"snapshotId":"../escape","context":3}),
+ ),
+ ("review.changes", json!({"sessionId":f.session,"offset":-1})),
+ (
+ "review.turns",
+ json!({"sessionId":f.session,"before":"bad"}),
+ ),
+ ("review.turns", json!({})),
+ ] {
+ let error = handle_request(f.state.clone(), method, params, mpsc::unbounded_channel().0)
+ .await
+ .unwrap_err();
+ assert_eq!(error.data.unwrap()["errorCode"], "INVALID_PARAMS");
+ }
+ let error = handle_request(
+ f.state.clone(),
+ "review.turns",
+ json!({"sessionId":"missing"}),
+ mpsc::unbounded_channel().0,
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(error.data.unwrap()["errorCode"], "SESSION_NOT_FOUND");
+}
+
+#[tokio::test]
+async fn review_rpc_remote_boundary_and_newline_only_records() {
+ let f = Fixture::new().await;
+ f.user("u", None).await;
+ f.append(
+ json!({"id":"task","role":"tool","content":"","createdAt":"2026-10-20T00:00:00Z",
+ "toolName":"Task","toolCallId":"task-call","toolStatus":"success"}),
+ None,
+ )
+ .await;
+ f.user("later-user", None).await;
+ std::fs::write(f.root.path().join("file.txt"), "unchanged").unwrap();
+ let review = f.capture(f.root.path(), "newline", "unchanged\n");
+ assert!(review.hunks.is_empty()); // Preserve the old three-line record.
+ f.tool("newline", json!([review, review]), Some("task-call"), None)
+ .await;
+ assert_eq!(
+ f.call("review.turns", json!({})).await["turns"][0]["id"],
+ "u"
+ );
+ assert_eq!(
+ f.call("review.turns", json!({})).await["turns"][0]["changeCount"],
+ 1
+ );
+ let expanded = f
+ .call(
+ "review.context",
+ json!({"snapshotId":review.snapshot_id,"context":1}),
+ )
+ .await;
+ assert!(expanded.to_string().contains("No newline"));
+ let group = f
+ .state
+ .lock()
+ .await
+ .db
+ .create_remote_project_group(
+ "Remote",
+ crate::db::RemoteWorkspace {
+ host_key: "test-host".into(),
+ path: "/workspace/project".into(),
+ },
+ )
+ .unwrap();
+ let remote = handle_request(
+ f.state.clone(),
+ "session.create",
+ json!({"projectPath":group.primary_path}),
+ mpsc::unbounded_channel().0,
+ )
+ .await
+ .unwrap();
+ let id = remote["session"]["id"]
+ .as_str()
+ .or_else(|| remote["id"].as_str())
+ .unwrap();
+ for method in [
+ "review.turns",
+ "review.changes",
+ "review.context",
+ "review.rollback",
+ "review.fileTarget",
+ "review.rollbackFile",
+ ] {
+ let error = handle_request(
+ f.state.clone(),
+ method,
+ json!({"sessionId":id,"snapshotId":"snapshot","context":3}),
+ mpsc::unbounded_channel().0,
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(error.data.unwrap()["errorCode"], "CAPABILITY_UNAVAILABLE");
+ }
+}
+
+#[tokio::test]
+async fn review_file_rollback_preflights_chain_and_restores_once() {
+ for conflict in [false, true] {
+ let f = Fixture::new().await;
+ f.user("file-round", None).await;
+ std::fs::write(f.root.path().join("file.txt"), "original\n").unwrap();
+ let first = f.capture(f.root.path(), "file-first", "one\n");
+ f.tool("file-first", json!(first), None, None).await;
+ let second = f.capture(f.root.path(), "file-second", "two\n");
+ f.tool("file-second", json!(second), None, None).await;
+ if conflict {
+ std::fs::write(f.root.path().join("file.txt"), "user edit\n").unwrap();
+ }
+ let result = f
+ .call(
+ "review.rollbackFile",
+ json!({"snapshotId":first.snapshot_id}),
+ )
+ .await;
+ assert_eq!(
+ result["status"],
+ if conflict { "conflict" } else { "rolledBack" }
+ );
+ assert_eq!(
+ std::fs::read_to_string(f.root.path().join("file.txt")).unwrap(),
+ if conflict {
+ "user edit\n"
+ } else {
+ "original\n"
+ }
+ );
+ let changes = f.call("review.changes", json!({})).await;
+ for row in changes["changes"].as_array().unwrap() {
+ assert_eq!(
+ row["message"]["toolResult"]["details"]["review"]["state"],
+ if conflict { "active" } else { "rolledBack" }
+ );
+ }
+ if !conflict {
+ assert_eq!(result["changes"].as_array().unwrap().len(), 2);
+ assert_eq!(
+ f.call(
+ "review.rollbackFile",
+ json!({"snapshotId":second.snapshot_id})
+ )
+ .await["status"],
+ "alreadyRolledBack"
+ );
+ }
+ }
+}
+
+#[tokio::test]
+async fn review_file_rollback_rejects_broken_intermediate_history_without_partial_write() {
+ let f = Fixture::new().await;
+ f.user("broken-round", None).await;
+ let first = f.capture(f.root.path(), "broken-first", "one\n");
+ f.tool("broken-first", json!(first), None, None).await;
+ std::fs::write(f.root.path().join("file.txt"), "unrecorded\n").unwrap();
+ let second = f.capture(f.root.path(), "broken-second", "two\n");
+ f.tool("broken-second", json!(second), None, None).await;
+ let result = f
+ .call(
+ "review.rollbackFile",
+ json!({"snapshotId":second.snapshot_id}),
+ )
+ .await;
+ assert_eq!(result["status"], "conflict");
+ assert_eq!(
+ std::fs::read_to_string(f.root.path().join("file.txt")).unwrap(),
+ "two\n"
+ );
+}
+
+#[tokio::test]
+async fn review_file_target_is_exact_session_owned_and_rejects_replaced_paths() {
+ let f = Fixture::new().await;
+ f.user("open-round", None).await;
+ let parent = tempdir().unwrap();
+ let external = parent.path().join("external");
+ std::fs::create_dir(&external).unwrap();
+ let review = f.capture(&external, "outside-open", "current\n");
+ f.tool("outside-open", json!(review), None, None).await;
+ let result = f
+ .call(
+ "review.fileTarget",
+ json!({"snapshotId":review.snapshot_id}),
+ )
+ .await;
+ assert_eq!(
+ Path::new(result["path"].as_str().unwrap()),
+ crate::workspace::simple_canonicalize(&external.join("file.txt")).unwrap()
+ );
+ let other = Fixture::new().await;
+ assert!(handle_request(
+ other.state.clone(),
+ "review.fileTarget",
+ json!({"sessionId":other.session,"snapshotId":review.snapshot_id}),
+ mpsc::unbounded_channel().0
+ )
+ .await
+ .is_err());
+ let redirected = tempdir().unwrap();
+ std::fs::write(redirected.path().join("file.txt"), "different\n").unwrap();
+ std::fs::remove_dir_all(&external).unwrap();
+ crate::session_worktrees::test_support::link_dir(redirected.path(), &external);
+ assert!(handle_request(
+ f.state.clone(),
+ "review.fileTarget",
+ json!({"sessionId":f.session,"snapshotId":review.snapshot_id}),
+ mpsc::unbounded_channel().0
+ )
+ .await
+ .is_err());
+}
+
+#[tokio::test]
+async fn review_rpc_records_workspace_scratch_and_approved_external_write_edit() {
+ let f = Fixture::new().await;
+ f.call(
+ "session.configure",
+ json!({"id":f.session,"mode":"agent","permissionMode":"auto"}),
+ )
+ .await;
+ f.user("outside-round", None).await;
+ let outside = tempdir().unwrap();
+ let scratch = crate::scratch::session_dir(f.data.path(), &f.session).unwrap();
+ std::fs::create_dir_all(&scratch).unwrap();
+ let targets = [
+ ("workspace", f.root.path().join("same.txt")),
+ ("scratch", scratch.join("same.txt")),
+ ("external", outside.path().join("same.txt")),
+ ];
+ for (index, (kind, target)) in targets.iter().enumerate() {
+ let id = format!("write-{index}");
+ let write = f.call("tools.execute", json!({"toolCallId":id,"toolName":"Write","args":{"path":target.to_string_lossy(),"content":"before\n"},"mode":"agent"})).await;
+ assert_eq!(write["ok"], true, "{write}");
+ assert_eq!(write["content"]["root"], *kind);
+ let review = &write["content"]["review"];
+ assert!(
+ review.is_object(),
+ "successful {kind} Write must carry review: {write}"
+ );
+ let expected = if *kind == "workspace" {
+ "same.txt".into()
+ } else {
+ crate::workspace::simple_canonicalize(target)
+ .unwrap()
+ .to_string_lossy()
+ .replace('\\', "/")
+ };
+ assert_eq!(review["path"], expected);
+ assert_eq!(review["reversible"], *kind == "workspace");
+ f.append(json!({"id":id,"role":"tool","content":"","createdAt":"2026-10-20T00:00:01Z","toolName":"Write","toolCallId":id,"toolStatus":"success","toolResult":{"details":write["content"]}}),None).await;
+ let edit_id = format!("edit-{index}");
+ let edit = f.call("tools.execute", json!({"toolCallId":edit_id,"toolName":"Edit","args":{"path":target.to_string_lossy(),"tag":write["content"]["tag"],"ops":"PUT 1.=1:\n+after\n"},"mode":"agent"})).await;
+ assert_eq!(edit["ok"], true, "{edit}");
+ assert!(
+ edit["content"]["review"].is_object(),
+ "{kind} Edit must carry review: {edit}"
+ );
+ assert_eq!(edit["content"]["review"]["path"], expected);
+ let snapshot = edit["content"]["review"]["snapshotId"].as_str().unwrap();
+ let saved = f
+ .call("review.context", json!({"snapshotId":snapshot,"context":5}))
+ .await;
+ assert!(saved["hunks"].to_string().contains("before"));
+ assert!(saved["hunks"].to_string().contains("after"));
+ f.append(json!({"id":edit_id,"role":"tool","content":"","createdAt":"2026-10-20T00:00:02Z","toolName":"Edit","toolCallId":edit_id,"toolStatus":"success","toolResult":{"details":edit["content"]}}),None).await;
+ if *kind != "workspace" {
+ let rollback = f
+ .call("review.rollback", json!({"snapshotId":snapshot}))
+ .await;
+ assert_eq!(
+ rollback["status"], "unavailable",
+ "snapshot never grants outside write access"
+ );
+ assert_eq!(std::fs::read_to_string(target).unwrap(), "after\n");
+ }
+ }
+ let changes = f.call("review.changes", json!({})).await;
+ assert_eq!(changes["changes"].as_array().unwrap().len(), 6);
+ for (index, (kind, _)) in targets.iter().enumerate() {
+ assert_eq!(
+ changes["changes"][index * 2]["message"]["toolResult"]["details"]["root"],
+ *kind
+ );
+ }
+ assert_eq!(
+ f.call("review.turns", json!({})).await["turns"][0]["changeCount"],
+ 6
+ );
+ let failed = f.call("tools.execute",json!({"toolCallId":"failed-edit","toolName":"Edit","args":{"path":targets[2].1.to_string_lossy(),"old_string":"missing text","new_string":"replacement"},"mode":"agent"})).await;
+ assert_eq!(failed["ok"], false);
+ assert!(failed["content"].get("review").is_none());
+ let bash = f.call("tools.execute",json!({"toolCallId":"shell-only","toolName":"Bash","args":{"command":"echo review-test"},"mode":"agent"})).await;
+ assert!(
+ bash["content"].get("review").is_none(),
+ "Bash never produces review"
+ );
+}
+
+#[tokio::test]
+async fn review_rpc_denied_external_write_never_reads_or_captures_before_approval() {
+ let f = Fixture::new().await;
+ f.call(
+ "session.configure",
+ json!({"id":f.session,"mode":"agent","permissionMode":"ask"}),
+ )
+ .await;
+ let outside = tempdir().unwrap();
+ let target = outside.path().join("outside.txt");
+ std::fs::write(&target, "untouched\n").unwrap();
+ let state = f.state.clone();
+ let params = json!({"sessionId":f.session,"toolCallId":"denied-external","toolName":"Write","args":{"path":target.to_string_lossy(),"content":"new\n"},"mode":"agent"});
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ let pending =
+ tokio::spawn(async move { handle_request(state, "tools.execute", params, tx).await });
+ let notification: Value = serde_json::from_str(&rx.recv().await.unwrap()).unwrap();
+ assert_eq!(notification["method"], "permissions.request");
+ assert!(!f
+ .data
+ .path()
+ .join("review-changes")
+ .join(&f.session)
+ .exists());
+ f.call(
+ "permissions.resolve",
+ json!({"requestId":notification["params"]["requestId"],"decision":"deny"}),
+ )
+ .await;
+ let result = pending.await.unwrap().unwrap();
+ assert_eq!(result["ok"], false);
+ assert!(result["content"].get("review").is_none());
+ assert_eq!(std::fs::read_to_string(&target).unwrap(), "untouched\n");
+ assert!(!f
+ .data
+ .path()
+ .join("review-changes")
+ .join(&f.session)
+ .exists());
+}
+
+#[tokio::test]
+async fn review_rollbacks_wait_for_active_host_file_mutations() {
+ use std::future::{poll_fn, Future};
+ use std::task::Poll;
+ for method in ["review.rollback", "review.rollbackFile"] {
+ let f = Fixture::new().await;
+ f.user("before-mutation", None).await;
+ std::fs::write(f.root.path().join("file.txt"), "before\n").unwrap();
+ let change = f.capture(f.root.path(), "captured-write", "after\n");
+ f.tool("captured-write", json!(change), None, None).await;
+ let budget = f.state.lock().await.tool_budget.clone();
+ let active = budget
+ .acquire_files(
+ "other-session",
+ "Write",
+ false,
+ crate::file_resources::FileResources::fence(true),
+ None,
+ )
+ .await
+ .unwrap();
+ let mut rollback = Box::pin(f.call(method, json!({"snapshotId":change.snapshot_id})));
+ poll_fn(|cx| {
+ assert!(
+ rollback.as_mut().poll(cx).is_pending(),
+ "rollback bypassed active file mutation: {method}"
+ );
+ if budget.snapshot().queued == 1 {
+ Poll::Ready(())
+ } else {
+ Poll::Pending
+ }
+ })
+ .await;
+ assert_eq!(
+ std::fs::read_to_string(f.root.path().join("file.txt")).unwrap(),
+ "after\n"
+ );
+ drop(active);
+ assert_eq!(rollback.await["status"], "rolledBack");
+ assert_eq!(
+ std::fs::read_to_string(f.root.path().join("file.txt")).unwrap(),
+ "before\n"
+ );
+ assert_eq!(budget.snapshot().active, 0);
+ assert_eq!(budget.snapshot().queued, 0);
+ }
+}
diff --git a/crates/host-core/src/rpc/visualization_tests.rs b/crates/host-core/src/rpc/visualization_tests.rs
index dd4827136..19cb5cc7b 100644
--- a/crates/host-core/src/rpc/visualization_tests.rs
+++ b/crates/host-core/src/rpc/visualization_tests.rs
@@ -469,8 +469,9 @@ fn visualization_paths_do_not_require_external_path_permission() {
}
#[test]
-fn visualization_writes_are_not_review_snapshotted() {
+fn visualization_writes_are_reviewed_without_granting_rollback_access() {
let f = fixture();
+ visualizations::ensure_session_root(&f.visualization).unwrap();
let roots = local_contained_roots(&f.data_dir, "s1", false);
let pending = review::prepare_change(
&f.data_dir,
@@ -480,9 +481,13 @@ fn visualization_writes_are_not_review_snapshotted() {
&roots,
"Write",
&json!({ "path": f.visualization.join("a.html").to_string_lossy() }),
+ false,
)
.unwrap();
- assert!(pending.is_none());
+ let pending = pending.expect("visualization Write is captured");
+ let change = review::finalize_change(&pending).unwrap();
+ assert!(Path::new(&change.path).is_absolute());
+ assert!(!change.reversible);
}
#[test]
diff --git a/docs/adr/0043-message-owned-review-snapshots-and-rollback.md b/docs/adr/0043-message-owned-review-snapshots-and-rollback.md
index 733f477d9..0f048a441 100644
--- a/docs/adr/0043-message-owned-review-snapshots-and-rollback.md
+++ b/docs/adr/0043-message-owned-review-snapshots-and-rollback.md
@@ -26,10 +26,12 @@ that produced it rather than to a mutable repository snapshot.
## Decision
-1. Before a workspace `Write` or `Edit`, host-core captures the previous file
- bytes in a session-scoped snapshot outside the workspace. After a successful
- tool, it writes a bounded `details.review` record into the tool result. The
- record contains the snapshot id, message/tool id, relative path, operation,
+1. After normal path authorization, before any `Write` or `Edit`, host-core
+ captures the previous file bytes in a session-scoped snapshot outside the
+ workspace. Successful workspace, scratch, visualization, and approved external
+ mutations write bounded `details.review` evidence into the tool result. The
+ record contains snapshot/message ids, a workspace-relative or otherwise
+ absolute path, operation,
added/modified/deleted status, addition/deletion counts, expandable hunks,
active/rolled-back state, and whether rollback is reversible.
2. The renderer derives `ReviewChangeCard` and the Review panel's chronological
@@ -48,9 +50,10 @@ that produced it rather than to a mutable repository snapshot.
Session deletion removes it; startup removes directories for missing
sessions. Forked transcripts retain visible diff evidence but mark rollback
unavailable because the source snapshot belongs to another session.
-5. Scratch-root writes, failed tools, and tools without a structured workspace
- path do not create review records. Large or binary files may still show
- status/count metadata while omitting hunks and rollback when the bounded
+5. Failed, denied, sensitive, or unresolvable operations do not create review
+ records. Non-workspace snapshots are readable evidence, not persistent path
+ grants, so they are non-reversible; existing file-open authorization remains
+ unchanged. Large or binary files may omit hunks and rollback when the bounded
previous content cannot be retained.
## Consequences
@@ -71,3 +74,18 @@ that produced it rather than to a mutable repository snapshot.
and the patch would be lost on restart or session reload.
- **Rollback unconditionally:** it could overwrite a user's later edit or an
external change, so the post-tool hash guard is mandatory.
+
+## Round review reader amendment
+
+The native Review panel additionally groups persisted changes by user conversation
+round and execution root/path. Latest means the newest user round with recorded
+changes, not the most recently arriving tool result. Delegate ancestry and the
+Host message-turn index preserve ownership of late results. This is a read
+projection, not a second capture store or a change to model context.
+
+New snapshots retain bounded 1/3/5-line context hunks next to the existing
+`before` rollback snapshot and optional execution-root metadata. `review.context`
+reads these immutable hunks only; no full after-image cache is created. Legacy records retain their recorded hunks and explicitly
+report unavailable expanded context. The root is provenance, not permission;
+rollback cannot use it to write into a different checkout. Existing hash guards,
+session cleanup and preview computation budgets remain in force.
diff --git a/docs/adr/0338-explicit-reviewed-file-actions.md b/docs/adr/0338-explicit-reviewed-file-actions.md
new file mode 100644
index 000000000..3e71617da
--- /dev/null
+++ b/docs/adr/0338-explicit-reviewed-file-actions.md
@@ -0,0 +1,58 @@
+# ADR 0338: Explicit actions on reviewed files
+
+- Status: Accepted
+- Date: 2026-10-30
+- Related: [ADR 0043](0043-message-owned-review-snapshots-and-rollback.md)
+
+## Context
+
+Review records approved Write/Edit operations outside the workspace, but the
+normal file-open APIs deliberately accept only project and host-owned roots.
+Widening those APIs would change unrelated filesystem authorization. Separately,
+rendering one footer per operation makes a file with several edits look like
+several independently actionable files.
+
+## Decision
+
+External open and folder reveal for a non-workspace review row use a dedicated
+main-window-only IPC request containing session ID, snapshot ID and destination.
+No renderer-supplied path is accepted. The Rust Host verifies that the snapshot
+belongs to a successful persisted tool message in that session and resolves its
+exact recorded file. Host and Main reject missing files, directories, sensitive
+paths and replacement symlinks. Main then invokes the system default application
+or reveals the file in the system file manager. This explicit user action grants
+neither directory access nor read/write capability to a tool or plugin. Generic
+`fsOpen`, `fsReveal`, permission evaluation and remote-session behavior are unchanged.
+Non-workspace file menus do not offer internal open.
+
+The Review panel renders recorded hunks continuously with one copy/rollback
+footer per file. Copy includes all recorded operations in order and does not
+claim a net diff. File rollback selects the anchor snapshot's owning round and
+file on the Host; the renderer cannot omit intermediate operations. Before one
+file restoration, Host validates the entire active hash chain, captured root,
+restoration bytes and current hash. Conflicts leave the file and record states
+untouched. Success updates each participating snapshot and transcript state.
+Existing single-snapshot rollback and inline chat actions remain unchanged.
+
+File-action menu density is opt-in. Review scope and historical round selection
+reuse the shared native Select with review-only customizable-picker styles.
+Selected fills follow the sidebar color, and only the list's outer top/bottom
+option corners are rounded. The scope trigger is 24px high and the round field
+28px; both vertically center their text and arrow. Shared primitives, Command
+shell and other selectors keep their defaults.
+
+## Consequences
+
+- Recorded external files can be opened without relaxing the general path sandbox.
+- One file has one action bar, while individual immutable snapshots remain intact.
+- Discontinuous or conflicted chains cannot be partially rolled back.
+- External snapshots remain non-reversible; explicit opening is not write permission.
+- Scope/history retain native selection behavior without changing shared defaults.
+
+## Alternatives rejected
+
+- Add snapshot roots to general filesystem roots: grants more than the clicked file.
+- Accept a raw external path from Renderer: loses binding to native recorded evidence.
+- Repeatedly call single-snapshot rollback: can stop halfway through a file's edits.
+- Merge cached hunks into a purported net diff: bounded historical hunks do not contain
+ arbitrary complete after-images, so they cannot establish that claim.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 07ca0ca51..1faffff3a 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -395,5 +395,6 @@ Each ADR includes:
| 0332 | [macOS keeps its translucent window surface with an opaque opt-out](0332-macos-opaque-window-surface.md) | Accepted (D665, amended by D666 and D667; supersedes the macOS vibrancy window backing from D348; issue #1064) |
| gen-ui-inline-visualization | [Inline generative UI visualizations](gen-ui-inline-visualization.md) | Accepted (D671) |
| 0337 | [Keep the request prefix stable across delegation settlements](0337-stable-prompt-prefix-across-delegation.md) | Accepted (supersedes ADR 0279 §9) |
+| 0338 | [Explicit actions on reviewed files](0338-explicit-reviewed-file-actions.md) | Accepted |
| model-reasoning-effort-override | [Model reasoning effort override](model-reasoning-effort-override.md) | Proposed |
diff --git a/docs/public/screenshots/review-history/review-latest.png b/docs/public/screenshots/review-history/review-latest.png
new file mode 100644
index 000000000..5c6077282
Binary files /dev/null and b/docs/public/screenshots/review-history/review-latest.png differ
diff --git a/docs/public/screenshots/review-history/review-menu.png b/docs/public/screenshots/review-history/review-menu.png
new file mode 100644
index 000000000..4e242a182
Binary files /dev/null and b/docs/public/screenshots/review-history/review-menu.png differ
diff --git a/docs/public/screenshots/review-history/review-narrow.png b/docs/public/screenshots/review-history/review-narrow.png
new file mode 100644
index 000000000..aed8c7c16
Binary files /dev/null and b/docs/public/screenshots/review-history/review-narrow.png differ
diff --git a/docs/public/screenshots/review-history/review-native-aligned.png b/docs/public/screenshots/review-history/review-native-aligned.png
new file mode 100644
index 000000000..2adbc15a1
Binary files /dev/null and b/docs/public/screenshots/review-history/review-native-aligned.png differ
diff --git a/docs/public/screenshots/review-history/review-native-history.png b/docs/public/screenshots/review-history/review-native-history.png
new file mode 100644
index 000000000..6768a7e54
Binary files /dev/null and b/docs/public/screenshots/review-history/review-native-history.png differ
diff --git a/docs/public/screenshots/review-history/review-native-scope.png b/docs/public/screenshots/review-history/review-native-scope.png
new file mode 100644
index 000000000..b85de5c00
Binary files /dev/null and b/docs/public/screenshots/review-history/review-native-scope.png differ
diff --git a/docs/public/screenshots/review-history/review-native-single-round.png b/docs/public/screenshots/review-history/review-native-single-round.png
new file mode 100644
index 000000000..ff4872156
Binary files /dev/null and b/docs/public/screenshots/review-history/review-native-single-round.png differ
diff --git a/docs/public/screenshots/review-history/review-native-themed-history.png b/docs/public/screenshots/review-history/review-native-themed-history.png
new file mode 100644
index 000000000..79333ce88
Binary files /dev/null and b/docs/public/screenshots/review-history/review-native-themed-history.png differ
diff --git a/docs/public/screenshots/review-history/review-normal.png b/docs/public/screenshots/review-history/review-normal.png
new file mode 100644
index 000000000..96ee6243d
Binary files /dev/null and b/docs/public/screenshots/review-history/review-normal.png differ
diff --git a/docs/public/screenshots/review-history/review-overview.png b/docs/public/screenshots/review-history/review-overview.png
new file mode 100644
index 000000000..808e2c775
Binary files /dev/null and b/docs/public/screenshots/review-history/review-overview.png differ
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index eb988f726..546f70f38 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -407,7 +407,8 @@ visualization lives as long as its session:
- **Permissions.** `Write`/`Edit` inside the root auto-allow without a card,
under the same conditions as scratch. Plan and Goal expose no Write/Edit, so
contract modes cannot write here. Results carry `root: "visualization"`, are
- not recorded as artifacts, and are not review-snapshotted.
+ not recorded as artifacts. Successful Write/Edit operations retain bounded
+ review evidence without granting rollback access outside the workspace.
- **Lifecycle.** Created lazily on the first write. Deleted with
`session.delete`. The startup sweep removes only safe session directories
whose session no longer exists; it never expires live cards by age or
@@ -439,9 +440,10 @@ visualization lives as long as its session:
## 4c. Message-owned review snapshots and rollback
-`Write` and `Edit` are the structured review boundary. For a successful
-workspace-root mutation, host-core captures the previous file before execution
-and adds bounded review evidence to the tool result:
+`Write` and `Edit` are the structured review boundary, regardless of whether
+their approved target is in the workspace, scratch, visualization, or external
+filesystem. After normal tool approval, host-core captures the previous file
+before execution and adds bounded review evidence only on tool success:
```ts
type ReviewChange = {
@@ -463,8 +465,11 @@ type ReviewChange = {
- The renderer persists and displays this record with the tool message; it
does not recompute Review from Git, `HEAD`, or the current dirty tree.
-- Scratch-root, failed, denied, and unresolvable writes have no `review`
- record. Binary or oversized content may omit hunks and be non-reversible.
+- Failed, denied, sensitive, and unresolvable writes have no `review` record.
+ Bash and external applications are not capture sources. Workspace paths remain
+ relative; other targets retain absolute identity and display as `.../basename`.
+ Binary or oversized content may omit hunks. Non-workspace snapshots are
+ readable evidence, not persistent path grants, and are non-reversible.
- Rollback is host-owned and hash-guarded. It restores the captured previous
bytes, or removes a newly-created file, only when the current content still
equals the post-tool hash. A later edit returns `conflict` without touching
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index 94320b4a5..41afcf859 100644
--- a/docs/spec/03-runtime/04-data-storage.md
+++ b/docs/spec/03-runtime/04-data-storage.md
@@ -250,7 +250,8 @@ This does not change the SQLite schema or transcript retention.
### 2.0 Message-owned review snapshots (ADR 0043)
-Successful workspace `Write`/`Edit` tool results carry the bounded
+Successful authorized `Write`/`Edit` tool results, including scratch,
+visualization and approved external paths, carry the bounded
`details.review` record described in [03-tools-and-permissions](03-tools-and-permissions.md).
The transcript JSONL is the durable index for the visible card; the previous
bytes and hashes live outside the workspace in
@@ -513,6 +514,16 @@ plugin's private data directory; the host settings schema does not change.
New config domains (e.g. MCP servers) start as a namespace; they graduate to
tables only when they need relations or indexes.
+#### Renderer review display preference
+
+The native Review context-line choice is stored as `1`, `3` or `5` under
+renderer localStorage key `pi.desktop.reviewContextLines`. It is shared across
+conversations and projects in the same application profile, survives panel and
+application reopening, and is not synchronized across devices. Missing, invalid
+or unreadable values fall back to 3; failed writes do not block the current
+view. Reading the preference does not rewrite storage. This presentation-only
+key does not change database schemas, transcript evidence or saved context hunks.
+
#### Renderer sidebar preferences (D093)
Sidebar organization is non-authoritative presentation state stored
@@ -2053,3 +2064,20 @@ An unknown price is distinct from a known zero price; partial known costs remain
on the individual operations. Late usage targets its captured turn and does not
revive it or debit the currently active turn. Immediate nested parent and owning
Task remain separate optional transcript/event fields.
+
+## Round review reader
+
+New native review snapshots may include a bounded `contexts.json` containing
+only 1/3/5-line context hunks and optional execution-root/context-availability
+metadata. No complete after-image or full-file context cache is written. Existing `before` bytes
+and post-tool hashes retain their rollback roles. Extended context never reads
+current workspace bytes; legacy snapshots without the preview remain readable
+and report that extended context is unavailable. No database schema change or
+second capture store is introduced; normal session-owned cleanup applies.
+
+Preview computation removes identical line prefixes/suffixes before allocating
+its LCS matrix, then reattaches those equal lines to preserve original hunk
+coordinates and finite context. The existing 512 KiB-per-image, 4000-total-lines
+per side, 2,000,000-middle-cell, and context serialization caps are unchanged.
+This affects new captures only; missing historical previews are not reconstructed
+from current disk contents.
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index afa703b3a..20eeda993 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -1521,3 +1521,37 @@ clients never supply authoritative identities. A changed workspace binding
reports TOOL_CONTEXT_CHANGED; an identity/address change fails before writing.
Close/expiry cannot release a running disk task; no failed/uncertain write is
automatically replayed. See the Host file admission ADR for lifecycle and limits.
+
+## Round review reader
+
+- `review.turns({sessionId, before?, limit?})` returns `turns` (newest user round
+ first, each with `id`, `userMessageId`, `createdAt`, `title`, `changeCount`) and
+ optional `nextBefore`. Only rounds with valid successful Write/Edit review
+ evidence are listed, including approved targets outside the workspace.
+ Source `details.root` is preserved; workspace-relative and non-workspace
+ absolute paths retain distinct identities. Limit is bounded to 100; title is a short excerpt.
+- `review.changes({sessionId, turnId?, snapshotId?, offset?, limit?})` returns
+ `turnId`, `changes: [{message, root?}]`, and optional `nextOffset`. Without a
+ selector it resolves the latest modified user round; a snapshot selector locates
+ its owning round, or returns null when absent. Transport omits unrelated tool
+ arguments and result bodies. Oversized previews are explicitly truncated, never
+ silently dropped. Parent Task ancestry and durable message-turn ownership beat
+ arrival order. Duplicate snapshots are emitted once.
+- `review.context({sessionId, snapshotId, context})` accepts only 1, 3 or 5
+ and returns `hunks`, optionally `unavailable: legacy | binary | tooLarge`.
+ Content comes only from bounded immutable context hunks, not current workspace files.
+ Normal containment, session ownership and remote-workspace capability rules apply.
+
+These reads do not replace the chat transcript window or alter execution state.
+
+`review.fileTarget({sessionId, snapshotId})` authenticates a persisted native
+snapshot in the session transcript and returns its exact existing regular file
+path. Replaced symlinks and sensitive targets are rejected. It is used only by
+Main's explicit reviewed-file open/reveal action; it is not a directory grant.
+`review.rollbackFile({sessionId, snapshotId})` selects the complete same-file
+snapshot chain in the anchor's round, returning `{status, changes}`. All active
+links and the current file are checked before one restoration; conflicts leave
+both content and states untouched. Success persists each affected review state.
+The old `review.rollback` contract remains unchanged. Both rollback methods
+participate in Host file-resource exclusion and re-resolve the session root after
+admission. Both new operations reject remote workspaces. See [ADR 0338](../../adr/0338-explicit-reviewed-file-actions.md).
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index d67da9816..fe4f598d4 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -4603,3 +4603,57 @@ Input, selection, submission and dismissal semantics remain unchanged.
Project-delete descriptions and plugin dialog headings/outcomes also wrap long
project or plugin names instead of overflowing their existing widths. Project
instructions, memory and OAuth dialogs retain their existing bounded layouts.
+
+## Round review reader
+
+Local Review defaults to Last round (the latest modified user round). Its
+scope dropdown also offers History, which reveals a separate user-round selector row,
+independent of the chat's loaded message window. Rounds without changes do not
+replace Latest. Main and delegated Write/Edit evidence share a file list; actual
+execution roots distinguish identically named files. The file header opens all
+of that file's recorded operations in order, without claiming a net diff.
+
+Expanded file content has no fixed-height inner viewport or vertical scrollbar.
+The outer Review scroll owns vertical travel; the current file header sticks
+below the toolbar within its file section. It is not reordered. A borderless ellipsis button after the summary totals opens a menu containing
+only Word wrap and Context lines. Hovering Context lines opens a secondary
+menu with 1/3/5 (first-use default 3); the choice is profile-wide, remembered
+across sessions, panel reopening and application restarts. Invalid or missing
+preferences use 3, and unavailable storage never blocks the current selection.
+No context selector is shown in the main toolbar.
+Toggle checks appear on the right. History options show only date and time in
+a compact selector with reserved arrow space. File headings have no permanent
+button fill or border; execution roots are not rendered as extra diff rows.
+A separate file ellipsis offers Open internally (disabled without the loaded
+File Manager view; never auto-enables it), Open externally (OS default app),
+and Open folder (system file manager, revealing the current file).
+All three resolve the current exact file through session-aware authorized roots, not
+a historical export or a same-named fallback. Stale session/project results are
+discarded; lookup/open failures are visible without changing stored evidence.
+Absolute and outside-root relative path labels use `.../basename`; full paths
+remain in the title and stored evidence. Native review captures successful
+approved Write/Edit mutations inside and outside the workspace, never Bash or
+external-application changes. Outside snapshots do not grant rollback or general filesystem permissions.
+Their file menu omits internal open and offers only external open and folder
+reveal through explicit snapshot-bound user actions (ADR 0338). Other file-open
+surfaces retain their existing authorization.
+
+Both scope and historical round selectors reuse the shared native Select.
+Review-only CSS opts into Chromium's customizable native picker: its base follows
+the sidebar color, with a contrasting sidebar-derived selected fill (no system
+blue). Only the first option's upper and last option's lower corners are rounded;
+interior edges are square, including when an interior row is selected or hovered.
+A single option has all four outer corners. The scope trigger is 24px high; the
+round field stays 28px high. Both vertically center their text and arrow. Round
+labels show date/time only with reserved arrow space. Native keyboard selection,
+Escape dismissal and focus remain browser-owned. Shared primitives and the AI
+Command shell selector are unchanged.
+Only file action menus opt into compact density. Recorded operations have no
+numbered title or dividing rule. One footer per file copies all its recorded
+hunks or requests a Host-preflighted file rollback; chat's inline actions remain
+unchanged. The copied sequence is not represented as a net diff.
+Diff rows show old/new line numbers, and Word wrap toggles wrapping without
+introducing nested vertical scrolling. Unsupported
+historical context has an explicit explanation and retains recorded evidence.
+Remote Review retains its existing presentation. Chat inline review rows retain
+their default layout and hash-guarded rollback; no Git or model behavior changes.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index c86ce2a3d..75a291bbf 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -19378,3 +19378,64 @@ their separate platform acceptance.
`apps/desktop/test/plugin-projects.test.mjs` covers pin-independent ordering,
group lookup failure, missing project providers, failed/malformed lookup,
rename identity, and stale results after Host replacement.
+
+## Round review reader
+
+Scenario: E2E-REVIEW-ROUNDS (local desktop, implemented)
+
+- Preconditions: candidate JavaScript and Rust Host built; isolated temporary
+ profile/data/workspace; no provider or running user instance.
+- Command: `node scripts/e2e-review-history.mjs` with `PI_DESKTOP_HOST_BIN` pointing
+ at this candidate's Host binary. The runner writes controlled-data preview PNGs
+ under `docs/public/screenshots/review-history/`.
+- Actions: create modified, newer modified and no-edit rounds through real Host
+ RPC; add delegated evidence; select rounds, expand a multi-operation file,
+ choose Last round/History, hover the context submenu (only 1/3/5), toggle word
+ wrapping, scroll and resize, copy, attempt conflicting rollback, append a
+ late delegate result, restart Host and switch sessions. Choose one context line,
+ reopen Review, switch conversations and reload the renderer from the same
+ isolated profile; verify both the checked menu option and actual diff context
+ retain that choice. Missing/invalid/blocked storage is unit-covered by
+ `apps/desktop/test/review-preferences.test.mjs`.
+- Expected: latest skips no-edit rounds; delegates belong to their original user
+ round; all file records are accessible; old/new numbers and bounded immutable context
+ agree; no full after-image is cached; only the outer review scrolls; headers stick without toolbar overlap in
+ normal/narrow layouts; copy and conflict protection survive; history restores.
+ Toggle checks trail labels, summary dots have no circle, history options contain
+ only date/time and fit a compact arrow-safe field, file headers have no idle
+ fill, and no execution-root row appears. File menus disable internal open when
+ the plugin is absent, open its loaded view when available, and pass the resolved
+ current file and session to external open. The third action, Open folder,
+ invokes system reveal without requiring a plugin (OS launch/reveal boundaries
+ are stubbed). Non-workspace rows hide internal open; their remaining two actions
+ exercise the real reviewed-file service and Host snapshot authentication.
+ A multi-operation file has exactly one action bar and no record-number heading;
+ copy contains every operation, conflicting rollback changes nothing, and a
+ successful grouped rollback restores the content before the first operation.
+ Scope and historical round controls reuse the shared native Select with local
+ customizable-picker styles. Check light/dark palettes and live sidebar color
+ changes: selected fills follow the sidebar but differ from the list base, not
+ system blue. Only first-row upper and last-row lower corners are rounded;
+ interior edges are square, and a single row has all four corners. Verify native
+ ArrowUp/ArrowDown, Enter, Escape/focus retention and close-after-selection;
+ the scope trigger is 24px high, the round field stays 28px high, and both
+ vertically center their text and arrow. Round labels show only date/time with
+ reserved trigger-arrow space.
+ The long-file fixture has 3100 lines with local edits: unchanged head/tail do
+ not consume the LCS matrix budget, while original hunk coordinates, 1/3/5-line
+ context, copy and guarded rollback still work. Byte/line/middle-cell caps remain. Absolute/outside-root labels show `.../basename`, while the title
+ retains the full path; normal workspace-relative labels remain unchanged.
+ A real approved outside-workspace Write is included in the historical round:
+ its diff remains readable after restart, its label is `.../basename`, and it
+ grants no rollback writes. Rust RPC tests cover workspace/scratch/external
+ Write and Edit, same-named paths, approval denial, failed Edit, and no Bash capture.
+ `review-file-open.test.mjs` covers missing/fuzzy paths, worktree/secondary-root
+ locations, plugin unload, stale session/project results, and visible failures.
+- Additional acceptance: Rust RPC tests cover over 100 turns/changes, dedup,
+ invalid evidence and root isolation; context tests cover legacy, binary, resource
+ budgets, additions/deletions and newline-only changes. Renderer unit tests cover
+ numbered ranges, grouping and cancelled pagination. Existing review/chat/history
+ tests remain required regression coverage.
+- Specs: ADR 0043; runtime RPC/storage specs; component spec Round review reader.
+- Milestone: maintenance. Traceability: acceptance criteria 1–9 of the approved
+ native round-review enhancement map to this scenario and the tests above.
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index ed37c88eb..eeb1119ef 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -2151,6 +2151,32 @@ sklm: {
"rollback": "Machen Sie diese Änderung rückgängig",
"rollingBack": "Rollback…",
"rolledBack": "Rollback",
+ historyTitle: "Conversation round",
+ loadingHistory: "Loading review history…",
+ historyError: "Could not load review history. Retry.",
+ retryHistory: "Retry",
+ moreHistory: "Older rounds",
+ contextError: "Could not load context. Showing the recorded 3-line diff.",
+ oldLine: "Old line {{line}}",
+ newLine: "New line {{line}}",
+ changeRecord: "Change {{index}} of {{count}}",
+ contextUnavailable: {
+ legacy: "This historical snapshot has no extended context. Showing its recorded diff.",
+ binary: "Binary content has no text context.",
+ tooLarge: "Context exceeds the safe preview budget. Showing its recorded diff.",
+ },
+ previousRound: "Last round",
+ historyMode: "History",
+ reviewScope: "Review scope",
+ reviewSettings: "Review settings",
+ wordWrap: "Word wrap",
+ contextDisplay: "Context lines",
+ fileActions: "Dateiaktionen",
+ openInternal: "Intern öffnen",
+ openExternal: "Extern öffnen",
+ openFolder: "Ordner öffnen",
+ openError: "Diese Datei konnte nicht geöffnet werden. Sie ist möglicherweise nicht verfügbar oder außerhalb des erlaubten Arbeitsbereichs.",
+ contextLineOption: "{{count}} lines",
"rollbackUnavailable": "Rollback nicht verfügbar",
"rollbackConflict": "Die Datei wurde nach dieser Meldung geändert; Rollback wurde übersprungen.",
"rollbackError": "Diese Änderung konnte nicht rückgängig gemacht werden.",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index d707cddfc..08aca6cd1 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -2171,6 +2171,32 @@ sklm: {
rollback: "Rollback this change",
rollingBack: "Rolling back…",
rolledBack: "Rolled back",
+ historyTitle: "Conversation round",
+ loadingHistory: "Loading review history…",
+ historyError: "Could not load review history. Retry.",
+ retryHistory: "Retry",
+ moreHistory: "Older rounds",
+ contextError: "Could not load context. Showing the recorded 3-line diff.",
+ oldLine: "Old line {{line}}",
+ newLine: "New line {{line}}",
+ changeRecord: "Change {{index}} of {{count}}",
+ contextUnavailable: {
+ legacy: "This historical snapshot has no extended context. Showing its recorded diff.",
+ binary: "Binary content has no text context.",
+ tooLarge: "Context exceeds the safe preview budget. Showing its recorded diff.",
+ },
+ previousRound: "Last round",
+ historyMode: "History",
+ reviewScope: "Review scope",
+ reviewSettings: "Review settings",
+ wordWrap: "Word wrap",
+ contextDisplay: "Context lines",
+ fileActions: "File actions",
+ openInternal: "Open internally",
+ openExternal: "Open externally",
+ openFolder: "Open folder",
+ openError: "Could not open this file. It may be unavailable or outside the allowed workspace.",
+ contextLineOption: "{{count}} lines",
rollbackUnavailable: "Rollback unavailable",
rollbackConflict: "The file changed after this message; rollback was skipped.",
rollbackError: "Couldn't roll back this change.",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 27400a7b8..b83c6523f 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -2151,6 +2151,32 @@ sklm: {
"rollback": "Revertir este cambio",
"rollingBack": "Revertir…",
"rolledBack": "Revertir",
+ historyTitle: "Conversation round",
+ loadingHistory: "Loading review history…",
+ historyError: "Could not load review history. Retry.",
+ retryHistory: "Retry",
+ moreHistory: "Older rounds",
+ contextError: "Could not load context. Showing the recorded 3-line diff.",
+ oldLine: "Old line {{line}}",
+ newLine: "New line {{line}}",
+ changeRecord: "Change {{index}} of {{count}}",
+ contextUnavailable: {
+ legacy: "This historical snapshot has no extended context. Showing its recorded diff.",
+ binary: "Binary content has no text context.",
+ tooLarge: "Context exceeds the safe preview budget. Showing its recorded diff.",
+ },
+ previousRound: "Last round",
+ historyMode: "History",
+ reviewScope: "Review scope",
+ reviewSettings: "Review settings",
+ wordWrap: "Word wrap",
+ contextDisplay: "Context lines",
+ fileActions: "Acciones del archivo",
+ openInternal: "Abrir internamente",
+ openExternal: "Abrir externamente",
+ openFolder: "Abrir carpeta",
+ openError: "No se pudo abrir el archivo. Puede no estar disponible o estar fuera del espacio permitido.",
+ contextLineOption: "{{count}} lines",
"rollbackUnavailable": "Revertir no disponible",
"rollbackConflict": "El archivo cambió después de este mensaje; se omitió la reversión.",
"rollbackError": "No se pudo revertir este cambio.",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 20f418ee0..ed8ce8afa 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -2151,6 +2151,32 @@ sklm: {
"rollback": "Annuler cette modification",
"rollingBack": "Restauration…",
"rolledBack": "Restauration",
+ historyTitle: "Conversation round",
+ loadingHistory: "Loading review history…",
+ historyError: "Could not load review history. Retry.",
+ retryHistory: "Retry",
+ moreHistory: "Older rounds",
+ contextError: "Could not load context. Showing the recorded 3-line diff.",
+ oldLine: "Old line {{line}}",
+ newLine: "New line {{line}}",
+ changeRecord: "Change {{index}} of {{count}}",
+ contextUnavailable: {
+ legacy: "This historical snapshot has no extended context. Showing its recorded diff.",
+ binary: "Binary content has no text context.",
+ tooLarge: "Context exceeds the safe preview budget. Showing its recorded diff.",
+ },
+ previousRound: "Last round",
+ historyMode: "History",
+ reviewScope: "Review scope",
+ reviewSettings: "Review settings",
+ wordWrap: "Word wrap",
+ contextDisplay: "Context lines",
+ fileActions: "Actions du fichier",
+ openInternal: "Ouvrir en interne",
+ openExternal: "Ouvrir en externe",
+ openFolder: "Ouvrir le dossier",
+ openError: "Impossible d’ouvrir ce fichier. Il est peut-être indisponible ou hors de l’espace autorisé.",
+ contextLineOption: "{{count}} lines",
"rollbackUnavailable": "Restauration indisponible",
"rollbackConflict": "Le fichier a changé après ce message ; la restauration a été ignorée.",
"rollbackError": "Impossible d'annuler cette modification.",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index f32595497..7e46371da 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -2167,6 +2167,32 @@ sklm: {
rollback: "이 변경 되돌리기",
rollingBack: "되돌리는 중…",
rolledBack: "되돌림",
+ historyTitle: "Conversation round",
+ loadingHistory: "Loading review history…",
+ historyError: "Could not load review history. Retry.",
+ retryHistory: "Retry",
+ moreHistory: "Older rounds",
+ contextError: "Could not load context. Showing the recorded 3-line diff.",
+ oldLine: "Old line {{line}}",
+ newLine: "New line {{line}}",
+ changeRecord: "Change {{index}} of {{count}}",
+ contextUnavailable: {
+ legacy: "This historical snapshot has no extended context. Showing its recorded diff.",
+ binary: "Binary content has no text context.",
+ tooLarge: "Context exceeds the safe preview budget. Showing its recorded diff.",
+ },
+ previousRound: "Last round",
+ historyMode: "History",
+ reviewScope: "Review scope",
+ reviewSettings: "Review settings",
+ wordWrap: "Word wrap",
+ contextDisplay: "Context lines",
+ fileActions: "파일 작업",
+ openInternal: "내부에서 열기",
+ openExternal: "외부에서 열기",
+ openFolder: "폴더 열기",
+ openError: "파일을 열 수 없습니다. 파일이 없거나 허용된 작업 공간 밖에 있을 수 있습니다.",
+ contextLineOption: "{{count}} lines",
rollbackUnavailable: "되돌릴 수 없음",
rollbackConflict: "이 메시지 후 파일이 변경되어 되돌리기를 건너뛰었습니다.",
rollbackError: "이 변경을 되돌릴 수 없습니다.",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 4ee0b61d2..0fbef54e4 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -2117,6 +2117,32 @@ export const ptBR = {
rollback: "Reverter esta alteração",
rollingBack: "Revertendo…",
rolledBack: "Revertida",
+ historyTitle: "Conversation round",
+ loadingHistory: "Loading review history…",
+ historyError: "Could not load review history. Retry.",
+ retryHistory: "Retry",
+ moreHistory: "Older rounds",
+ contextError: "Could not load context. Showing the recorded 3-line diff.",
+ oldLine: "Old line {{line}}",
+ newLine: "New line {{line}}",
+ changeRecord: "Change {{index}} of {{count}}",
+ contextUnavailable: {
+ legacy: "This historical snapshot has no extended context. Showing its recorded diff.",
+ binary: "Binary content has no text context.",
+ tooLarge: "Context exceeds the safe preview budget. Showing its recorded diff.",
+ },
+ previousRound: "Last round",
+ historyMode: "History",
+ reviewScope: "Review scope",
+ reviewSettings: "Review settings",
+ wordWrap: "Word wrap",
+ contextDisplay: "Context lines",
+ fileActions: "Ações do arquivo",
+ openInternal: "Abrir internamente",
+ openExternal: "Abrir externamente",
+ openFolder: "Abrir pasta",
+ openError: "Não foi possível abrir o arquivo. Ele pode estar indisponível ou fora do espaço permitido.",
+ contextLineOption: "{{count}} lines",
rollbackUnavailable: "Reversão indisponível",
rollbackConflict: "Este arquivo foi alterado novamente após esta mensagem; a reversão foi ignorada.",
rollbackError: "Não foi possível reverter esta alteração.",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 880ee1a77..d6281c0b2 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -2161,6 +2161,32 @@ sklm: {
rollback: "Bu değişikliği geri al",
rollingBack: "Geri alınıyor…",
rolledBack: "Geri alındı",
+ historyTitle: "Conversation round",
+ loadingHistory: "Loading review history…",
+ historyError: "Could not load review history. Retry.",
+ retryHistory: "Retry",
+ moreHistory: "Older rounds",
+ contextError: "Could not load context. Showing the recorded 3-line diff.",
+ oldLine: "Old line {{line}}",
+ newLine: "New line {{line}}",
+ changeRecord: "Change {{index}} of {{count}}",
+ contextUnavailable: {
+ legacy: "This historical snapshot has no extended context. Showing its recorded diff.",
+ binary: "Binary content has no text context.",
+ tooLarge: "Context exceeds the safe preview budget. Showing its recorded diff.",
+ },
+ previousRound: "Last round",
+ historyMode: "History",
+ reviewScope: "Review scope",
+ reviewSettings: "Review settings",
+ wordWrap: "Word wrap",
+ contextDisplay: "Context lines",
+ fileActions: "Dosya işlemleri",
+ openInternal: "Dahili aç",
+ openExternal: "Harici aç",
+ openFolder: "Klasörü aç",
+ openError: "Dosya açılamadı. Kullanılamıyor veya izin verilen çalışma alanının dışında olabilir.",
+ contextLineOption: "{{count}} lines",
rollbackUnavailable: "Geri alma yok",
rollbackConflict: "Bu iletiden sonra dosya değişti; geri alma atlandı.",
rollbackError: "Bu değişiklik geri alınamadı.",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index d245d6425..b3316de99 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -2146,6 +2146,32 @@ sklm: {
rollback: "回退这项改动",
rollingBack: "正在回退…",
rolledBack: "已回退",
+ historyTitle: "对话轮次",
+ loadingHistory: "正在读取审阅记录…",
+ historyError: "审阅记录读取失败,请重试。",
+ retryHistory: "重试",
+ moreHistory: "更早轮次",
+ contextError: "上下文读取失败,显示已保存的 3 行差异。",
+ oldLine: "旧版第 {{line}} 行",
+ newLine: "新版第 {{line}} 行",
+ changeRecord: "修改记录 {{index}} / {{count}}",
+ contextUnavailable: {
+ legacy: "该历史快照未保存扩展上下文,显示原有差异。",
+ binary: "二进制内容不提供文本上下文。",
+ tooLarge: "上下文超过安全预览预算,显示原有差异。",
+ },
+ previousRound: "上一轮",
+ historyMode: "历史",
+ reviewScope: "审阅范围",
+ reviewSettings: "审阅设置",
+ wordWrap: "自动换行",
+ contextDisplay: "上下文显示",
+ fileActions: "文件操作",
+ openInternal: "内部打开",
+ openExternal: "外部打开",
+ openFolder: "打开文件夹",
+ openError: "无法打开此文件,文件可能已不存在或不在允许的工作区中。",
+ contextLineOption: "{{count}} 行",
rollbackUnavailable: "无法回退",
rollbackConflict: "该文件在此消息之后又发生了变化,已跳过回退。",
rollbackError: "这项改动回退失败。",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index a4a62e24b..b6b9bb1d7 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -2146,6 +2146,32 @@ sklm: {
rollback: "回退這項改動",
rollingBack: "正在回退…",
rolledBack: "已回退",
+ historyTitle: "对话轮次",
+ loadingHistory: "正在读取审阅记录…",
+ historyError: "审阅记录读取失败,请重试。",
+ retryHistory: "重试",
+ moreHistory: "更早轮次",
+ contextError: "上下文读取失败,显示已保存的 3 行差异。",
+ oldLine: "旧版第 {{line}} 行",
+ newLine: "新版第 {{line}} 行",
+ changeRecord: "修改记录 {{index}} / {{count}}",
+ contextUnavailable: {
+ legacy: "该历史快照未保存扩展上下文,显示原有差异。",
+ binary: "二进制内容不提供文本上下文。",
+ tooLarge: "上下文超过安全预览预算,显示原有差异。",
+ },
+ previousRound: "上一轮",
+ historyMode: "历史",
+ reviewScope: "审阅范围",
+ reviewSettings: "审阅设置",
+ wordWrap: "自动换行",
+ contextDisplay: "上下文显示",
+ fileActions: "檔案操作",
+ openInternal: "內部開啟",
+ openExternal: "外部開啟",
+ openFolder: "開啟資料夾",
+ openError: "無法開啟此檔案,檔案可能已不存在或不在允許的工作區中。",
+ contextLineOption: "{{count}} 行",
rollbackUnavailable: "無法回退",
rollbackConflict: "該檔案在此訊息之後又發生了變化,已跳過回退。",
rollbackError: "這項改動回退失敗。",
diff --git a/packages/shared/src/protocol.test.ts b/packages/shared/src/protocol.test.ts
index f8e4c7c79..bf7935a49 100644
--- a/packages/shared/src/protocol.test.ts
+++ b/packages/shared/src/protocol.test.ts
@@ -75,6 +75,10 @@ describe("Plan protocol contracts", () => {
expect(IPC_WHITELIST.has(IPC.invoke.appOpenFeedback)).toBe(true);
expect(IPC.invoke.fsOpen).toBe("pi-desktop/fs/open");
expect(IPC_WHITELIST.has(IPC.invoke.fsOpen)).toBe(true);
+ expect(IPC.invoke.workspaceReviewOpenFile).toBe("pi-desktop/workspace/review/openFile");
+ expect(IPC.invoke.workspaceReviewRollbackFile).toBe("pi-desktop/workspace/review/rollbackFile");
+ expect(IPC_WHITELIST.has(IPC.invoke.workspaceReviewOpenFile)).toBe(true);
+ expect(IPC_WHITELIST.has(IPC.invoke.workspaceReviewRollbackFile)).toBe(true);
expect(IPC.invoke.statsGetTokenUsageHistory).toBe(
"pi-desktop/stats/getTokenUsageHistory",
);
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index ede945d38..3a79e05ec 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -422,6 +422,11 @@ export const IPC = {
composerCommands: "pi-desktop/composer/commands",
workspaceDiff: "pi-desktop/workspace/diff",
workspaceReviewRollback: "pi-desktop/workspace/review/rollback",
+ workspaceReviewTurns: "pi-desktop/workspace/review/turns",
+ workspaceReviewChanges: "pi-desktop/workspace/review/changes",
+ workspaceReviewContext: "pi-desktop/workspace/review/context",
+ workspaceReviewOpenFile: "pi-desktop/workspace/review/openFile",
+ workspaceReviewRollbackFile: "pi-desktop/workspace/review/rollbackFile",
browserNavigate: "pi-desktop/browser/navigate",
browserAction: "pi-desktop/browser/action",
browserSetBounds: "pi-desktop/browser/setBounds",
diff --git a/packages/shared/src/types/workpanel.ts b/packages/shared/src/types/workpanel.ts
index ac5eb44f0..98ec7dcc4 100644
--- a/packages/shared/src/types/workpanel.ts
+++ b/packages/shared/src/types/workpanel.ts
@@ -1,3 +1,5 @@
+import type { UiMessage } from "./messages.js";
+
/** Shared public types grouped by the owning application domain. */
// --- Work panel (review / browser / files / plugin views) ---
@@ -26,6 +28,7 @@ export type ReviewChange = {
version: 1;
snapshotId: string;
messageId: string;
+ /** Relative inside the execution workspace; absolute for other approved roots. */
path: string;
operation: ReviewChangeOperation;
status: ReviewChangeStatus;
@@ -36,6 +39,28 @@ export type ReviewChange = {
binary?: boolean;
truncated?: boolean;
reversible: boolean;
+ /** Host-resolved execution root; never a renderer authorization grant. */
+ root?: string;
+};
+
+export type ReviewContextLines = 1 | 3 | 5;
+export type ReviewTurn = {
+ id: string;
+ userMessageId: string;
+ createdAt: string;
+ title: string;
+ changeCount: number;
+};
+export type ReviewTurnsPage = { turns: ReviewTurn[]; nextBefore?: number };
+export type ReviewHistoryChange = { message: UiMessage; root?: string };
+export type ReviewChangesPage = {
+ turnId: string | null;
+ changes: ReviewHistoryChange[];
+ nextOffset?: number;
+};
+export type ReviewContextResult = {
+ hunks: DiffHunk[];
+ unavailable?: "legacy" | "binary" | "tooLarge";
};
export type ReviewRollbackStatus =
@@ -51,6 +76,11 @@ export type ReviewRollbackResult = {
path?: string;
};
+export type ReviewFileRollbackResult = {
+ status: ReviewRollbackStatus;
+ changes: ReviewRollbackResult[];
+};
+
export type DiffFileStatus =
| "added"
| "modified"
diff --git a/scripts/e2e-review-history.mjs b/scripts/e2e-review-history.mjs
new file mode 100644
index 000000000..7cdee5621
--- /dev/null
+++ b/scripts/e2e-review-history.mjs
@@ -0,0 +1,80 @@
+#!/usr/bin/env node
+/** Actual Rust/stdiorpc + Electron + production Review UI; never uses a user's profile or model. */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { pathToFileURL } from "node:url";
+import { IPC } from "../packages/shared/dist/index.js";
+import { repositoryRoot, resolveElectronBinary } from "./e2e/boot.mjs";
+import { resolveHostBinary } from "./e2e/host.mjs";
+const root = repositoryRoot(), hostBinary = resolveHostBinary();
+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");
+const temp = await mkdtemp(join(process.env.PI_SCRATCH_DIR || tmpdir(), "review-e2e-"));
+const screenshots = join(root, "docs/public/screenshots/review-history");
+await mkdir(screenshots, { recursive: true });
+try {
+ await build({ entryPoints: [join(root, "scripts/e2e/review-history.tsx")], outfile: join(temp, "renderer.js"), bundle: true,
+ platform: "browser", format: "esm", jsx: "automatic", loader: { ".css": "empty" }, define: { "process.env.NODE_ENV": '"production"', "import.meta.env.DEV": "false" },
+ alias: { "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"), "@pi-desktop/shared": join(root, "packages/shared/src/index.ts"),
+ react: join(root, "apps/desktop/node_modules/react"), "react-dom": join(root, "apps/desktop/node_modules/react-dom"),
+ i18next: join(root, "apps/desktop/node_modules/i18next"), "react-i18next": join(root, "apps/desktop/node_modules/react-i18next") }, nodePaths: [join(root, "apps/desktop/node_modules")] });
+ await build({ entryPoints: [join(root, "apps/desktop/electron/main/reviewed-file-open.ts")], outfile: join(temp, "reviewed-file-open.cjs"), bundle: true, platform: "node", format: "cjs" });
+ const renderer = join(root, "apps/desktop/out/renderer");
+ const html = await readFile(join(renderer, "index.html"), "utf8");
+ const css = [...html.matchAll(/href="([^" ]+\.css)"/g)].map(match => pathToFileURL(join(renderer, match[1])).href);
+ assert(css.length, "Build the candidate desktop renderer first");
+ await writeFile(join(temp, "index.html"), `<!doctype html><html><head><meta charset="utf-8">${css.map(url => `<link rel="stylesheet" href="${url}">`).join("")}<style>html,body,#root{height:100%;margin:0}.fixture{height:100%;display:flex;flex-direction:column;padding:12px;background:var(--ds-bg-primary);color:var(--ds-text-primary)}.fixture-label{flex:none;font-size:12px;padding:4px 8px 10px;color:var(--ds-text-muted)}.fixture-panel{flex:1;min-height:0;display:flex;flex-direction:column;border:1px solid var(--ds-border-default);border-radius:8px;overflow:hidden}</style></head><body><div id="root"></div><script type="module" src="renderer.js"></script></body></html>`);
+ await writeFile(join(temp, "preload.cjs"), `const {contextBridge,ipcRenderer}=require('electron');contextBridge.exposeInMainWorld('piDesktop',{platform:process.platform,invoke:(channel,input)=>ipcRenderer.invoke('fixture:invoke',channel,input),on:()=>()=>{}});contextBridge.exposeInMainWorld('reviewFixture',{action:(name,input)=>ipcRenderer.invoke('fixture:action',name,input)});`);
+ const channels = { [IPC.invoke.workspaceReviewTurns]: "review.turns", [IPC.invoke.workspaceReviewChanges]: "review.changes", [IPC.invoke.workspaceReviewContext]: "review.context", [IPC.invoke.workspaceReviewRollback]: "review.rollback", [IPC.invoke.workspaceReviewRollbackFile]: "review.rollbackFile" };
+ await writeFile(join(temp, "main.cjs"), `
+const {app,BrowserWindow,ipcMain}=require('electron');const path=require('node:path');const fs=require('node:fs/promises');
+app.setPath('userData',path.join(__dirname,'profile'));
+let host,win,seed,copied='',runningTurn,hold=false,blocked,notifyBlocked,gate,release; const opened=[],revealed=[];
+app.whenReady().then(async()=>{let watchdog;try{
+const {Host}=await import(${JSON.stringify(pathToFileURL(join(root, "scripts/e2e/host.mjs")).href)});
+const {seedReviewHistory}=await import(${JSON.stringify(pathToFileURL(join(root, "scripts/e2e/review-history-fixture.mjs")).href)});
+host=new Host(${JSON.stringify(hostBinary)},path.join(__dirname,'data'));await host.start();
+win=new BrowserWindow({show:false,width:920,height:760,useContentSize:true,webPreferences:{preload:path.join(__dirname,'preload.cjs'),sandbox:true,contextIsolation:true,nodeIntegration:false,backgroundThrottling:false}});
+win.webContents.on('console-message',event=>console.error(event.message));
+ipcMain.handle('fixture:invoke',async(_event,channel,input)=>{if(channel===${JSON.stringify(IPC.invoke.pluginViews)})return {ok:true,data:[{pluginId:"pi.file-manager",viewId:"manager"}]};if(channel===${JSON.stringify(IPC.invoke.fsResolveRef)}){const target=path.toNamespacedPath(path.resolve(input.ref)),base=path.toNamespacedPath(path.join(__dirname,"workspace"));const rel=path.relative(base,target);if(rel.startsWith("..")||path.isAbsolute(rel))throw new Error("Outside fixture workspace");const stat=await fs.stat(target).catch(()=>null);return {ok:true,data:{match:stat?.isFile()?{root:"workspace",relativePath:rel.replaceAll(String.fromCharCode(92),"/"),absolutePath:target,matchedBy:"exact-absolute",projectRoot:{primary:true}}:null}};}if(channel===${JSON.stringify(IPC.invoke.fsOpen)}){opened.push(input);return {ok:true,data:{}};}if(channel===${JSON.stringify(IPC.invoke.fsReveal)}){revealed.push(input);return {ok:true,data:{}};}if(channel===${JSON.stringify(IPC.invoke.workspaceReviewOpenFile)}){const {openReviewedFile}=require('./reviewed-file-open.cjs');return {ok:true,data:await openReviewedFile(input,{target:(sessionId,snapshotId)=>host.call('review.fileTarget',{sessionId,snapshotId}),isCurrent:()=>true,stripPrefix:p=>p.replace(/^\\\\\\\\\\?\\\\(?=[A-Za-z]:\\\\)/,''),openPath:async path=>{opened.push({path,sessionId:input.sessionId,review:true});return '';},reveal:path=>revealed.push({path,sessionId:input.sessionId,review:true})})};}const method=${JSON.stringify(channels)}[channel];if(!method)throw new Error('Unexpected IPC '+channel);if(hold&&method==='review.changes'){notifyBlocked();await gate;}try{return {ok:true,data:await host.call(method,input)}}catch(error){return {ok:false,error:{code:error.errorCode||'INTERNAL',message:error.message}}}});
+ipcMain.handle('fixture:action',async(_event,name,input)=>{switch(name){
+case 'seed':seed=await seedReviewHistory(host,__dirname);return {session:seed.session,other:seed.other,round:seed.round,latest:seed.latest,firstSnapshot:seed.firstSnapshot,late:seed.lateMessage};
+case 'currentSeed':return {session:seed.session,firstSnapshot:seed.firstSnapshot};
+case 'late':return seed.appendLate();
+case 'runningStart':runningTurn=await seed.startRunning();return;
+case 'runningWrite':return seed.writeRunning(runningTurn);
+case 'runningEnd':return seed.endRunning(runningTurn);
+case 'holdReads':hold=true;blocked=new Promise(resolve=>notifyBlocked=resolve);gate=new Promise(resolve=>release=resolve);return;
+case 'readBlocked':await blocked;return;
+case 'releaseReads':hold=false;release();return;
+case 'restart':await host.restart();return;
+case 'readCurrent':return seed.readCurrent();
+case 'resetCurrent':return seed.resetCurrent();
+case 'copy':copied=input;return;
+case 'clipboard':return copied;
+case 'opened':return opened;
+case 'revealed':return revealed;
+case 'resize':win.setContentSize(input,760);return;
+case 'screenshot':if(!/^review-(normal|narrow|overview|latest|menu)\\.png$/.test(input))throw new Error('Invalid screenshot');await fs.writeFile(path.join(${JSON.stringify(screenshots)},input),(await win.webContents.capturePage()).toPNG());return;
+default:throw new Error('Unknown action '+name)}});
+watchdog=setTimeout(()=>{console.error('Review fixture timed out');host.stop().finally(()=>app.exit(1))},90000);
+await win.loadFile(path.join(__dirname,'index.html'));
+const result=await win.webContents.executeJavaScript('window.reviewProbe().catch(error=>{console.error(error.stack);throw error})');
+await win.loadFile(path.join(__dirname,'index.html'));
+const restored=await win.webContents.executeJavaScript('window.reviewReloadProbe().catch(error=>{console.error(error.stack);throw error})');
+result.checks.push(...restored.checks);console.log('REVIEW_HISTORY '+JSON.stringify(result));clearTimeout(watchdog);await host.stop();app.exit(0);
+}catch(error){console.error(error);clearTimeout(watchdog);await host?.stop();app.exit(1)}});
+`);
+ const env = { ...process.env }; delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(resolveElectronBinary(root).electronBinary, [join(temp, "main.cjs")], { env, stdio: ["ignore", "pipe", "pipe"] });
+ let output = "";
+ for (const stream of [child.stdout, child.stderr]) stream.on("data", chunk => { output += chunk; });
+ const timer = setTimeout(() => child.kill("SIGKILL"), 100000);
+ let code; try { code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); }); } finally { clearTimeout(timer); }
+ assert.equal(code, 0, output);
+ const result = output.split(/\r?\n/).find(line => line.startsWith("REVIEW_HISTORY ")); assert(result, output); console.log(result);
+ console.log("Preview screenshots: " + screenshots);
+} finally { await rm(temp, { recursive: true, force: true }); }
diff --git a/scripts/e2e/review-history-fixture.mjs b/scripts/e2e/review-history-fixture.mjs
new file mode 100644
index 000000000..b2a3cd29b
--- /dev/null
+++ b/scripts/e2e/review-history-fixture.mjs
@@ -0,0 +1,52 @@
+import { mkdir, writeFile, readFile } from "node:fs/promises";
+import { join } from "node:path";
+
+/** Controlled external input; all mutation snapshots and persisted messages use real Host RPC. */
+export async function seedReviewHistory(host, directory) {
+ const root = join(directory, "workspace"); await mkdir(root, { recursive: true });
+ const session = (await host.call("session.create", { title: "Review test", projectPath: root, mode: "agent" })).session;
+ const other = (await host.call("session.create", { title: "Other test", projectPath: root, mode: "agent" })).session;
+ await host.call("session.configure", { id: session.id, mode: "agent", permissionMode: "auto" });
+ let serial = 0;
+ const append = (message, turnId) => host.call("session.appendMessage", { sessionId: session.id, message, turnId });
+ const begin = async (id, title) => {
+ const { turnId } = await host.call("session.beginTurn", { sessionId: session.id });
+ await append({ id, role: "user", content: title, createdAt: new Date().toISOString() }, turnId);
+ return turnId;
+ };
+ const end = turnId => host.call("session.endTurn", { turnId, status: "completed", createNotification: false });
+ const mutate = async (turnId, path, content, parentToolCallId) => {
+ const id = `review-call-${++serial}`;
+ const result = await host.call("tools.execute", { sessionId: session.id, turnId, toolCallId: id, toolName: "Write", args: { path, content }, mode: "agent" });
+ if (!result.ok || !result.content.review) throw new Error("Fixture Write must produce review: " + JSON.stringify(result));
+ const message = { id, role: "tool", content: "", createdAt: new Date().toISOString(), toolName: "Write", toolCallId: id, toolStatus: "success", toolResult: { details: result.content }, ...(parentToolCallId ? { parentToolCallId } : {}) };
+ await append(message, turnId);
+ return message;
+ };
+ const original = Array.from({ length: 3100 }, (_, i) => `const line_${String(i + 1).padStart(3, "0")} = ${i + 1};`).join("\n") + "\n";
+ await writeFile(join(root, "long.ts"), original);
+ const firstTurn = await begin("round-one", "完善轮次审阅并统一子代理修改");
+ await append({ id: "task-row", role: "tool", content: "", createdAt: new Date().toISOString(), toolName: "Task", toolCallId: "review-task", toolStatus: "success" }, firstTurn);
+ const changed = original.replace("line_030 = 30", "line_030 = 300").replace("line_080 = 80", "line_080 = 800");
+ const first = await mutate(firstTurn, "long.ts", changed);
+ await mutate(firstTurn, "long.ts", changed.replace("line_040 = 40", "line_040 = 400"), "review-task");
+ await mutate(firstTurn, "child.md", "# Unified review\n\nDelegate output belongs to this conversation.\n", "review-task");
+ const outsidePath = join(directory, "outside", "review-open-tests-source.mjs");
+ await mutate(firstTurn, outsidePath, "export const outside = true;\n");
+ await end(firstTurn);
+ const second = await begin("round-two", "新增最近修改的测试文件");
+ await mutate(second, "latest.txt", "Latest modified round\n"); await end(second);
+ const third = await begin("round-no-edit", "只讨论方案,不修改文件"); await end(third);
+ // The disk is no longer the historical after image. Context must remain immutable.
+ await writeFile(join(root, "long.ts"), "external-current-only\n");
+ return {
+ session, other, round: "round-one", latest: "round-two", firstSnapshot: first.toolResult.details.review.snapshotId,
+ lateMessage: { ...first, id: "late-refresh" },
+ async appendLate() { return mutate(firstTurn, "late.txt", "Late old delegate\n", "review-task"); },
+ startRunning: () => begin("round-running", "运行中首次修改测试"),
+ writeRunning: turnId => mutate(turnId, "running.txt", "First modification in the running round\n"),
+ endRunning: end,
+ readCurrent: () => readFile(join(root, "long.ts"), "utf8"),
+ resetCurrent: () => writeFile(join(root, "long.ts"), changed.replace("line_040 = 40", "line_040 = 400")),
+ };
+}
diff --git a/scripts/e2e/review-history.tsx b/scripts/e2e/review-history.tsx
new file mode 100644
index 000000000..f52db59a3
--- /dev/null
+++ b/scripts/e2e/review-history.tsx
@@ -0,0 +1,298 @@
+// Production UI and store; only the external IPC transport and input data are fixtures.
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import i18n from "i18next";
+import { initReactI18next } from "react-i18next";
+import { catalogs, flattenCatalog } from "@pi-desktop/i18n";
+import { api } from "../../apps/desktop/src/lib/api";
+import { ReviewHistoryFile } from "../../apps/desktop/src/components/workpanel/ReviewHistoryFile";
+import { groupReviewFiles } from "../../apps/desktop/src/lib/review-history";
+import { ReviewTab } from "../../apps/desktop/src/components/workpanel/ReviewTab";
+import { useAppStore } from "../../apps/desktop/src/stores/app-store";
+import { requestReviewFocus } from "../../apps/desktop/src/lib/review-focus-request";
+import type { SessionSummary, UiMessage } from "@pi-desktop/shared";
+
+declare global {
+ interface Window {
+ reviewFixture: { action(name: string, input?: unknown): Promise<unknown> };
+ reviewProbe(): Promise<{ checks: string[] }>;
+ reviewReloadProbe(): Promise<{ checks: string[] }>;
+ }
+}
+await i18n.use(initReactI18next).init({ lng: "zh-CN", fallbackLng: "en", keySeparator: false,
+ resources: { "zh-CN": { translation: flattenCatalog(catalogs["zh-CN"]) }, en: { translation: flattenCatalog(catalogs.en) } }, interpolation: { escapeValue: false } });
+document.documentElement.dataset.theme = "light";
+const root = createRoot(document.getElementById("root")!);
+// Yield one renderer task; hidden-window animation frames may be suspended.
+// Readiness is determined by until predicates, not elapsed time or paint count.
+const frame = () => new Promise<void>(resolve => {
+ const channel = new MessageChannel();
+ channel.port1.onmessage = () => { channel.port1.close(); channel.port2.close(); resolve(); };
+ channel.port2.postMessage(null);
+});
+function assert(value: unknown, reason: string): asserts value { if (!value) throw new Error(reason); }
+async function until(predicate: () => boolean | Promise<boolean>, reason: string) {
+ const end = performance.now() + 15000;
+ while (!await predicate()) { if (performance.now() > end) throw new Error(reason); await frame(); }
+ await frame();
+}
+const action = (name: string, input?: unknown) => window.reviewFixture.action(name, input);
+Object.defineProperty(navigator, "clipboard", { value: { writeText: (text: string) => action("copy", text) } });
+const select = (label: string) => document.querySelector<HTMLSelectElement>(`select[aria-label="${label}"]`)!;
+function checkSelectStyle(node: HTMLSelectElement) {
+ assert(node?.classList.contains('field-select'), 'Review restores the shared native Select');
+ assert(getComputedStyle(node).appearance === 'base-select', 'Native picker supports local styling');
+ assert(getComputedStyle(node).alignItems === 'center', 'Closed native trigger centers its text and arrow vertically');
+ const height = node.getBoundingClientRect().height;
+ assert(Math.abs(height - (node.classList.contains('review-round-scope') ? 24 : 28)) < 1, 'Scope is 24px; round field retains 28px');
+ const picker = getComputedStyle(node, '::picker(select)');
+ assert(parseFloat(picker.borderTopLeftRadius) > 0 && parseFloat(picker.borderBottomLeftRadius) > 0, 'Picker has top and bottom outer corners');
+ const options = [...node.options];
+ options.forEach((option, index) => {
+ const style = getComputedStyle(option);
+ assert((parseFloat(style.borderTopLeftRadius) > 0) === (index === 0) && (parseFloat(style.borderTopRightRadius) > 0) === (index === 0), 'Only first option has upper corners');
+ assert((parseFloat(style.borderBottomLeftRadius) > 0) === (index === options.length - 1) && (parseFloat(style.borderBottomRightRadius) > 0) === (index === options.length - 1), 'Only last option has lower corners');
+ });
+ const chosen = node.selectedOptions[0];
+ assert(chosen && getComputedStyle(chosen).backgroundColor !== picker.backgroundColor, 'Selected background differs from list base');
+ const root = document.documentElement, originalTheme = root.dataset.theme;
+ const property = '--ds-bg-sidebar', original = root.style.getPropertyValue(property), priority = root.style.getPropertyPriority(property);
+ try {
+ for (const theme of ['light', 'dark']) {
+ root.dataset.theme = theme;
+ const colors: string[] = [];
+ for (const sidebar of ['#465548', '#5e4652']) {
+ root.style.setProperty(property, sidebar);
+ const base = getComputedStyle(node, '::picker(select)').backgroundColor;
+ const selected = getComputedStyle(chosen).backgroundColor;
+ assert(selected !== base && selected !== 'rgb(0, 120, 215)', 'Theme selection is distinct, not system blue');
+ colors.push(selected);
+ }
+ assert(colors[0] !== colors[1], 'Selection follows live sidebar color changes');
+ }
+ } finally {
+ if (originalTheme === undefined) delete root.dataset.theme; else root.dataset.theme = originalTheme;
+ if (original) root.style.setProperty(property, original, priority); else root.style.removeProperty(property);
+ }
+}
+async function choose(label: string, value: string) {
+ const node = select(label);
+ checkSelectStyle(node);
+ assert([...node.options].some(option => option.value === value), 'Requested option exists');
+ if (label === '对话轮次') assert([...node.options].every(option => !option.textContent?.includes('·')), 'Round labels show date and time only');
+ const setter = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value')!.set!;
+ setter.call(node, value);
+ node.dispatchEvent(new Event('change', { bubbles: true }));
+ await frame();
+}
+async function mode(history: boolean) {
+ await choose("审阅范围", history ? "history" : "last");
+}
+async function contextLines(lines: 1 | 3 | 5, expected?: 1 | 3 | 5) {
+ document.querySelector<HTMLButtonElement>(".review-settings-button")!.click();
+ await until(() => !!document.querySelector('[data-context-menu-item="review-context"]'), "Settings menu opens");
+ document.querySelector('[data-context-menu-item="review-context"]')!.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
+ await until(() => document.querySelectorAll('[data-context-menu-submenu-item]').length === 3, "Hover reveals exactly 1/3/5 options");
+ assert(!document.querySelector('[data-context-menu-item="review-context--1"]'), "No full context option");
+ const checked = document.querySelector<HTMLElement>('[data-context-menu-submenu-item][aria-checked="true"]')!;
+ assert(checked.getAttribute("aria-checked") === "true", "Selected context is accessible");
+ if (expected !== undefined) assert(checked.dataset.contextMenuItem === `review-context-${expected}`, "Global context choice survives session switches and reopening");
+ const mark = checked.querySelector<HTMLElement>('.context-menu-check')!;
+ assert(mark && mark.getBoundingClientRect().left > checked.querySelector('.context-menu-label')!.getBoundingClientRect().right, "Checkmark is on the right");
+ await action("screenshot", "review-menu.png");
+ document.querySelector<HTMLButtonElement>(`[data-context-menu-item="review-context-${lines}"]`)!.click();
+ await frame();
+}
+const headers = () => [...document.querySelectorAll<HTMLButtonElement>(".review-history-file-header")];
+const scroller = () => document.querySelector<HTMLElement>(".review-scroll")!;
+async function ready() { await until(() => document.querySelector(".review-history")?.getAttribute("aria-busy") === "false", "Review read must settle"); assert(!document.querySelector('[role="alert"]'), document.querySelector('[role="alert"]')?.textContent ?? "Review error"); }
+async function mount(session: SessionSummary, wait = true) {
+ useAppStore.setState({ activeSessionId: session.id, sessions: [session], messages: [], isRunning: false });
+ flushSync(() => root.render(<main className="fixture"><p className="fixture-label">受控测试数据 · 原生审阅实现预览</p><div className="fixture-panel"><ReviewTab /></div></main>));
+ if (wait) await ready();
+}
+window.reviewProbe = async () => {
+ const checks: string[] = [];
+ const seed = await action("seed") as { session: SessionSummary; other: SessionSummary; round: string; latest: string; firstSnapshot: string; late: UiMessage };
+ await mount(seed.session);
+ await contextLines(3, 3);
+ assert(headers().some(node => node.textContent?.includes("latest.txt")), "Latest ignores the newer no-edit conversation");
+ const settingsStyle = getComputedStyle(document.querySelector('.review-settings-button')!);
+ assert(settingsStyle.borderTopWidth === "0px", "Settings dots have no circular border");
+ assert(getComputedStyle(headers()[0]).backgroundColor === "rgba(0, 0, 0, 0)", "File buttons have no permanent fill");
+ checks.push("latest-skips-no-edit-round");
+ const fileMenu = async (index = 0) => {
+ document.querySelectorAll<HTMLButtonElement>('.review-file-menu-button')[index].click();
+ await until(() => !!document.querySelector('[data-context-menu-item="review-open-external"]'), "File menu opens");
+ };
+ await fileMenu();
+ assert(document.querySelector<HTMLButtonElement>('[data-context-menu-item="review-open-internal"]')!.disabled, "Missing file manager disables internal open");
+ assert(headers()[0].getAttribute('aria-expanded') === 'false', "Menu does not expand the file");
+ document.querySelector<HTMLButtonElement>('[data-context-menu-item="review-open-external"]')!.click();
+ await until(() => !document.querySelector('[data-context-menu-item="review-open-external"]'), "File menu closes after action");
+ await until(async () => (await action('opened') as unknown[]).length === 1, "External open reaches OS boundary");
+ const opened = await action('opened') as {path:string;sessionId:string}[];
+ assert(opened.length === 1 && opened[0].path.endsWith('latest.txt') && opened[0].sessionId === seed.session.id, "External action opens resolved current file with owning session");
+ await fileMenu();
+ const fileItems = [...document.querySelectorAll<HTMLButtonElement>('[data-context-menu-item]')];
+ assert(fileItems.map(item => item.dataset.contextMenuItem).join(',') === 'review-open-internal,review-open-external,review-open-folder', "Folder action follows the two open actions");
+ assert(!fileItems[2].disabled, "System folder action does not require a plugin");
+ fileItems[2].click();
+ await until(async () => (await action('revealed') as unknown[]).length === 1, "Folder action reaches OS file manager boundary");
+ const revealed = await action('revealed') as {path:string;sessionId:string}[];
+ assert(revealed[0].path.endsWith('latest.txt') && revealed[0].sessionId === seed.session.id, "Folder action uses exact resolved file and owning session");
+ checks.push('open-containing-folder-through-system-file-manager');
+ useAppStore.setState({ pluginViews: await api.listPluginViews() }); await frame();
+ await fileMenu();
+ assert(!document.querySelector<HTMLButtonElement>('[data-context-menu-item="review-open-internal"]')!.disabled, "Loaded file manager enables internal open");
+ document.querySelector<HTMLButtonElement>('[data-context-menu-item="review-open-internal"]')!.click();
+ await until(() => useAppStore.getState().workPanelTabs.some(tab => tab.location === 'latest.txt' && tab.resource === 'pi.file-manager/manager'), "Internal action opens the file manager tab");
+ checks.push('file-menu-disabled-internal-loaded-plugin-and-external-current-file');
+ await action("screenshot", "review-latest.png");
+ assert(!select('对话轮次'), "History selector is hidden by default");
+ assert(!document.querySelector('select[aria-label="上下文"]'), "No main context selector");
+ await mode(true);
+ await until(() => !!select('对话轮次'), "History adds its own row");
+ const roundSelect = select("对话轮次");
+ assert(roundSelect.getBoundingClientRect().height <= 30, "History selector stays compact");
+ assert(parseFloat(getComputedStyle(roundSelect).columnGap) >= 10, 'Native trigger reserves space before its arrow');
+ for (const count of [1, 3]) {
+ const geometry = roundSelect.cloneNode(true) as HTMLSelectElement;
+ geometry.replaceChildren(...Array.from({ length: count }, (_, index) => new Option(`Round ${index}`, String(index), index === 0, index === 0)));
+ roundSelect.parentElement!.append(geometry);
+ try { checkSelectStyle(geometry); } finally { geometry.remove(); }
+ }
+ checks.push('native-review-select-sidebar-colors-and-outer-only-corners');
+ await choose("对话轮次", seed.round); await ready();
+ assert(headers().length === 3, "Workspace, delegated and approved outside changes share one file list");
+ assert(headers()[2].querySelector('.review-change-card-path')?.textContent === '.../review-open-tests-source.mjs', "Real outside Write shows only basename with three-dot prefix");
+ assert(getComputedStyle(headers()[2].querySelector('.review-change-card-path')!).direction === 'ltr', "Outside prefix must stay before the filename visually");
+ assert(headers()[2].title.includes('outside') && !headers()[2].title.includes('/workspace/'), "Outside title retains actual path, without prepending workspace");
+ headers()[2].click(); await until(() => document.querySelectorAll('.review-history-file-body').length === 1, "Outside file expands");
+ await fileMenu(2);
+ assert(!document.querySelector('[data-context-menu-item="review-open-internal"]'), "Outside files omit internal open entirely");
+ assert(document.querySelectorAll('[data-context-menu-item]').length === 2, "Outside menu has only external open and folder");
+ assert(document.querySelector('.context-menu')!.getBoundingClientRect().width < 180, "File menu is compact");
+ document.querySelector<HTMLButtonElement>('[data-context-menu-item="review-open-external"]')!.click();
+ await until(async () => (await action('opened') as unknown[]).length === 2, "Outside open reaches actual reviewed-file service");
+ await fileMenu(2); document.querySelector<HTMLButtonElement>('[data-context-menu-item="review-open-folder"]')!.click();
+ await until(async () => (await action('revealed') as unknown[]).length === 2, "Outside folder reaches actual reviewed-file service");
+ checks.push('outside-files-open-and-reveal-through-snapshot-no-internal-option');
+ await until(() => document.querySelector('.review-history-file-body')?.textContent?.includes('outside = true') === true, "Outside file has real captured diff");
+ assert(!document.querySelector('.review-change-rollback'), "Outside snapshot does not grant rollback writes");
+ headers()[2].click(); await frame();
+ checks.push('real-approved-outside-write-capture-display-and-safe-rollback');
+ assert(headers()[0].textContent?.includes("long.ts"), "Files preserve original order");
+ headers()[0].click();
+ await until(() => document.querySelectorAll(".review-history-record").length === 2, "All same-file change records expand together");
+ assert(document.querySelectorAll('.review-history-file-body .review-change-card-actions').length === 1, "One action bar per file");
+ assert(document.querySelectorAll('.review-change-copy').length === 1 && document.querySelectorAll('.review-change-rollback').length === 1, "Exactly one copy and rollback for all operations");
+ assert(!document.querySelector('.review-history-file-body')!.textContent?.includes('修改记录'), "No per-operation title");
+ checks.push('one-file-one-copy-and-rollback-no-record-titles');
+ assert(!document.querySelector(".review-history-root"), "No extra execution-root row in the diff");
+ assert(document.querySelectorAll(".review-line-number").length > 0, "Old and new line numbers render");
+ await contextLines(5);
+ await until(() => document.querySelector('.review-change-diff')?.textContent?.includes("line_025") === true, "5-line context is loaded from bounded history");
+ assert(!document.querySelector('.review-change-diff')?.textContent?.includes("line_001"), "No full-file context is rendered");
+ assert(!document.querySelector('.review-change-diff')?.textContent?.includes("external-current-only"), "Current disk never supplies historical context");
+ assert(!document.querySelector('.review-history-file-body')!.textContent?.includes('差异过大'), "3100-line file with small edits stays reviewable");
+ checks.push("trimmed-3100-line-file-keeps-numbered-finite-context");
+ checks.push("hover-menu-only-1-3-5-context-and-numbered-lines");
+ const nested = [...scroller().querySelectorAll<HTMLElement>("*")].filter(node => ["auto", "scroll"].includes(getComputedStyle(node).overflowY) && node.scrollHeight > node.clientHeight + 1);
+ assert(nested.length === 0, "No nested vertical scrolling in expanded files");
+ assert(scroller().scrollHeight > scroller().clientHeight, "Outer review scrolls");
+ scroller().scrollTop = 420; await frame();
+ const box = headers()[0].getBoundingClientRect(), outer = scroller().getBoundingClientRect();
+ const stickyTop = outer.top + parseFloat(getComputedStyle(scroller()).paddingTop);
+ assert(Math.abs(box.top - stickyTop) <= 2, `File header sticks below toolbar: ${box.top}/${stickyTop}`);
+ assert(document.elementFromPoint(box.left + 20, box.top + box.height / 2)?.closest(".review-history-file-header"), "Sticky header is not covered");
+ await action("screenshot", "review-normal.png");
+ await action("resize", 420); await frame(); await frame();
+ assert(scroller().getBoundingClientRect().width <= 420, "Narrow viewport applied");
+ assert(headers()[0].getBoundingClientRect().right <= window.innerWidth + 1, "Narrow header fits");
+ assert(Math.abs(headers()[0].getBoundingClientRect().top - scroller().getBoundingClientRect().top - parseFloat(getComputedStyle(scroller()).paddingTop)) <= 2, "Narrow sticky header is visible");
+ await action("screenshot", "review-narrow.png");
+ checks.push("single-outer-scroll-normal-narrow-sticky-uncovered");
+ await action("resize", 920); scroller().scrollTop = 0; await frame();
+ const copy = document.querySelector<HTMLButtonElement>(".review-change-copy")!; copy.click();
+ await until(() => copy.classList.contains("copied"), "Copy action succeeds");
+ assert((await action("clipboard") as string).includes("@@"), "Copied text is a diff, not line-number UI");
+ assert((await action("clipboard") as string).includes("line_040 = 400"), "File copy includes every recorded operation");
+ document.querySelector<HTMLButtonElement>(".review-change-rollback")!.click();
+ await until(() => useAppStore.getState().toasts.length > 0, "Hash conflict remains visible");
+ assert((await action("readCurrent") as string).includes("external-current-only"), "Conflict rollback leaves user edits untouched");
+ checks.push("copy-and-existing-hash-guarded-rollback");
+ document.querySelector<HTMLButtonElement>(".review-settings-button")!.click();
+ await until(() => !!document.querySelector('[data-context-menu-item="review-wrap"]'), "Word wrap menu opens");
+ document.querySelector<HTMLButtonElement>('[data-context-menu-item="review-wrap"]')!.click();
+ await until(() => !!document.querySelector('.review-history.is-nowrap'), "Word wrap can be disabled");
+ assert(getComputedStyle(document.querySelector('.diff-line-text')!).whiteSpace === "pre", "Disabled wrapping preserves lines");
+ document.querySelector<HTMLButtonElement>(".review-settings-button")!.click();
+ await until(() => !!document.querySelector('[data-context-menu-item="review-wrap"]'), "Word wrap menu reopens");
+ document.querySelector<HTMLButtonElement>('[data-context-menu-item="review-wrap"]')!.click();
+ await until(() => !document.querySelector('.review-history.is-nowrap'), "Word wrap restores");
+
+ headers()[0].click(); await frame(); assert(!document.querySelector(".review-history-file-body"), "File can collapse after browsing");
+ await mode(false); await ready();
+ await action("late");
+ useAppStore.setState({ messages: [seed.late] }); await ready();
+ assert(headers().some(node => node.textContent?.includes("latest.txt")), "Late old delegate does not take over Latest");
+ await action("restart");
+ await mount(seed.other); assert(headers().length === 0, "Other session has no leaked files");
+ await contextLines(1, 5);
+ flushSync(() => root.render(null));
+ await mount(seed.other); await contextLines(1, 1);
+ await mount(seed.session); assert(headers().some(node => node.textContent?.includes("latest.txt")), "Persisted history survives restart");
+ await contextLines(1, 1);
+ requestReviewFocus([seed.firstSnapshot], { expand: true, sessionId: seed.session.id }); await ready();
+ await until(() => headers()[0]?.getAttribute("aria-expanded") === "true", "Chat file request finds old round and expands file");
+ checks.push("late-delegate-session-isolation-restart-and-focus");
+ await until(() => document.querySelector('.review-change-diff')?.textContent?.includes('line_029') === true && !document.querySelector('.review-change-card-body-content [role="status"]'), 'Remembered one-line context reaches the actual diff');
+ assert(!document.querySelector('.review-change-diff')?.textContent?.includes('line_028'), 'Remembered context does not expand to three or five lines');
+ checks.push('global-context-choice-survives-session-switch-and-panel-reopen');
+ await contextLines(3, 1); await frame(); scroller().scrollTop = 0; await frame();
+ await action("screenshot", "review-overview.png");
+ await mount(seed.other);
+ await action("holdReads");
+ await mount(seed.session, false);
+ await action("readBlocked");
+ await mount(seed.other, false);
+ await action("releaseReads"); await ready();
+ assert(headers().length === 0, "An old session read cannot populate the new session");
+ await mount(seed.session);
+ await mode(false); await ready();
+ await action("runningStart"); useAppStore.setState({ isRunning: true }); await ready();
+ assert(headers().some(node => node.textContent?.includes("latest.txt")), "Empty running round keeps prior modified round");
+ const live = await action("runningWrite") as UiMessage;
+ useAppStore.setState({ messages: [live] }); await ready();
+ await until(() => headers().some(node => node.textContent?.includes("running.txt")), "First live modification becomes Latest");
+ await action("runningEnd"); useAppStore.setState({ isRunning: false }); await ready();
+ checks.push("inflight-session-switch-and-first-live-modification");
+ await mode(true); await choose("对话轮次", seed.round); await ready();
+ await action('resetCurrent'); headers()[0].click();
+ await until(() => !!document.querySelector('.review-change-rollback'), "Grouped rollback is reachable from file footer");
+ document.querySelector<HTMLButtonElement>('.review-change-rollback')!.click();
+ await until(() => !!document.querySelector('.review-history-file-body .is-rolled-back'), "One grouped action marks every file record rolled back");
+ const restored = await action('readCurrent') as string;
+ assert(restored.includes('line_030 = 30;') && restored.includes('line_040 = 40;') && restored.includes('line_080 = 80;'), "File rollback restores the state before the first operation");
+ checks.push('single-file-action-rolls-back-entire-chain');
+ // Presentation-only fixture: this does not claim outside-workspace capture.
+ const outside = { ...groupReviewFiles([{ message: seed.late }])[0], root: undefined, path: '/outside/deep/review-open-tests-source.mjs' };
+ flushSync(() => root.render(<ReviewHistoryFile file={outside} sessionId={seed.session.id} context={3} disabled={false} onChanged={() => {}} />));
+ assert(document.querySelector('.review-change-card-path')?.textContent === '.../review-open-tests-source.mjs', "Absolute file labels hide directory prefixes");
+ assert(headers()[0].title === outside.path, "Full source path remains available in title");
+ checks.push('outside-path-display-only-basename-and-full-title');
+ await mount(seed.session); await contextLines(1);
+ return { checks };
+};
+
+// A fresh renderer module graph must read the same choice from the profile.
+window.reviewReloadProbe = async () => {
+ const seed = await action('currentSeed') as { session: SessionSummary; firstSnapshot: string };
+ await mount(seed.session);
+ await contextLines(1, 1);
+ requestReviewFocus([seed.firstSnapshot], { expand: true, sessionId: seed.session.id }); await ready();
+ await until(() => document.querySelector('.review-change-diff')?.textContent?.includes('line_029') === true && !document.querySelector('.review-change-card-body-content [role="status"]'), 'Reloaded renderer restores one-line context in captured diff');
+ assert(!document.querySelector('.review-change-diff')?.textContent?.includes('line_028'), 'Reloaded renderer does not revert to the default context');
+ return { checks: ['global-context-choice-survives-renderer-reload'] };
+};