A desktop coding agent with free access to frontier models.
TypeScript
fix: safer undo keys, review bar and diff limits
Samrat Talukdar906f2152f1ce
diff --git a/apps/app/src/components/chat/message-list.tsx b/apps/app/src/components/chat/message-list.tsxindex 4efa03a1..228924d9 100644--- a/apps/app/src/components/chat/message-list.tsx+++ b/apps/app/src/components/chat/message-list.tsx@@ -130,7 +130,8 @@ import { cn } from "@/lib/utils"import { DevProfiler } from "@/react-app/shell/dev-profiler"import { groupMessages, isMessageGroup, getLastTextPart, getAggregateOnlyParts, getAssistantRenderGroups, getFileTitle, getMediaBadge, getMessageCompleted, getMessageCreated, formatMessageTimestamp, splitTurnAtAnswer, type UIMessageWithIndex, getMessagesText, getSafeFileDownloadUrl, getSafeFileRevealPath } from "./utils"import type { AnyToolPart } from "@/lib/tool-aggregate"-import { commandTemplateLabel, parseReviewReply } from "@/react-app/domains/session/commands/review-message"+import { commandTemplateLabel, reviewForTurn } from "@/react-app/domains/session/commands/review-message"+import { useSessionCommandBridge } from "@/react-app/domains/session/commands/session-commands-store"import { ReviewFixBar } from "@/react-app/domains/session/commands/review-fix-bar"import { resolveConnectorToolIdentity } from "@/react-app/domains/connections/connector-tool-identity"@@ -1233,6 +1234,8 @@ interface AssistantMessageGroupProps {items: UIMessageWithIndex[]isLastGroup: booleanisStreaming: boolean+ /** The text of the user message this group answers (a review turn offers "Fix these"). */+ turnUserText?: string}function collectMcpAppParts(items: UIMessageWithIndex[]): DynamicToolUIPart[] {@@ -1256,8 +1259,10 @@ function MessageGroup({items,isLastGroup,isStreaming,+ turnUserText,}: AssistantMessageGroupProps) {- const { onRevertToUserMessage, onForkAtMessage, showThinking, onRunCommand } = useMessageList()+ const { onRevertToUserMessage, onForkAtMessage, showThinking, onRunCommand, sessionId } = useMessageList()+ const commandBridge = useSessionCommandBridge(sessionId)const lastItem = items[items.length - 1]// Branch/revert must target a real server-side message id. Synthetic// client-side messages (e.g. session errors) don't exist on the server and@@ -1275,7 +1280,7 @@ function MessageGroup({// A review reply with issues (the engine's review layout) offers "Fix these" while it is the newest reply.const lastTextPart = lastTextMessage?.parts[0]const review = onRunCommand && isLastGroup && !isStreaming && lastItem.message.role === "assistant" && lastTextPart?.type === "text"- ? parseReviewReply(lastTextPart.text)+ ? reviewForTurn(turnUserText, lastTextPart.text): null// Leading messages without prose (tool/reasoning steps) render inline and@@ -1462,7 +1467,7 @@ function MessageGroup({</div>)}{review?.fixable && onRunCommand ? (- <ReviewFixBar review={review} onFix={() => onRunCommand("/fix")} />+ <ReviewFixBar review={review} disabled={commandBridge?.busy ?? false} onFix={() => onRunCommand("/fix")} />) : null}</div></DevProfiler>@@ -1472,6 +1477,7 @@ function MessageGroup({function sameMessageGroupProps(left: AssistantMessageGroupProps, right: AssistantMessageGroupProps): boolean {return left.isLastGroup === right.isLastGroup&& left.isStreaming === right.isStreaming+ && left.turnUserText === right.turnUserText&& left.items.length === right.items.length&& left.items.every((item, index) => (item.index === right.items[index]?.index@@ -1481,6 +1487,16 @@ function sameMessageGroupProps(left: AssistantMessageGroupProps, right: Assistanconst MemoizedMessageGroup = React.memo(MessageGroup, sameMessageGroupProps)+/** The text of the newest user message before `index` (the prompt an assistant group answers). */+function precedingUserText(messages: UIMessage[], index: number): string | undefined {+ for (let at = index - 1; at >= 0; at -= 1) {+ const message = messages[at]+ if (message?.role !== "user") continue+ return message.parts.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n")+ }+ return undefined+}+type StandaloneMessageProps = {message: UIMessageisLastMessage: boolean@@ -1623,6 +1639,7 @@ export function MessageList({ messages, status, activityStatus, retryStatus, synitems={item.messages}isLastGroup={item.messages.at(-1)?.index === messages.length - 1}isStreaming={isStreaming && item.messages.at(-1)?.index === messages.length - 1}+ turnUserText={precedingUserText(messages, item.messages[0]?.index ?? 0)}/>)}diff --git a/apps/app/src/react-app/domains/session/chat/session-page.tsx b/apps/app/src/react-app/domains/session/chat/session-page.tsxindex 675771c0..f4c682cd 100644--- a/apps/app/src/react-app/domains/session/chat/session-page.tsx+++ b/apps/app/src/react-app/domains/session/chat/session-page.tsx@@ -4,7 +4,7 @@ import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } froimport { usePanelRef } from "react-resizable-panels";import { DesktopUpdateButton } from "../../settings/state/desktop-updater-provider";import { BuildathonChip } from "../../buildathon/buildathon";-import { ArrowLeft, Cloud, Code2, FileDiff, FileText, Globe, ListChecks, Maximize2, MoreHorizontal, PanelRight, TextSearch, X, Zap } from "lucide-react";+import { ArrowLeft, Cloud, Code2, FileDiff, FileText, Gauge, Redo2, Undo2, Globe, ListChecks, Maximize2, MoreHorizontal, PanelRight, TextSearch, X, Zap } from "lucide-react";import { SessionCommandControls } from "../commands/session-command-controls";import { useSessionCommandBridge, useSessionCommandsStore } from "../commands/session-commands-store";@@ -1196,6 +1196,8 @@ export function SessionPage(props: SessionPageProps) {const commandSessionId = canRenderReactSurface && !props.primarySlot && !hasMainContentTakeover ? props.selectedSessionId : null;const commandBridge = useSessionCommandBridge(commandSessionId);const openChangesPanel = useSessionCommandsStore((state) => state.openChanges);+ const openStatusDialog = useSessionCommandsStore((state) => state.openStatus);+ const headerActions = useSessionCommandsStore((state) => (commandSessionId ? state.headerActions[commandSessionId] ?? null : null));const canGoBackInConversationHistory = !pendingConversationHistoryNavigation && canNavigateSelectedConversationHistory(conversationHistory,props.selectedWorkspaceId,@@ -1741,6 +1743,24 @@ export function SessionPage(props: SessionPageProps) {Find in conversation</DropdownMenuItem>) : null}+ {commandSessionId && headerActions ? (+ <DropdownMenuItem disabled={!headerActions.canUndo} onClick={() => void headerActions.undo()}>+ <Undo2 className="size-4" />+ Undo last turn+ </DropdownMenuItem>+ ) : null}+ {commandSessionId && headerActions?.canRedo ? (+ <DropdownMenuItem onClick={() => void headerActions.redo()}>+ <Redo2 className="size-4" />+ Redo+ </DropdownMenuItem>+ ) : null}+ {commandSessionId ? (+ <DropdownMenuItem onClick={() => openStatusDialog(commandSessionId)}>+ <Gauge className="size-4" />+ Status+ </DropdownMenuItem>+ ) : null}{commandSessionId ? (<DropdownMenuItem onClick={() => openChangesPanel(commandSessionId)}><FileDiff className="size-4" />diff --git a/apps/app/src/react-app/domains/session/commands/changes-panel.tsx b/apps/app/src/react-app/domains/session/commands/changes-panel.tsxindex c895a183..c5bee4c0 100644--- a/apps/app/src/react-app/domains/session/commands/changes-panel.tsx+++ b/apps/app/src/react-app/domains/session/commands/changes-panel.tsx@@ -14,6 +14,8 @@ import {CHANGES_SOURCE_LABEL,changeTotals,normalizeChanges,+ MAX_DIFF_LINES,+ patchLineCount,patchLines,type ChangedFile,type ChangesSource,@@ -30,7 +32,9 @@ const STATUS_BADGE: Record<ChangedFile["status"], string> = {};function DiffBody({ patch }: { patch: string }) {- const lines = useMemo(() => patchLines(patch), [patch]);+ const [showAll, setShowAll] = useState(false);+ const all = useMemo(() => patchLines(patch), [patch]);+ const lines = showAll ? all : all.slice(0, MAX_DIFF_LINES);if (!lines.length) {return <div className="px-3 py-2 text-xs text-muted-foreground">No line changes to show (a binary file, or only its mode changed).</div>;}@@ -53,6 +57,13 @@ function DiffBody({ patch }: { patch: string }) {<span className="whitespace-pre pr-4">{line.kind === "hunk" ? line.text : line.text || " "}</span></div>))}+ {lines.length < all.length ? (+ <div className="sticky left-0 px-3 py-2">+ <Button size="sm" variant="secondary" data-testid="changes-show-all" onClick={() => setShowAll(true)}>+ Show all {all.length.toLocaleString("en-US")} lines+ </Button>+ </div>+ ) : null}</div>);}@@ -169,7 +180,7 @@ function ChangesBody(props: SessionCommandTarget & { onClose: () => void }) {variant="secondary"data-testid="changes-review"disabled={reviewDisabled}- title={running ? "Wait for the agent to finish first" : "Ask the agent to review the uncommitted changes in this chat"}+ title={running ? "Wait for the agent to finish first" : "Ask the agent to review the project's uncommitted changes (the whole working tree)"}onClick={() => {if (!bridge) return;void bridge.runCommand("/review");@@ -217,7 +228,7 @@ function ChangesBody(props: SessionCommandTarget & { onClose: () => void }) {) : (<div className="flex flex-col gap-2">{files.map((file) => (- <FileRow key={`${source}:${file.path}`} file={file} defaultOpen={files.length <= 3} />+ <FileRow key={`${source}:${file.path}`} file={file} defaultOpen={files.length <= 3 && patchLineCount(file.patch) <= MAX_DIFF_LINES} />))}</div>)}diff --git a/apps/app/src/react-app/domains/session/commands/changes.ts b/apps/app/src/react-app/domains/session/commands/changes.tsindex 4a5d1481..7748f2f4 100644--- a/apps/app/src/react-app/domains/session/commands/changes.ts+++ b/apps/app/src/react-app/domains/session/commands/changes.ts@@ -83,3 +83,14 @@ export function patchLines(patch: string): PatchLine[] {while (lines.length && lines[lines.length - 1]?.kind === "context" && lines[lines.length - 1]?.text === "") lines.pop();return lines;}++/** A diff longer than this many lines is cut (a "Show all" button renders the rest) and never opens on its own. */+export const MAX_DIFF_LINES = 1500;++/** How many lines a patch has (cheap: counts newlines, no parsing). */+export function patchLineCount(patch: string): number {+ if (!patch) return 0;+ let count = 1;+ for (let at = patch.indexOf("\n"); at !== -1; at = patch.indexOf("\n", at + 1)) count += 1;+ return count;+}diff --git a/apps/app/src/react-app/domains/session/commands/review-fix-bar.tsx b/apps/app/src/react-app/domains/session/commands/review-fix-bar.tsxindex b082ab06..54c0d3d3 100644--- a/apps/app/src/react-app/domains/session/commands/review-fix-bar.tsx+++ b/apps/app/src/react-app/domains/session/commands/review-fix-bar.tsx@@ -1,4 +1,5 @@/** @jsxImportSource react */+import { useState } from "react";import { Wrench } from "lucide-react";import { Button } from "@/components/ui/button";@@ -15,6 +16,8 @@ const CHIP: Record<ReviewSeverity, string> = {/** Under a review reply with issues: how many of each severity, and "Fix these" (the engine's fix command). */export function ReviewFixBar(props: { review: ReviewSummary; disabled?: boolean; onFix: () => void }) {const total = props.review.issues.length;+ // One click sends one fix command; the bar goes away once its turn starts.+ const [sent, setSent] = useState(false);return (<div className="mx-auto flex w-full max-w-3xl flex-wrap items-center gap-2 px-2 md:px-10" data-testid="review-fix-bar">{REVIEW_SEVERITIES.filter((severity) => props.review.counts[severity] > 0).map((severity) => (@@ -30,8 +33,12 @@ export function ReviewFixBar(props: { review: ReviewSummary; disabled?: boolean;size="sm"className="h-7 rounded-full px-3 text-xs"data-testid="review-fix-these"- disabled={props.disabled}- onClick={props.onFix}+ disabled={props.disabled || sent}+ onClick={() => {+ if (sent) return;+ setSent(true);+ props.onFix();+ }}title={total > 0 ? `Ask the agent to fix ${total === 1 ? "this issue" : `these ${total} issues`}` : "Ask the agent to fix the issues"}><Wrench className="size-3.5" />diff --git a/apps/app/src/react-app/domains/session/commands/review-message.ts b/apps/app/src/react-app/domains/session/commands/review-message.tsindex 209f0364..68e80d28 100644--- a/apps/app/src/react-app/domains/session/commands/review-message.ts+++ b/apps/app/src/react-app/domains/session/commands/review-message.ts@@ -85,6 +85,19 @@ export function commandTemplateLabel(text: string | null | undefined): string |return null;}+/**+ * The review a turn's reply holds, only when the turn was the review command+ * (its user message is the review template) and the reply opens with the+ * template's `Reviewed:` line; null for any other reply, however it is laid out.+ */+export function reviewForTurn(userText: string | null | undefined, replyText: string | null | undefined): ReviewSummary | null {+ const typed = (userText ?? "").trimStart();+ if (!commandTemplateLabel(userText)?.startsWith("/review") && !/^\/review(\s|$)/.test(typed)) return null;+ const firstLine = (replyText ?? "").split(/\r?\n/).find((line) => line.trim())?.trim() ?? "";+ if (!firstLine.startsWith("Reviewed:")) return null;+ return parseReviewReply(replyText);+}+const SEVERITY_LABEL: Record<ReviewSeverity, string> = { critical: "Critical", high: "High", medium: "Medium", low: "Low" };export function severityLabel(severity: ReviewSeverity): string {diff --git a/apps/app/src/react-app/domains/session/commands/session-command-controls.tsx b/apps/app/src/react-app/domains/session/commands/session-command-controls.tsxindex d7ae9a11..03ee8875 100644--- a/apps/app/src/react-app/domains/session/commands/session-command-controls.tsx+++ b/apps/app/src/react-app/domains/session/commands/session-command-controls.tsx@@ -3,6 +3,8 @@ import { useEffect, useState } from "react";import { FileDiff, Gauge, Redo2, Undo2 } from "lucide-react";import { Button } from "@/components/ui/button";+import { toast } from "@/components/ui/sonner";+import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { cn } from "@/lib/utils";@@ -52,22 +54,33 @@ export function SessionCommandControls(props: SessionCommandControlsProps) {const openChanges = useSessionCommandsStore((state) => state.openChanges);const { undo, redo, canUndo, canRedo } = commands;+ const running = commands.running;+ // The same undo / redo for the header menu (narrow windows hide these buttons).+ const setHeaderActions = useSessionCommandsStore((state) => state.setHeaderActions);+ useEffect(() => {+ setHeaderActions(props.sessionId, { canUndo, canRedo, undo, redo });+ return () => setHeaderActions(props.sessionId, null);+ }, [canRedo, canUndo, props.sessionId, redo, setHeaderActions, undo]);useEffect(() => {const onKey = (event: KeyboardEvent) => {const action = chatUndoKey(event, isMac());if (!action) return;// Only with the chat on screen: no dialog or menu in front of it.- if (document.querySelector("[role=dialog][data-open], [role=alertdialog]")) return;+ if (document.querySelector("[role=dialog][data-open], [role=alertdialog], [role=menu]")) return;if (action === "undo" && !canUndo) return;if (action === "redo" && !canRedo) return;event.preventDefault();event.stopPropagation();+ // The keyboard never stops a turn (a stray Ctrl+Z must not cut the agent off).+ if (running) {+ toast.info("Stop the turn first (Esc), then undo", { duration: 4000 });+ return;+ }void (action === "undo" ? undo() : redo());};- // Capture phase: the composer's editor keeps its own undo for text, so an empty composer must be seen first.window.addEventListener("keydown", onKey, true);return () => window.removeEventListener("keydown", onKey, true);- }, [canRedo, canUndo, redo, undo]);+ }, [canRedo, canUndo, redo, running, undo]);const mod = isMac() ? "⌘" : "Ctrl+";return (@@ -128,6 +141,7 @@ export function SessionCommandControls(props: SessionCommandControlsProps) {<TooltipContent>Changes</TooltipContent></Tooltip><StatusPopover {...props} />+ <StatusDialog {...props} /><ChangesPanelworkspaceId={props.workspaceId}sessionId={props.sessionId}@@ -139,6 +153,20 @@ export function SessionCommandControls(props: SessionCommandControlsProps) {);}+/** Status from the header menu (narrow windows, where the header button is hidden). */+function StatusDialog(props: SessionCommandControlsProps) {+ const open = useSessionCommandsStore((state) => state.statusOpenFor === props.sessionId);+ const closeStatus = useSessionCommandsStore((state) => state.closeStatus);+ return (+ <Dialog open={open} onOpenChange={(next) => { if (!next) closeStatus(); }}>+ <DialogContent className="max-w-sm gap-0 p-0" data-testid="session-status-dialog">+ <DialogTitle className="sr-only">Status</DialogTitle>+ {open ? <StatusRows {...props} /> : null}+ </DialogContent>+ </Dialog>+ );+}+function StatusPopover(props: SessionCommandControlsProps) {const [open, setOpen] = useState(false);return (diff --git a/apps/app/src/react-app/domains/session/commands/session-commands-store.ts b/apps/app/src/react-app/domains/session/commands/session-commands-store.tsindex d5e8ac97..acc19cb3 100644--- a/apps/app/src/react-app/domains/session/commands/session-commands-store.ts+++ b/apps/app/src/react-app/domains/session/commands/session-commands-store.ts@@ -11,18 +11,40 @@ export type SessionCommandBridge = {busy: boolean;};+/** The header's undo / redo for the header menu of narrow windows (session-command-controls.tsx). */+export type SessionHeaderActions = {+ canUndo: boolean;+ canRedo: boolean;+ undo: () => void | Promise<void>;+ redo: () => void | Promise<void>;+};+type SessionCommandsStore = {bridges: Record<string, SessionCommandBridge>;/** The chat whose Changes panel is open, or null. */changesOpenFor: string | null;+ /** The chat whose Status dialog (header menu) is open, or null. */+ statusOpenFor: string | null;+ headerActions: Record<string, SessionHeaderActions>;register: (sessionId: string, bridge: SessionCommandBridge) => () => void;+ setHeaderActions: (sessionId: string, actions: SessionHeaderActions | null) => void;openChanges: (sessionId: string) => void;closeChanges: () => void;+ openStatus: (sessionId: string) => void;+ closeStatus: () => void;};export const useSessionCommandsStore = create<SessionCommandsStore>((set, get) => ({bridges: {},changesOpenFor: null,+ statusOpenFor: null,+ headerActions: {},+ setHeaderActions: (sessionId, actions) => set((state) => {+ const next = { ...state.headerActions };+ if (actions) next[sessionId] = actions;+ else delete next[sessionId];+ return { headerActions: next };+ }),register: (sessionId, bridge) => {set((state) => ({ bridges: { ...state.bridges, [sessionId]: bridge } }));return () => {@@ -36,6 +58,8 @@ export const useSessionCommandsStore = create<SessionCommandsStore>((set, get) =},openChanges: (sessionId) => set({ changesOpenFor: sessionId }),closeChanges: () => set({ changesOpenFor: null }),+ openStatus: (sessionId) => set({ statusOpenFor: sessionId }),+ closeStatus: () => set({ statusOpenFor: null }),}));export function useSessionCommandBridge(sessionId: string | null | undefined): SessionCommandBridge | null {diff --git a/apps/app/src/react-app/domains/session/commands/undo-key.ts b/apps/app/src/react-app/domains/session/commands/undo-key.tsindex 5cad7896..5a8a90f5 100644--- a/apps/app/src/react-app/domains/session/commands/undo-key.ts+++ b/apps/app/src/react-app/domains/session/commands/undo-key.ts@@ -1,16 +1,17 @@-// Cmd/Ctrl+Z for the chat: undo the last turn (Shift: redo), never a text field's own undo.+// Cmd/Ctrl+Z for the chat: undo the last turn (Shift: redo), only with focus outside any editable element.-/** A key press Cmd/Ctrl+Z may take for the chat: never from a text field that has text (its own undo). */+/** A key press Cmd/Ctrl+Z may take for the chat: never from an editable element (its own undo). */export function chatUndoKey(event: Pick<KeyboardEvent, "key" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey" | "target" | "defaultPrevented">, mac: boolean): "undo" | "redo" | null {if (event.defaultPrevented || event.altKey) return null;if (!(mac ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey)) return null;if (event.key?.toLowerCase() !== "z") return null;+ // Only with focus outside every editable element: a text field (the composer too, even empty),+ // a code editor or a terminal keeps its own undo.const target = event.target as HTMLElement | null;if (target && typeof target === "object" && "tagName" in target) {if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.tagName === "SELECT") return null;- // Code editors and terminals keep their own undo, whatever element holds their focus.- if (typeof target.closest === "function" && target.closest(".monaco-editor, .xterm, .cm-editor")) return null;- if (target.isContentEditable && (target.textContent ?? "").replace(/[\u200B\uFEFF]/g, "").trim().length > 0) return null;+ if (target.isContentEditable) return null;+ if (typeof target.closest === "function" && target.closest("[contenteditable], .monaco-editor, .xterm, .cm-editor")) return null;}return event.shiftKey ? "redo" : "undo";}diff --git a/apps/app/src/react-app/domains/session/commands/use-session-commands.ts b/apps/app/src/react-app/domains/session/commands/use-session-commands.tsindex e39e68ac..77748795 100644--- a/apps/app/src/react-app/domains/session/commands/use-session-commands.ts+++ b/apps/app/src/react-app/domains/session/commands/use-session-commands.ts@@ -94,11 +94,12 @@ async function tracksFiles(client: OpencodeClient, root: string): Promise<booleaif (known !== undefined) return known;try {const project = unwrap(await client.project.current({ directory: root || undefined })) as { worktree?: string } | null;+ if (!project) return true;const tracked = projectTracksFiles(project);trackedByRoot.set(root, tracked);return tracked;} catch {- // Unknown: say what the engine reported about the files.+ // Unknown (not cached, asked again next time): say what the engine reported about the files.return true;}}diff --git a/apps/app/tests/session-commands.test.ts b/apps/app/tests/session-commands.test.tsindex a99750d1..aced23da 100644--- a/apps/app/tests/session-commands.test.ts+++ b/apps/app/tests/session-commands.test.ts@@ -1,9 +1,9 @@import { describe, expect, test } from "bun:test";import { NOT_TRACKED_MESSAGE, projectTracksFiles, undoNotice } from "../src/react-app/domains/session/commands/undo-notice";-import { commandTemplateLabel, parseReviewReply } from "../src/react-app/domains/session/commands/review-message";+import { commandTemplateLabel, parseReviewReply, reviewForTurn } from "../src/react-app/domains/session/commands/review-message";import { contextUse, sandboxLabel, uploadsLine } from "../src/react-app/domains/session/commands/context-usage";-import { changeTotals, normalizeChanges, patchLines } from "../src/react-app/domains/session/commands/changes";+import { MAX_DIFF_LINES, changeTotals, normalizeChanges, patchLineCount, patchLines } from "../src/react-app/domains/session/commands/changes";import { chatUndoKey } from "../src/react-app/domains/session/commands/undo-key";describe("undoNotice", () => {@@ -79,6 +79,26 @@ describe("parseReviewReply", () => {});});+describe("reviewForTurn", () => {+ const REVIEW_PROMPT = "You are a code reviewer. Your job is...\n\nInput: \n";+ test("only a reply to the review command, opening with Reviewed:, offers Fix these", () => {+ expect(reviewForTurn(REVIEW_PROMPT, REVIEW)?.fixable).toBe(true);+ expect(reviewForTurn("/review", REVIEW)?.fixable).toBe(true);+ const plan = [+ "Here is the plan, most important first:",+ "### High",+ "1. src/server.ts:42 - Add the retry",+ "### Low",+ "2. README.md:3 - Mention it",+ "Reply **fix these** to fix them all (or for example **fix 1, 3**), or run /fix.",+ ].join("\n");+ expect(reviewForTurn("make a prioritized plan for the retry work", plan)).toBeNull();+ expect(reviewForTurn("make a prioritized plan", REVIEW)).toBeNull();+ expect(reviewForTurn(REVIEW_PROMPT, plan)).toBeNull();+ expect(reviewForTurn(undefined, REVIEW)).toBeNull();+ });+});+describe("commandTemplateLabel", () => {test("names the review and fix commands their prompts came from", () => {expect(commandTemplateLabel("You are a code reviewer. Your job is...\n\n---\n\nInput: \n\n---")).toBe("/review");@@ -139,6 +159,13 @@ describe("changes", () => {expect(normalizeChanges(null)).toEqual([]);});+ test("long patches are counted cheaply against the render cap", () => {+ expect(patchLineCount("")).toBe(0);+ expect(patchLineCount("a\nb\nc")).toBe(3);+ const big = Array.from({ length: MAX_DIFF_LINES + 10 }, (_, i) => `+line ${i}`).join("\n");+ expect(patchLineCount(big)).toBeGreaterThan(MAX_DIFF_LINES);+ });+test("patch lines carry old and new line numbers", () => {const lines = patchLines("Index: a.ts\n===\n--- a.ts\n+++ a.ts\n@@ -3,3 +3,3 @@\n keep\n-old\n+new\n tail\n");expect(lines.map((line) => [line.kind, line.oldLine, line.newLine, line.text])).toEqual([@@ -164,10 +191,11 @@ describe("chatUndoKey", () => {expect(chatUndoKey(key({ metaKey: true, key: "y" }), true)).toBeNull();});- test("a text field keeps its own undo; an empty composer does not", () => {+ test("any editable element keeps its own undo, the empty composer too", () => {expect(chatUndoKey(key({ metaKey: true, target: { tagName: "TEXTAREA", isContentEditable: false, textContent: "" } }), true)).toBeNull();expect(chatUndoKey(key({ metaKey: true, target: { tagName: "DIV", isContentEditable: true, textContent: "draft" } }), true)).toBeNull();- expect(chatUndoKey(key({ metaKey: true, target: { tagName: "DIV", isContentEditable: true, textContent: " " } }), true)).toBe("undo");+ expect(chatUndoKey(key({ metaKey: true, target: { tagName: "DIV", isContentEditable: true, textContent: " " } }), true)).toBeNull();+ expect(chatUndoKey(key({ metaKey: true, target: { tagName: "BUTTON", isContentEditable: false, textContent: "Send", closest: () => null } }), true)).toBe("undo");const inEditor = { tagName: "DIV", isContentEditable: false, textContent: "", closest: (selector: string) => (selector.includes(".monaco-editor") ? {} : null) };expect(chatUndoKey(key({ ctrlKey: true, target: inEditor }), false)).toBeNull();});diff --git a/apps/server/src/command-events.test.ts b/apps/server/src/command-events.test.tsindex f4ace4e4..8df15cea 100644--- a/apps/server/src/command-events.test.ts+++ b/apps/server/src/command-events.test.ts@@ -108,7 +108,7 @@ describe("SessionUploader.recordCommand", () => {const sessionId = "session-cmd-1234";sessionUploader.startSession(sessionId, "workspace-test", root);sessionUploader.captureSnapshot(sessionId, "prompt");- const undone = revertEvent("revert", { revert: { messageID: "msg_2", restored: ["src/app.ts"], merged: [], kept: ["notes/[email protected]"] } });+ const undone = revertEvent("revert", { revert: { messageID: "msg_2", restored: ["src/app.ts"], merged: [], kept: ["notes/[email protected]", ".env", "deploy/id_rsa"] } });sessionUploader.recordCommand(sessionId, undone!.type, undone!.data);sessionUploader.recordCommand(sessionId, "turn.redone", { message_id: "msg_2" });const review = commandEvent({ command: "review", arguments: "" })!;@@ -123,11 +123,15 @@ describe("SessionUploader.recordCommand", () => {const pick = (type: string) => events.filter((event) => event.type === type);expect(pick("turn.undone")).toHaveLength(1);const data = pick("turn.undone")[0]!.data!;- expect(data).toMatchObject({ schema: 1, message_id: "msg_2", repeat: false, restored: 1, merged: 0, kept: 1, outside: 0 });+ // Protected names are dropped from the lists; the counts stay.+ expect(data).toMatchObject({ schema: 1, message_id: "msg_2", repeat: false, restored: 1, merged: 0, kept: 3, outside: 0 });const files = data.files as { restored: string[]; kept: string[] };expect(files.restored).toEqual(["src/app.ts"]);// Paths take the same upload pass as every other path (an e-mail address in a name is not sent as is).+ expect(files.kept).toHaveLength(1);expect(files.kept[0]).not.toContain("[email protected]");+ expect(JSON.stringify(files)).not.toContain(".env");+ expect(JSON.stringify(files)).not.toContain("id_rsa");expect(pick("turn.redone")[0]!.data).toEqual({ schema: 1, message_id: "msg_2" });expect(pick("review.run")[0]!.data).toEqual({ schema: 1, target: "uncommitted", has_arguments: false });expect(pick("review.fix")).toHaveLength(1);diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 2e4a0110..83b01850 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -2384,11 +2384,11 @@ export async function proxyOpencodeRequest(input: {capture.archiveSessionStarted(uploadedSessionId, workspace.path, engineTarget(baseUrl, headers, search));}}- // A review or its fixes (command-events.ts), typed or from a button: an additive event of the chat's trace.- if (capture && captured && uploadedSessionId && isSessionCommandProxyRequest(method, proxyPath) && capture.hasSession(uploadedSessionId)) {- const event = commandEvent(body);- if (event) capture.recordCommand(uploadedSessionId, event.type, event.data);- }+ // A review or its fixes (command-events.ts), typed or from a button: an additive event of the chat's+ // trace, recorded once the engine answers the command with a 2xx.+ const reviewEvent = capture && captured && uploadedSessionId && isSessionCommandProxyRequest(method, proxyPath)+ ? commandEvent(body)+ : null;// Undo of the last turn and its redo (command-events.ts) of a chat the uploader tracks: the revert// point before it is read first; the engine's answer says what happened to each file.const revertCall = capture?.uploadEnabled && workspace && workspace.workspaceType !== "remote"@@ -2486,6 +2486,9 @@ export async function proxyOpencodeRequest(input: {body,}).finally(() => release?.()).then((response) => {enginePoolForConfig(input.config)?.reportRequestSuccess(baseUrl);+ if (reviewEvent && response.ok && capture && uploadedSessionId && capture.hasSession(uploadedSessionId)) {+ capture.recordCommand(uploadedSessionId, reviewEvent.type, reviewEvent.data);+ }if (capture?.uploadEnabled && uploadedSessionId && steer) {if (response.ok) steered(capture, uploadedSessionId, engineTarget(baseUrl, headers, search));} else if (capture?.uploadEnabled && uploadedSessionId) {diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.tsindex 4335b747..415ab7d0 100644--- a/apps/server/src/session-uploader.ts+++ b/apps/server/src/session-uploader.ts@@ -5936,7 +5936,7 @@ export class SessionUploader {* what happened to each file) and "review.run" / "review.fix" (a code* review asked for, and its fixes). Schema 1, additive: a session that never* runs them carries none. File paths go through the same upload-path pass- * as every other path.+ * as every other path; protected file names are left out (counts kept).*/recordCommand(sessionId: string, type: "turn.undone" | "turn.redone" | "review.run" | "review.fix", data: Record<string, unknown>): void {const state = this.sessions.get(sessionId);@@ -5945,7 +5945,10 @@ export class SessionUploader {const cleanFiles = files? Object.fromEntries(Object.entries(files).map(([key, items]) => [key,- Array.isArray(items) ? items.filter((item): item is string => typeof item === "string").slice(0, 200).map((item) => portablePathForUpload(item)) : [],+ // Protected names (keys, env files, …) are never sent: they are dropped, the counts stay.+ Array.isArray(items)+ ? items.filter((item): item is string => typeof item === "string" && !isUploadFileDenied(item.replaceAll("\\", "/"))).slice(0, 200).map((item) => portablePathForUpload(item))+ : [],])): undefined;this.appendTrace(state, type, { schema: 1, ...data, ...(cleanFiles ? { files: cleanFiles } : {}) });