Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(review): synchronize disclosure, session focus, and syntax
new-Beginner1fc3736a20c6
diff --git a/apps/desktop/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsxindex 9093a36d3..fd010bc9a 100644--- a/apps/desktop/src/components/Markdown.tsx+++ b/apps/desktop/src/components/Markdown.tsx@@ -168,7 +168,7 @@ function tokenStyle(token: ThemedToken): CSSProperties | undefined {}/* Rows are cached by reference in the line cache, so settled lines memo-skip. */-const TokenLine = memo(function TokenLine({ line }: { line: ThemedToken[] }) {+export const TokenLine = memo(function TokenLine({ line }: { line: ThemedToken[] }) {return (<>{line.map((token, i) => (@@ -180,7 +180,7 @@ const TokenLine = memo(function TokenLine({ line }: { line: ThemedToken[] }) {);});-function useHighlightedTokens(+export function useHighlightedTokens(code: string,lang: string,): ThemedToken[][] | null {diff --git a/apps/desktop/src/components/ReviewChangeCard.tsx b/apps/desktop/src/components/ReviewChangeCard.tsxindex a6e0ee57c..bc2a299c3 100644--- a/apps/desktop/src/components/ReviewChangeCard.tsx+++ b/apps/desktop/src/components/ReviewChangeCard.tsx@@ -9,12 +9,13 @@ import type {ReviewContextResult,} from "@pi-desktop/shared";import { api } from "../lib/api";-import { numberedReviewHunks, reviewFilePathLabel, reviewLineNumber } from "../lib/review-history";+import { numberedReviewHunks, reviewFilePathLabel } from "../lib/review-history";import { reviewChangeFromMessage } from "../lib/workspace-review";import { useAppStore } from "../stores/app-store";import { useCopy } from "./Markdown";import { cx } from "./ui";import { IconCheck, IconChevronRight, IconCopy, IconSnapshot } from "./icons";+import { ReviewDiffHunk } from "./ReviewDiffHunk";/* Git-status letters carry the status without relying on color alone; thelocalized word stays in the row's accessible name. */@@ -37,9 +38,9 @@ export function reviewDiffText(change: Pick<ReviewChange, "hunks">): string {.join("\n");}-export function ReviewChangeDetails({ message, compact = false, contextLines = 3, sessionId, onChanged, numbered = false, actions = true }: {+export function ReviewChangeDetails({ message, compact = false, contextLines = 3, sessionId, onChanged, numbered = false, actions = true, highlightCode = false }: {message: UiMessage; compact?: boolean; contextLines?: ReviewContextLines;- sessionId?: string; onChanged?: () => void; numbered?: boolean; actions?: boolean;+ sessionId?: string; onChanged?: () => void; numbered?: boolean; actions?: boolean; highlightCode?: boolean;}) {const { t } = useTranslation();const change = reviewChangeFromMessage(message);@@ -88,25 +89,8 @@ export function ReviewChangeDetails({ message, compact = false, contextLines = 3<div className="review-change-note">{t("panel.review.tooLarge")}</div>) : displayChange.hunks.length > 0 ? (<div className="review-change-diff">- {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={line.type === "del" ? "old" : "new"}- aria-label={reviewLineNumber(line) === null ? undefined : t(line.type === "del" ? "panel.review.oldLine" : "panel.review.newLine", { line: reviewLineNumber(line) })}>- {reviewLineNumber(line)}- </span>}- {!numbered && <span className="diff-line-sign" aria-hidden>- {line.type === "add" ? "+" : line.type === "del" ? "−" : " "}- </span>}- <span className="diff-line-text">{line.text}</span>- </div>- ))}- </div>- ))}+ {hunks.map((hunk, hunkIndex) => <ReviewDiffHunk key={`${hunk.header}-${hunkIndex}`}+ hunk={hunk} path={displayChange.path} numbered={numbered} highlightCode={highlightCode} />)}</div>) : (<div className="review-change-note">{t("panel.review.noLineDetails")}</div>diff --git a/apps/desktop/src/components/ReviewDiffHunk.tsx b/apps/desktop/src/components/ReviewDiffHunk.tsxnew file mode 100644index 000000000..03c79ffbc--- /dev/null+++ b/apps/desktop/src/components/ReviewDiffHunk.tsx@@ -0,0 +1,63 @@+import { useMemo } from "react";+import { useTranslation } from "react-i18next";+import type { ThemedToken } from "shiki";+import type { NumberedReviewLine } from "../lib/review-history";+import { reviewLineNumber } from "../lib/review-history";+import { langForPath } from "../lib/tool-presentation";+import { TokenLine, useHighlightedTokens } from "./Markdown";+import { cx } from "./ui";++type Hunk = { header: string; lines: NumberedReviewLine[] };+type HunkProps = { hunk: Hunk; path: string; numbered: boolean; highlightCode: boolean };++/** A hunk has two independent grammar streams; diff headers/EOF markers are not source. */+function sourceViews(hunk: Hunk) {+ const before: string[] = [], after: string[] = [];+ const indices = hunk.lines.map(line => {+ const marker = line.text === "\\ No newline at end of file";+ return {+ before: marker || line.type === "add" ? null : before.push(line.text) - 1,+ after: marker || line.type === "del" ? null : after.push(line.text) - 1,+ };+ });+ return { before: before.join("\n"), after: after.join("\n"), indices };+}++/** Only the local Review reader opts in; inline/legacy diffs never load a grammar. */+export function ReviewDiffHunk(props: HunkProps) {+ return props.highlightCode ? <HighlightedHunk {...props} /> : <HunkLines hunk={props.hunk} numbered={props.numbered} />;+}++function HighlightedHunk({ hunk, path, numbered }: HunkProps) {+ const views = useMemo(() => sourceViews(hunk), [hunk]);+ const language = langForPath(path);+ const before = useHighlightedTokens(views.before, language);+ const after = useHighlightedTokens(views.after, language);+ const tokens = hunk.lines.map((line, index) => {+ const position = views.indices[index];+ return line.type === "del" ? before?.[position.before ?? -1] : after?.[position.after ?? -1];+ });+ return <HunkLines hunk={hunk} numbered={numbered} tokens={tokens} />;+}++function HunkLines({ hunk, numbered, tokens }: {+ hunk: Hunk; numbered: boolean; tokens?: (ThemedToken[] | undefined)[];+}) {+ const { t } = useTranslation();+ return <div className="diff-hunk">+ <div className="diff-line hunk"><span className="diff-line-text">{hunk.header}</span></div>+ {hunk.lines.map((line, index) => {+ const number = reviewLineNumber(line), rowTokens = tokens?.[index];+ return <div className={cx("diff-line", line.type)} key={index}>+ {numbered && <span className="review-line-number" data-side={line.type === "del" ? "old" : "new"}+ aria-label={number === null ? undefined : t(line.type === "del" ? "panel.review.oldLine" : "panel.review.newLine", { line: number })}>+ {number}+ </span>}+ {!numbered && <span className="diff-line-sign" aria-hidden>+ {line.type === "add" ? "+" : line.type === "del" ? "−" : " "}+ </span>}+ <span className="diff-line-text">{rowTokens ? <TokenLine line={rowTokens} /> : line.text}</span>+ </div>;+ })}+ </div>;+}diff --git a/apps/desktop/src/components/workpanel/ReviewHistoryFile.tsx b/apps/desktop/src/components/workpanel/ReviewHistoryFile.tsxindex 69c4cc418..8581b5f5d 100644--- a/apps/desktop/src/components/workpanel/ReviewHistoryFile.tsx+++ b/apps/desktop/src/components/workpanel/ReviewHistoryFile.tsx@@ -1,4 +1,4 @@-import { useEffect, useId, useState } from "react";+import { useEffect, useId } from "react";import { useTranslation } from "react-i18next";import type { ReviewContextLines } from "@pi-desktop/shared";import { reviewFilePathLabel, type ReviewFileGroup } from "../../lib/review-history";@@ -10,22 +10,22 @@ import { IconChevronRight, IconMore } from "../icons";import { ReviewFileIcon } from "../ReviewFileIcon";import { ReviewFileActions } from "./ReviewFileActions";-export function ReviewHistoryFile({ file, sessionId, context, focusSeq, focusSnapshots, expandFocus, disabled, onChanged }: {+export function ReviewHistoryFile({ file, sessionId, context, open, onOpenChange, focusSeq, focusSnapshots, expandFocus, disabled, onChanged }: {file: ReviewFileGroup; sessionId: string; context: ReviewContextLines;+ open: boolean; onOpenChange: (id: string, open: boolean) => void;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]);+ if (focusSeq && expandFocus && file.entries.some(entry => focusSnapshots?.includes(entry.change.snapshotId))) onOpenChange(file.id, true);+ }, [focusSeq, expandFocus, file, focusSnapshots, onOpenChange]);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)}>+ <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={() => onOpenChange(file.id, !open)}><ReviewFileIcon path={file.path} /><span className="review-file-label"><span className="review-change-card-path" data-outside-path={reviewFilePathLabel(file.path) !== file.path || undefined}>{reviewFilePathLabel(file.path)}</span><span className="review-file-disclosure"><IconChevronRight size={11} /></span>@@ -41,7 +41,7 @@ export function ReviewHistoryFile({ file, sessionId, context, focusSeq, focusSna<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} />+ <ReviewChangeDetails message={entry.message} compact numbered highlightCode actions={false} sessionId={sessionId} contextLines={context} /></div>)}<ReviewFileActions file={file} sessionId={sessionId} context={context} disabled={disabled} onChanged={onChanged} /></div>}diff --git a/apps/desktop/src/components/workpanel/ReviewHistoryPanel.tsx b/apps/desktop/src/components/workpanel/ReviewHistoryPanel.tsxindex 0ded93d63..b53c88f12 100644--- a/apps/desktop/src/components/workpanel/ReviewHistoryPanel.tsx+++ b/apps/desktop/src/components/workpanel/ReviewHistoryPanel.tsx@@ -1,4 +1,4 @@-import { createElement, useEffect, useMemo, useRef, useState } from "react";+import { createElement, useCallback, 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";@@ -23,6 +23,7 @@ export function ReviewHistoryPanel({ sessionId }: { sessionId: string }) {const [catalog, setCatalog] = useState<ReviewTurnsPage>({ turns: [] });const [result, setResult] = useState<ReviewChangesPage>({ turnId: null, changes: [] });const [context, setContext] = useState<ReviewContextLines>(readReviewContextLines);+ const [openFiles, setOpenFiles] = useState<ReadonlySet<string>>(() => new Set());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);@@ -50,6 +51,24 @@ export function ReviewHistoryPanel({ sessionId }: { sessionId: string }) {return () => { active = false; if (generation.current === version) generation.current++; };}, [sessionId, selection, revision, running, reload]);const files = useMemo(() => groupReviewFiles(result.changes), [result]);+ const fileKeys = useMemo(() => files.map(file => `${result.turnId}:${file.id}`), [files, result.turnId]);+ // Match the existing keyed file lifecycle: keep choices on refresh, not across rounds or removed rows.+ useEffect(() => {+ setOpenFiles(current => {+ const next = new Set([...current].filter(key => !error && fileKeys.includes(key)));+ return next.size === current.size ? current : next;+ });+ }, [fileKeys, error]);+ const onFileOpenChange = useCallback((id: string, open: boolean) => {+ const key = `${result.turnId}:${id}`;+ setOpenFiles(current => {+ if (current.has(key) === open) return current;+ const next = new Set(current);+ if (open) next.add(key); else next.delete(key);+ return next;+ });+ }, [result.turnId]);+ const anyOpen = !error && fileKeys.some(key => openFiles.has(key));useEffect(() => {if (loading || !selection.snapshotId) return;scrollReviewToAnchor(@@ -77,7 +96,8 @@ export function ReviewHistoryPanel({ sessionId }: { sessionId: string }) {}} 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)} />+ }} wrap={wrap} onWrap={() => setWrap(value => !value)} anyOpen={anyOpen}+ disclosureDisabled={loading || error || !count} onToggleAll={() => setOpenFiles(new Set(anyOpen ? [] : fileKeys))} />{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")}@@ -95,6 +115,7 @@ export function ReviewHistoryPanel({ sessionId }: { sessionId: string }) {{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}+ open={openFiles.has(`${result.turnId}:${file.id}`)} onOpenChange={onFileOpenChange}focusSeq={selection.focusSeq} focusSnapshots={focus?.snapshotIds} expandFocus={focus?.expand}disabled={loading} onChanged={() => setReload(value => value + 1)} />)}</div>diff --git a/apps/desktop/src/components/workpanel/ReviewHistoryToolbar.tsx b/apps/desktop/src/components/workpanel/ReviewHistoryToolbar.tsxindex ccda85d75..50ec9e70d 100644--- a/apps/desktop/src/components/workpanel/ReviewHistoryToolbar.tsx+++ b/apps/desktop/src/components/workpanel/ReviewHistoryToolbar.tsx@@ -1,17 +1,25 @@import type { ReviewContextLines } from "@pi-desktop/shared";import { useTranslation } from "react-i18next";-import { ContextMenu, useContextMenu } from "../ContextMenu";+import { ContextMenu, useContextMenu, type ContextMenuItem } from "../ContextMenu";import { Select, TooltipButton } from "../ui";import { IconMore } from "../icons";-export function ReviewHistoryToolbar({ history, onHistory, count, additions, deletions, context, onContext, wrap, onWrap }: {+export function ReviewHistoryToolbar({ history, onHistory, count, additions, deletions, context, onContext, wrap, onWrap, anyOpen, disclosureDisabled, onToggleAll }: {history: boolean; onHistory: (history: boolean) => void;count: number; additions: number; deletions: number;context: ReviewContextLines; onContext: (context: ReviewContextLines) => void;wrap: boolean; onWrap: () => void;+ anyOpen: boolean; disclosureDisabled: boolean; onToggleAll: () => void;}) {const { t } = useTranslation();const settingsMenu = useContextMenu();+ const items: ContextMenuItem[] = [+ { 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),+ })) },+ { id: "review-toggle-all", label: t(anyOpen ? "panel.review.collapseAll" : "panel.review.expandAll"), disabled: disclosureDisabled, onSelect: onToggleAll },+ ];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"}@@ -24,14 +32,9 @@ export function ReviewHistoryToolbar({ history, onHistory, count, additions, del<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"), anchor: "bottom-end", 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),- })) },- ] });+ settingsMenu.openContextMenu(event, { label: t("panel.review.reviewSettings"), anchor: "bottom-end", items });}}><IconMore size={16} /></TooltipButton></div>- <ContextMenu state={settingsMenu.contextMenu} onClose={settingsMenu.closeContextMenu} />+ <ContextMenu state={settingsMenu.contextMenu && { ...settingsMenu.contextMenu, items }} onClose={settingsMenu.closeContextMenu} /></>;}diff --git a/apps/desktop/src/features/chat/transcript/TurnChangesCard.tsx b/apps/desktop/src/features/chat/transcript/TurnChangesCard.tsxindex b2128922c..04974b2b6 100644--- a/apps/desktop/src/features/chat/transcript/TurnChangesCard.tsx+++ b/apps/desktop/src/features/chat/transcript/TurnChangesCard.tsx@@ -56,7 +56,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 });const tab = toolWorkPanelTab("review");if (sessionId) openTabForSession(sessionId, tab);else openTab(tab);diff --git a/apps/desktop/src/lib/review-focus-request.ts b/apps/desktop/src/lib/review-focus-request.tsindex dc06a6dde..5f6ce1820 100644--- a/apps/desktop/src/lib/review-focus-request.ts+++ b/apps/desktop/src/lib/review-focus-request.ts@@ -2,9 +2,9 @@ import { useSyncExternalStore } from "react";/*** A one-shot "show these recorded changes" request from the transcript's- * per-turn change summary to the Review tab. Snapshot ids are unique per- * change, so the request needs no session key: a Review tab that does not- * hold the ids simply ignores it. Kept out of the app store because it is+ * per-turn change summary to the Review tab. The originating session prevents+ * a retained request from being replayed in another conversation after remount.+ * Kept out of the app store because it is* transient UI intent, not session or panel state.*/export type ReviewFocusRequest = {diff --git a/apps/desktop/test/review-presentation.test.mjs b/apps/desktop/test/review-presentation.test.mjsindex 4663bbbca..57911eada 100644--- a/apps/desktop/test/review-presentation.test.mjs+++ b/apps/desktop/test/review-presentation.test.mjs@@ -38,7 +38,7 @@ test("review and turn summaries share compact decorative file-type glyphs", asyntest("toolbar names the visible file count rather than the operation count", async t => {const ssr = await slotSsr(t);const { ReviewHistoryToolbar } = await ssr.load('/src/components/workpanel/ReviewHistoryToolbar.tsx');- const html = ssr.render(createElement(ReviewHistoryToolbar, {history:false,onHistory:()=>{},count:8,additions:302,deletions:2,context:3,onContext:()=>{},wrap:true,onWrap:()=>{}}));+ const html = ssr.render(createElement(ReviewHistoryToolbar, {history:false,onHistory:()=>{},count:8,additions:302,deletions:2,context:3,onContext:()=>{},wrap:true,onWrap:()=>{},anyOpen:false,disclosureDisabled:false,onToggleAll:()=>{}}));assert.match(html, /8 files/);assert.doesNotMatch(html, /recorded changes/);assert.match(html, /\+302/);diff --git a/apps/desktop/test/review-syntax.test.mjs b/apps/desktop/test/review-syntax.test.mjsnew file mode 100644index 000000000..a95bb21f6--- /dev/null+++ b/apps/desktop/test/review-syntax.test.mjs@@ -0,0 +1,90 @@+import assert from "node:assert/strict";+import test from "node:test";+import { createElement } from "react";+import { slotSsr } from "./helpers/slot-ssr.mjs";++function message(path, lines, extra = {}) {+ return {+ id: "syntax-message", role: "tool", content: "", createdAt: "2026-11-07",+ toolName: "Edit", toolStatus: "success",+ toolResult: { details: { root: "workspace", review: {+ version: 1, snapshotId: "syntax-snapshot", messageId: "syntax-message", path,+ operation: "edit", status: "modified", state: "active", additions: 1, deletions: 1,+ reversible: true, hunks: [{ header: "@@ -1,4 +1,4 @@", lines }], ...extra,+ } } },+ };+}+const styledTokens = html => [...html.matchAll(/<span style="([^"]+)">([^<]*)<\/span>/g)]+ .map(([, style, content]) => ({ style, content }));++async function setup(t, language) {+ const ssr = await slotSsr(t);+ const highlighter = await ssr.load("/src/lib/shiki.ts");+ if (!highlighter.tokenizeIncremental(null, "", language, "one-light")) {+ await new Promise(resolve => {+ const unsubscribe = highlighter.subscribeHighlighter(() => { unsubscribe(); resolve(); });+ highlighter.ensureLang(language);+ });+ }+ assert.ok(highlighter.tokenizeIncremental(null, "", language, "one-light"), "The real grammar must load before color assertions");+ const { ReviewChangeDetails, reviewDiffText } = await ssr.load("/src/components/ReviewChangeCard.tsx");+ const { HighlightedCode } = await ssr.load("/src/components/Markdown.tsx");+ return { ...ssr, highlighter, ReviewChangeDetails, reviewDiffText, HighlightedCode };+}++test("Review Python syntax uses exactly the regular code block's light/dark token styles", { timeout: 30000 }, async t => {+ const ssr = await setup(t, "python");+ const code = 'import json\ndef verify_case(root):\n # Keep strings separate from keywords\n return {"ok": True, "root": str(root)}';+ const row = message("src/verify_case.py", code.split("\n").map(text => ({ type: "add", text })));+ for (const theme of ["light", "dark"]) {+ document.documentElement.dataset.theme = theme;+ const reference = styledTokens(ssr.render(createElement(ssr.HighlightedCode, { code, lang: "py" })));+ assert.ok(reference.length > 6, "The regular block must have real syntax tokens");+ assert.ok(new Set(reference.map(token => token.style)).size > 2, "Keywords, comments and strings are not one uniform color");+ const html = ssr.render(createElement(ssr.ReviewChangeDetails, { message: row, numbered: true, highlightCode: true }));+ assert.deepEqual(styledTokens(html), reference, `Review and regular code must agree in ${theme} mode`);+ assert.doesNotMatch(html, /diff-line-sign/, "Review retains the single-number gutter");+ assert.match(html, /diff-line add/, "Syntax coloring does not replace the addition row");+ }+});++test("Review tokenizes before and after snippets independently, preserving multiline grammar state", { timeout: 30000 }, async t => {+ const ssr = await setup(t, "javascript");+ document.documentElement.dataset.theme = "light";+ const lines = [+ { type: "del", text: "/* old comment" },+ { type: "add", text: 'const added = "new";' },+ { type: "context", text: "still a comment" },+ { type: "del", text: "*/" },+ { type: "add", text: "const done = true;" },+ { type: "context", text: "return done;" },+ { type: "context", text: "\\ No newline at end of file" },+ ];+ const before = ssr.highlighter.tokenizeIncremental(null, '/* old comment\nstill a comment\n*/\nreturn done;', "javascript", "one-light");+ const after = ssr.highlighter.tokenizeIncremental(null, 'const added = "new";\nstill a comment\nconst done = true;\nreturn done;', "javascript", "one-light");+ const { TokenLine } = await ssr.load("/src/components/Markdown.tsx");+ const expected = [before.tokens[0], after.tokens[0], after.tokens[1], before.tokens[2], after.tokens[2], after.tokens[3]]+ .flatMap(line => styledTokens(ssr.render(createElement(TokenLine, { line }))));+ const row = message("src/check.mjs", lines);+ const html = ssr.render(createElement(ssr.ReviewChangeDetails, { message: row, numbered: true, highlightCode: true }));+ assert.deepEqual(styledTokens(html), expected);+ assert.match(html, /\\ No newline at end of file/);+ assert.equal(ssr.reviewDiffText(row.toolResult.details.review), lines.reduce((out, line) => out + `${line.type === "add" ? "+" : line.type === "del" ? "-" : " "}${line.text}\n`, "@@ -1,4 +1,4 @@\n").trimEnd());+});++test("Syntax coloring is opt-in; unknown languages and over-budget snippets remain escaped complete text", { timeout: 30000 }, async t => {+ const ssr = await setup(t, "javascript");+ const text = 'const value = "<script>unsafe</script>";';+ for (const props of [+ { message: message("file.js", [{ type: "add", text }]) },+ { message: message("file.unknown", [{ type: "add", text }]), highlightCode: true },+ { message: message("file.js", [{ type: "add", text: "x".repeat(2001) }]), highlightCode: true },+ { message: message("file.js", Array.from({ length: 801 }, () => ({ type: "add", text }))), highlightCode: true },+ ]) {+ const html = ssr.render(createElement(ssr.ReviewChangeDetails, props));+ assert.deepEqual(styledTokens(html), []);+ assert.doesNotMatch(html, /<script>/);+ if (props.message.toolResult.details.review.hunks[0].lines[0].text === text) assert.match(html, /<script>unsafe<\/script>/);+ else assert.ok(html.includes("x".repeat(2001)), "Highlight budget never truncates the captured source");+ }+});diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex d719f966e..b362e7043 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -4668,7 +4668,10 @@ instructions, memory and OAuth dialogs retain their existing bounded layouts.Local Review defaults to Last round (the latest modified user round). Itsscope 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+independent of the chat's loaded message window. Transcript summary focus requests+carry their originating session; switching back to another conversation cannot+replay that request there or empty its file list beneath a populated history option.+Rounds without changes do notreplace Latest. Main and delegated Write/Edit evidence share a file list; actualexecution roots distinguish identically named files. The file header opens allof that file's recorded operations in order, without claiming a net diff.@@ -4682,7 +4685,15 @@ Expanded file content has no fixed-height inner viewport or vertical scrollbar.The outer Review scroll reserves its vertical scrollbar gutter before overflowand owns vertical travel; the current file header sticksbelow 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+Word wrap, Context lines, and a plain Expand all / Collapse all action with no+trailing check. Any expanded visible file makes the action Collapse all;+only an entirely collapsed list makes it Expand all. It controls the same+per-file state as header clicks and focus requests, and closes the menu on+activation using its existing pointer/keyboard and focus-restoration behavior.+The action is disabled while loading, on read errors, or with no visible files.+Same-round refreshes preserve file choices; removed rows and changed rounds+reset them, and session isolation and default-collapsed behavior are unchanged.+Hovering Context lines opens a secondarymenu with 1/3/5 (first-use default 3); the choice is profile-wide, rememberedacross sessions, panel reopening and application restarts. Invalid or missingpreferences use 3, and unavailable storage never blocks the current selection.@@ -4739,5 +4750,16 @@ rows omit the separate add/delete sign column but retain change backgrounds andsummary signs; chat inline rows are unchanged. Word wrap toggles wrapping withoutintroducing nested vertical scrolling. Unsupportedhistorical context has an explicit explanation and retains recorded evidence.+Expanded local Review code reuses ordinary code blocks' Shiki grammars, token+styles, lazy loading and one-light / one-dark-pro themes, selected by the existing+file-name language resolver and active appearance. Each captured hunk tokenizes+before (context + deleted) and after (context + added) separately; deleted lines+use before tokens, others use after tokens. Hunk headers and EOF markers remain+plain. Only captured snippets supply context; coloring never reads current disk.+Unknown/unready languages and snippets over the existing 100,000-code-unit,+800-line or 2,000-code-unit-per-line budgets retain complete escaped plain text.+Only text ink changes: diff backgrounds, numbering, wrapping, selection, copy,+rollback and shared code-block defaults are unchanged. Inline/remote diffs do+not opt into highlighting or grammar loading.Remote Review retains its existing presentation. Chat inline review rows retaintheir 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.mdindex 9259b7708..7de8b8362 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -20185,6 +20185,11 @@ Scenario: E2E-REVIEW-ROUNDS (local desktop, implemented)isolated profile; verify both the checked menu option and actual diff contextretain that choice. Missing/invalid/blocked storage is unit-covered by`apps/desktop/test/review-preferences.test.mjs`.+- With two populated sessions, visit B, then click a file in A's real transcript+ turn-summary card and return to B. The retained focus request must belong to A;+ B must immediately retain its own recorded files. Cycling Last round → History+ must leave those files unchanged rather than repair an initially empty list,+ and B's selected history totals must agree with its visible file list.- Open several files from the per-turn summary with enough Review content toscroll. Each target comes into view inside Review while the conversation andwork-panel headers stay visible and the window content reaches the bottom edge.@@ -20195,6 +20200,14 @@ Scenario: E2E-REVIEW-ROUNDS (local desktop, implemented)retain trigger-relative placement across click points and fit narrow windows;no full after-image is cached; only the outer review scrolls; headers stick without toolbar overlap innormal/narrow layouts; copy and conflict protection survive; history restores.+ The settings menu's plain bulk action has no trailing check or checkbox role:+ all closed → Expand all → all open; any open/mixed → Collapse all → all closed.+ Manual single-file changes, including closing the last open file, immediately+ update its label. Keyboard End/Enter activates it, Escape cancels, and focus+ returns to the trigger. A consumed focus request cannot defeat bulk collapse;+ a new request still expands its target. Same-round refresh keeps choices,+ round/session changes do not leak them, and empty/loading lists disable the+ action. Word wrap and context choices retain their existing checks and effects.Toggle checks trail labels, summary dots have no circle, history options containdate/time plus true per-round recorded totals before the check and fit anarrow-safe field, including colored right-aligned totals when closed.@@ -20210,6 +20223,18 @@ Scenario: E2E-REVIEW-ROUNDS (local desktop, implemented)immediately after the visible filename appears only on hover/focus, right when closed and downwhen expanded, with a clear gap before statistics. Numbered diff rows have noindependent add/delete sign column.+ Expanded captured code must match ordinary code blocks' actual token colors+ and font styles in light and dark appearances, including a live theme switch.+ Syntax spans preserve the exact source text, transparent token backgrounds,+ existing diff fills and single gutter; the remaining copy/rollback, wrap,+ scrolling and session paths must still pass. `review-syntax.test.mjs` compares+ Python tokens against ordinary blocks, tests independent before/after multiline+ grammar state, escaped unknown/plain code and unchanged highlight budgets.+ For a Codex visual comparison, use the same complete Python/JS/TS snippet,+ language and appearance: verify keyword/string/comment/number categories and+ added/deleted/context rows separately. Exact palette/pixel equality additionally+ requires the same Codex version, theme, font and scale; do not infer those from+ a screenshot or change PI-Desktop's global theme to match one reference.File headers have no idlefill, and no execution-root row appears. File menus disable internal open whenthe plugin is absent, open its loaded view when available, and pass the resolveddiff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex c3a1cf306..cb04f45dc 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -2246,6 +2246,8 @@ sklm: {reviewScope: "Review scope",reviewSettings: "Review settings",wordWrap: "Word wrap",+ expandAll: "Alle ausklappen",+ collapseAll: "Alle einklappen",contextDisplay: "Context lines",fileActions: "Dateiaktionen",openInternal: "Intern öffnen",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex c97404057..9cdc2eba8 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -2266,6 +2266,8 @@ sklm: {reviewScope: "Review scope",reviewSettings: "Review settings",wordWrap: "Word wrap",+ expandAll: "Expand all",+ collapseAll: "Collapse all",contextDisplay: "Context lines",fileActions: "File actions",openInternal: "Open internally",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 522d6719d..32b2b25eb 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -2246,6 +2246,8 @@ sklm: {reviewScope: "Review scope",reviewSettings: "Review settings",wordWrap: "Word wrap",+ expandAll: "Expandir todo",+ collapseAll: "Contraer todo",contextDisplay: "Context lines",fileActions: "Acciones del archivo",openInternal: "Abrir internamente",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex bd4faf4a7..fa15af523 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -2246,6 +2246,8 @@ sklm: {reviewScope: "Review scope",reviewSettings: "Review settings",wordWrap: "Word wrap",+ expandAll: "Tout déplier",+ collapseAll: "Tout replier",contextDisplay: "Context lines",fileActions: "Actions du fichier",openInternal: "Ouvrir en interne",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex d92a183a6..c40d697fa 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -2262,6 +2262,8 @@ sklm: {reviewScope: "Review scope",reviewSettings: "Review settings",wordWrap: "Word wrap",+ expandAll: "모두 펼치기",+ collapseAll: "모두 접기",contextDisplay: "Context lines",fileActions: "파일 작업",openInternal: "내부에서 열기",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex c7e53dfae..603d1296b 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -2212,6 +2212,8 @@ export const ptBR = {reviewScope: "Review scope",reviewSettings: "Review settings",wordWrap: "Word wrap",+ expandAll: "Expandir tudo",+ collapseAll: "Recolher tudo",contextDisplay: "Context lines",fileActions: "Ações do arquivo",openInternal: "Abrir internamente",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 8f33e7d89..a7c2a076e 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -2256,6 +2256,8 @@ sklm: {reviewScope: "Review scope",reviewSettings: "Review settings",wordWrap: "Word wrap",+ expandAll: "Tümünü genişlet",+ collapseAll: "Tümünü daralt",contextDisplay: "Context lines",fileActions: "Dosya işlemleri",openInternal: "Dahili aç",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 1af0de723..59e36ab38 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -2241,6 +2241,8 @@ sklm: {reviewScope: "审阅范围",reviewSettings: "审阅设置",wordWrap: "自动换行",+ expandAll: "全部展开",+ collapseAll: "全部收起",contextDisplay: "上下文显示",fileActions: "文件操作",openInternal: "内部打开",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 1a8f0b34e..09d3218e8 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -2241,6 +2241,8 @@ sklm: {reviewScope: "审阅范围",reviewSettings: "审阅设置",wordWrap: "自动换行",+ expandAll: "全部展開",+ collapseAll: "全部收合",contextDisplay: "上下文显示",fileActions: "檔案操作",openInternal: "內部開啟",diff --git a/scripts/e2e-review-history.mjs b/scripts/e2e-review-history.mjsindex 660c95e91..f5d2eb327 100644--- a/scripts/e2e-review-history.mjs+++ b/scripts/e2e-review-history.mjs@@ -41,9 +41,10 @@ win=new BrowserWindow({show:false,width:920,height:760,useContentSize:true,webPrwin.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 'seed':seed=await seedReviewHistory(host,__dirname);return {session:seed.session,other:seed.other,populated:seed.populated,round:seed.round,latest:seed.latest,firstSnapshot:seed.firstSnapshot,late:seed.lateMessage};case 'currentSeed':return {session:seed.session,firstSnapshot:seed.firstSnapshot};case 'hoverReviewFile': {win.showInactive();const rect=await win.webContents.executeJavaScript("document.querySelector("+JSON.stringify(input?'.review-history-file-header':'.fixture-label')+").getBoundingClientRect().toJSON()");win.webContents.debugger.attach('1.3');try{await win.webContents.debugger.sendCommand('Input.dispatchMouseEvent',{type:'mouseMoved',x:rect.x+rect.width/2,y:rect.y+rect.height/2});}finally{win.webContents.debugger.detach();}return;}+case 'key': {const keys={End:['End',35],Return:['Enter',13],Escape:['Escape',27],Space:[' ',32]},key=keys[input];if(!key)throw new Error('Unsupported fixture key');win.webContents.debugger.attach('1.3');try{await win.webContents.debugger.sendCommand('Input.dispatchKeyEvent',{type:'keyDown',key:key[0],windowsVirtualKeyCode:key[1],...(input==='Return'?{text:'\\r'}:{})});await win.webContents.debugger.sendCommand('Input.dispatchKeyEvent',{type:'keyUp',key:key[0],windowsVirtualKeyCode:key[1]});}finally{win.webContents.debugger.detach();}return;}case 'late':return seed.appendLate();case 'runningStart':runningTurn=await seed.startRunning();return;case 'runningWrite':return seed.writeRunning(runningTurn);diff --git a/scripts/e2e/review-history-fixture.mjs b/scripts/e2e/review-history-fixture.mjsindex d996314ee..c21b9d9ff 100644--- a/scripts/e2e/review-history-fixture.mjs+++ b/scripts/e2e/review-history-fixture.mjs@@ -39,10 +39,23 @@ export async function seedReviewHistory(host, directory) {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);+ // A second populated session exposes stale focus requests that an empty session would hide.+ const populated = (await host.call("session.create", { title: "Other modified session", projectPath: root, mode: "agent" })).session;+ await host.call("session.configure", { id: populated.id, mode: "agent", permissionMode: "auto" });+ const { turnId: populatedTurn } = await host.call("session.beginTurn", { sessionId: populated.id });+ await host.call("session.appendMessage", { sessionId: populated.id, turnId: populatedTurn, message: {+ id: "other-modified-round", role: "user", content: "Other session modification", createdAt: new Date().toISOString(),+ } });+ const populatedWrite = await host.call("tools.execute", { sessionId: populated.id, turnId: populatedTurn, toolCallId: "other-write", toolName: "Write", args: { path: "other-session.txt", content: "Other session only\n" }, mode: "agent" });+ if (!populatedWrite.ok || !populatedWrite.content.review) throw new Error("Other session Write must produce review");+ await host.call("session.appendMessage", { sessionId: populated.id, turnId: populatedTurn, message: {+ id: "other-write-message", role: "tool", content: "", createdAt: new Date().toISOString(), toolName: "Write", toolCallId: "other-write", toolStatus: "success", toolResult: { details: populatedWrite.content },+ } });+ await end(populatedTurn);// 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,+ session, other, populated, 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", "运行中首次修改测试"),diff --git a/scripts/e2e/review-history.tsx b/scripts/e2e/review-history.tsxindex 2cbec5465..1c9f2ea84 100644--- a/scripts/e2e/review-history.tsx+++ b/scripts/e2e/review-history.tsx@@ -1,3 +1,6 @@+import { TurnChangesCard } from "../../apps/desktop/src/features/chat/transcript/TurnChangesCard";+import { SlotSessionProvider } from "../../apps/desktop/src/plugins/renderer-slots/use-slots";+import { currentReviewFocusRequest } from "../../apps/desktop/src/lib/review-focus-request";// 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";@@ -11,6 +14,7 @@ import { ReviewTab } from "../../apps/desktop/src/components/workpanel/ReviewTabimport { 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";+import { HighlightedCode } from "../../apps/desktop/src/components/Markdown";declare global {interface Window {@@ -46,6 +50,44 @@ function assertDisclosureFollowsFilename(header: HTMLElement) {const gap = header.querySelector('.review-file-disclosure')!.getBoundingClientRect().left - visibleTextRight;assert(gap >= 5 && gap <= 7, `Disclosure immediately follows the visible filename: gap=${gap}`);}+async function checkReviewSyntaxParity() {+ const line = () => document.querySelector<HTMLElement>('.review-change-diff .diff-line.add .diff-line-text');+ await until(() => (line()?.querySelectorAll(':scope > span[style]').length ?? 0) > 2, 'Captured TypeScript diff lazily acquires syntax tokens');+ const source = line()!.textContent!;+ const reference = document.createElement('div');+ reference.style.cssText = 'position:fixed;left:-10000px;top:0';+ document.body.append(reference);+ const referenceRoot = createRoot(reference);+ const rootTheme = document.documentElement.dataset.theme;+ const snapshot = (node: HTMLElement) => [...node.children].map(token => {+ const style = getComputedStyle(token);+ return { text: token.textContent, color: style.color, fontStyle: style.fontStyle, fontWeight: style.fontWeight, decoration: style.textDecorationLine };+ });+ let firstPalette = '';+ try {+ flushSync(() => referenceRoot.render(<HighlightedCode code={source} lang="ts" />));+ for (const theme of ['light', 'dark']) {+ document.documentElement.dataset.theme = theme;+ await until(() => {+ const actual = snapshot(line()!), expected = snapshot(reference);+ return actual.length > 2 && JSON.stringify(actual) === JSON.stringify(expected)+ && (theme === 'light' || JSON.stringify(actual) !== firstPalette);+ }, 'Review token colors/styles match ordinary code and react to the active theme');+ const actual = snapshot(line()!);+ if (theme === 'light') firstPalette = JSON.stringify(actual);+ assert(new Set(actual.map(token => token.color)).size > 1, 'Syntax uses more than one text color');+ assert(line()!.textContent === source, 'Coloring does not change captured code text');+ assert([...line()!.children].every(token => getComputedStyle(token).backgroundColor === 'rgba(0, 0, 0, 0)'), 'Tokens do not paint over diff backgrounds');+ assert(getComputedStyle(line()!.parentElement!).backgroundColor !== 'rgba(0, 0, 0, 0)', 'Addition row keeps its existing diff fill');+ assert(line()!.parentElement!.querySelectorAll('.review-line-number').length === 1, 'Syntax does not add a line-number column');+ }+ } finally {+ if (rootTheme === undefined) delete document.documentElement.dataset.theme;+ else document.documentElement.dataset.theme = rootTheme;+ referenceRoot.unmount(); reference.remove();+ }+ await until(() => JSON.stringify(snapshot(line()!)) === firstPalette, 'Restored light theme reaches Review before remaining interaction checks');+}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');@@ -112,15 +154,37 @@ async function contextLines(lines: 1 | 3 | 5, expected?: 1 | 3 | 5) {}const headers = () => [...document.querySelectorAll<HTMLButtonElement>(".review-history-file-header")];const scroller = () => document.querySelector<HTMLElement>(".review-scroll")!;+async function bulkMenu(expected: "全部展开" | "全部收起", disabled = false) {+ const trigger = document.querySelector<HTMLButtonElement>(".review-settings-button")!;+ trigger.focus({ preventScroll: true }); trigger.click();+ await until(() => !!document.querySelector('.context-menu.is-open') && document.activeElement?.hasAttribute('data-context-menu-root-item') === true, `Settings menu opens and focuses its first item (${expected}, disabled=${disabled}, files=${headers().map(node => node.textContent).join('|')})`);+ const item = document.querySelector<HTMLButtonElement>('[data-context-menu-item="review-toggle-all"]');+ assert(item, "Review settings includes a bulk expand/collapse action");+ assert(item.textContent === expected && item.disabled === disabled, "Bulk label follows actual visible file expansion");+ assert(item.getAttribute('role') === 'menuitem' && !item.hasAttribute('aria-checked') && !item.querySelector('.context-menu-check'), "Bulk action has neither a toggle role nor a trailing check");+ assert(document.querySelector('[data-context-menu-item="review-wrap"]')?.getAttribute('role') === 'menuitemcheckbox', "Word wrap retains its checked menu semantics");+ return item;+}+async function bulkClick(expected: "全部展开" | "全部收起") {+ (await bulkMenu(expected)).click();+ await until(() => !document.querySelector('.context-menu'), "Bulk action closes the shared menu");+}+function assertAllFilesOpen(open: boolean) {+ const nodes = headers();+ assert(nodes.length > 0, "Bulk assertions require a nonempty file list");+ assert(nodes.every(node => node.getAttribute('aria-expanded') === String(open)), "All visible file disclosures match the bulk action");+}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) {+async function mount(session: SessionSummary, wait = true, tools: readonly UiMessage[] = []) {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>));+ flushSync(() => root.render(<main className="fixture"><p className="fixture-label">受控测试数据 · 原生审阅实现预览</p>+ {tools.length > 0 && <SlotSessionProvider sessionId={session.id}><TurnChangesCard tools={tools} /></SlotSessionProvider>}+ <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 };+ const seed = await action("seed") as { session: SessionSummary; other: SessionSummary; populated: 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");@@ -206,6 +270,31 @@ window.reviewProbe = async () => {assert(!headers().some(header => header.textContent?.includes("zero-preview.txt")), "Both-zero file is absent from Review");assert(document.querySelector('.review-summary')?.textContent === '3 个文件', 'Five records across four paths must report only the three positive-counter files');checks.push("zero-counter-file-hidden-without-losing-native-evidence");+ assertAllFilesOpen(false);+ await bulkClick("全部展开"); assertAllFilesOpen(true);+ useAppStore.setState({ isRunning: true }); await ready(); assertAllFilesOpen(true);+ useAppStore.setState({ isRunning: false }); await ready(); assertAllFilesOpen(true);+ headers()[1].click(); await frame();+ assert(headers()[1].getAttribute('aria-expanded') === 'false' && headers()[0].getAttribute('aria-expanded') === 'true', "Single-file collapse creates a mixed state");+ const bulk = await bulkMenu("全部收起");+ await action('key', 'End');+ await until(() => document.activeElement === bulk, "Shared keyboard navigation reaches the bulk action");+ await action('key', 'Return');+ await until(() => !document.querySelector('.context-menu'), "Enter activates and dismisses the bulk menu");+ assertAllFilesOpen(false);+ assert(document.activeElement === document.querySelector('.review-settings-button'), "Menu activation restores trigger focus");+ checks.push('bulk-open-all-mixed-collapse-all-and-keyboard-menu-semantics');+ headers()[0].click(); await frame();+ await bulkClick("全部收起"); assertAllFilesOpen(false);+ headers()[0].click(); await frame(); headers()[0].click(); await frame();+ await bulkMenu("全部展开"); await action('key', 'Escape');+ await until(() => !document.querySelector('.context-menu'), "Escape cancels without changing file disclosures");+ assertAllFilesOpen(false);+ checks.push('bulk-label-tracks-single-file-and-last-manual-collapse');+ headers()[0].click(); await frame();+ await choose("对话轮次", seed.latest); await ready(); assertAllFilesOpen(false);+ await choose("对话轮次", seed.round); await ready(); assertAllFilesOpen(false);+ checks.push('bulk-state-preserved-on-refresh-not-retained-across-rounds');const selected = document.querySelector<HTMLElement>('.review-round-selected selectedcontent')!;await until(() => selected?.textContent?.includes('+7') === true, 'Native selectedcontent reflects the chosen round');const time = selected.querySelector<HTMLElement>('.review-turn-time')!, counts = selected.querySelector<HTMLElement>('.review-turn-counts')!;@@ -252,6 +341,8 @@ window.reviewProbe = async () => {await until(() => getComputedStyle(headers()[0].querySelector('.review-file-disclosure')!).visibility === 'hidden', 'Non-hovered disclosure disappears without consuming new space');checks.push('file-count-closed-select-layout-and-reserved-scrollbar');checks.push('one-file-one-copy-and-rollback-no-record-titles');+ await checkReviewSyntaxParity();+ checks.push('review-syntax-matches-regular-code-light-dark-without-layout-or-text-changes');assert(!document.querySelector(".review-history-root"), "No extra execution-root row in the diff");for (const row of document.querySelectorAll('.review-change-diff .diff-line:not(.hunk)')) {assert(row.querySelectorAll('.review-line-number').length === 1, 'Inline diff has exactly one line-number gutter');@@ -322,14 +413,35 @@ window.reviewProbe = async () => {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 bulkMenu("全部展开", true); await action('key', 'Escape');+ await until(() => !document.querySelector('.context-menu'), "Empty-list menu dismisses without leaked state");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);+ await bulkMenu("全部展开");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");+ const focusedAction = document.querySelector('[data-context-menu-item="review-toggle-all"]');+ if (focusedAction) assert(focusedAction.textContent === "全部收起", "An open menu follows focus-driven expansion");+ // Scroll events dismiss menus before the rendering-frame phase. A task yield alone is not that boundary.+ await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));+ if (document.querySelector('.context-menu')) {+ await action('key', 'Escape');+ await until(() => !document.querySelector('.context-menu'), "Focus-driven bulk label menu dismisses");+ }+ await bulkClick("全部收起"); assertAllFilesOpen(false);+ await frame(); assertAllFilesOpen(false);+ await action('holdReads');+ requestReviewFocus([seed.firstSnapshot], { expand: true, sessionId: seed.session.id });+ await action('readBlocked'); await action('releaseReads'); await ready();+ await until(() => headers()[0]?.getAttribute('aria-expanded') === 'true', "A new focus request can reopen after bulk collapse");+ await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));+ await bulkMenu("全部收起"); await action('key', 'Escape');+ await until(() => !document.querySelector('.context-menu'), "Focused-file menu dismisses");+ checks.push('bulk-collapse-overrides-consumed-focus-new-focus-still-expands');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');@@ -339,6 +451,8 @@ window.reviewProbe = async () => {await action("holdReads");await mount(seed.session, false);await action("readBlocked");+ await bulkMenu("全部展开", true); await action('key', 'Escape');+ await until(() => !document.querySelector('.context-menu'), "Loading-list bulk action stays disabled");await mount(seed.other, false);await action("releaseReads"); await ready();assert(headers().length === 0, "An old session read cannot populate the new session");@@ -361,11 +475,34 @@ window.reviewProbe = async () => {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={() => {}} />));+ flushSync(() => root.render(<ReviewHistoryFile file={outside} sessionId={seed.session.id} context={3} open={false} onOpenChange={() => {}} 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);+ // Visit B, click A's real transcript summary, then return to B without a new focus request.+ await mount(seed.populated);+ assert(headers().length === 1 && headers()[0].textContent?.includes('other-session.txt'), "Current session initially shows its own recorded file");+ await mount(seed.session, true, [seed.late]);+ document.querySelector<HTMLButtonElement>('.turn-changes-head')!.click();+ await until(() => document.querySelector('.turn-changes-head')?.getAttribute('aria-expanded') === 'true', "The real turn summary expands");+ await action('holdReads');+ document.querySelector<HTMLButtonElement>('.turn-changes-row')!.click();+ await action('readBlocked'); await action('releaseReads'); await ready();+ await until(() => headers().some(node => node.textContent?.includes('long.ts') && node.getAttribute('aria-expanded') === 'true'), "The real summary opens and expands its originating file");+ const sourceFocus = currentReviewFocusRequest();+ await mount(seed.populated);+ const returnedFiles = headers().map(node => node.querySelector('.review-change-card-path')?.textContent);+ const returnedTotals = select('对话轮次')?.selectedOptions[0]?.querySelector('.review-turn-counts')?.textContent;+ await mode(false); await ready(); await mode(true); await ready();+ const afterScopeCycle = headers().map(node => node.querySelector('.review-change-card-path')?.textContent);+ console.log('REVIEW_SELECTION_SWITCH ' + JSON.stringify({ returnedFiles, returnedTotals, afterScopeCycle, requestSession: sourceFocus?.sessionId }));+ assert(returnedFiles.length === 1 && returnedFiles[0] === 'other-session.txt', "Returning to a populated session must not show an empty list beneath another session's stale focus");+ assert(JSON.stringify(returnedFiles) === JSON.stringify(afterScopeCycle), "Last round / History cycling must not repair a missing initial file list");+ assert(sourceFocus?.sessionId === seed.session.id, "The transcript summary binds focus to its owning session");+ assert(select('对话轮次').selectedOptions[0]?.querySelector('.review-turn-counts')?.textContent === '+1 −0', "The selected history counts agree with the visible current-session file");+ checks.push('real-turn-summary-focus-is-scoped-across-returning-session-and-history-cycle');+ await mount(seed.session);return { checks };};