A desktop coding agent with free access to frontier models.
TypeScript
feat: review, undo, changes and status
Samrat Talukdarad91188b2dbb
diff --git a/apps/app/src/components/chat/message-list-provider.tsx b/apps/app/src/components/chat/message-list-provider.tsxindex 38d30611..d01f039b 100644--- a/apps/app/src/components/chat/message-list-provider.tsx+++ b/apps/app/src/components/chat/message-list-provider.tsx@@ -38,6 +38,8 @@ interface MessageListContextValue {) => Promise<ChatToolReconnectResult>onMcpReopenAuthorization: (action: ChatToolReconnectAction, authorizeUrl: string) => Promise<void>onMcpRetry: (action: ChatToolReconnectAction) => void | Promise<void>+ /** Send a chat command ("/fix", "/fix 1, 3") like a typed one; absent where commands cannot be sent. */+ onRunCommand?: (text: string) => void}const MessageListContext = React.createContext<MessageListContextValue | null>(null)@@ -66,6 +68,7 @@ interface MessageListProviderProps {syncDegraded?: booleandispatchAction: (action: DispatchAction) => voidsetPrompt: (prompt: string) => void+ onRunCommand?: (text: string) => void | Promise<void>}export interface DispatchAction {@@ -95,6 +98,7 @@ export function MessageListProvider({onMcpReconnect,onMcpReopenAuthorization,onMcpRetry,+ onRunCommand,}: MessageListProviderProps) {const handlersRef = React.useRef({dispatchAction,@@ -107,6 +111,7 @@ export function MessageListProvider({onMcpReconnect,onMcpReopenAuthorization,onMcpRetry,+ onRunCommand,})React.useEffect(() => {handlersRef.current = {@@ -120,6 +125,7 @@ export function MessageListProvider({onMcpReconnect,onMcpReopenAuthorization,onMcpRetry,+ onRunCommand,}}, [dispatchAction,@@ -132,6 +138,7 @@ export function MessageListProvider({onMcpReconnect,onMcpReopenAuthorization,onMcpRetry,+ onRunCommand,])const stableHandlers = React.useMemo(() => ({dispatchAction: (action: DispatchAction) => handlersRef.current.dispatchAction(action),@@ -149,9 +156,11 @@ export function MessageListProvider({handlersRef.current.onMcpReopenAuthorization(action, authorizeUrl)),onMcpRetry: (action: ChatToolReconnectAction) => handlersRef.current.onMcpRetry(action),+ onRunCommand: (text: string) => void handlersRef.current.onRunCommand?.(text),}), [])const canOpenSubagentSession = Boolean(onOpenSubagentSession)const canResumeInterrupted = Boolean(onResumeInterrupted)+ const canRunCommand = Boolean(onRunCommand)const value = React.useMemo(() => ({workspaceId,@@ -170,6 +179,7 @@ export function MessageListProvider({onResumeInterrupted: canResumeInterrupted? stableHandlers.onResumeInterrupted: undefined,+ onRunCommand: canRunCommand ? stableHandlers.onRunCommand : undefined,}),[workspaceId,@@ -184,6 +194,7 @@ export function MessageListProvider({stableHandlers,canOpenSubagentSession,canResumeInterrupted,+ canRunCommand,],)diff --git a/apps/app/src/components/chat/message-list.tsx b/apps/app/src/components/chat/message-list.tsxindex ea72fc64..4efa03a1 100644--- a/apps/app/src/components/chat/message-list.tsx+++ b/apps/app/src/components/chat/message-list.tsx@@ -130,6 +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 { ReviewFixBar } from "@/react-app/domains/session/commands/review-fix-bar"import { resolveConnectorToolIdentity } from "@/react-app/domains/connections/connector-tool-identity"const SEARCH_HIGHLIGHT_MARK_CLASS = "rounded px-0.5 bg-amber-4/70 text-current"@@ -740,6 +742,15 @@ const UserMessage = React.memo(>{inlineParts.map((part, index) => {if (part.type === "text") {+ // A review or fix command arrives as its whole prompt: show the command the person ran.+ const command = commandTemplateLabel(part.text)+ if (command) {+ return (+ <span key={`text-${index}`} className="font-mono text-[13px]" title={part.text.slice(0, 2000)} data-command-label={command}>+ {command}+ </span>+ )+ }return (<span key={`text-${index}`} className="whitespace-pre-wrap">{renderUserTextWithSkillChips(part.text, highlightQuery)}@@ -1246,7 +1257,7 @@ function MessageGroup({isLastGroup,isStreaming,}: AssistantMessageGroupProps) {- const { onRevertToUserMessage, onForkAtMessage, showThinking } = useMessageList()+ const { onRevertToUserMessage, onForkAtMessage, showThinking, onRunCommand } = useMessageList()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@@ -1261,6 +1272,11 @@ function MessageGroup({const renderableItems = getRenderableMessages(items)const lastTextMessage = getLastTextPart(lastItem.message)const mcpAppParts = collectMcpAppParts(items)+ // 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)+ : null// Leading messages without prose (tool/reasoning steps) render inline and// rely on the transcript's one scroll container. Tool activity must never@@ -1445,6 +1461,9 @@ function MessageGroup({{/* <MessageSources messages={items.map((item) => item.message)} /> */}</div>)}+ {review?.fixable && onRunCommand ? (+ <ReviewFixBar review={review} onFix={() => onRunCommand("/fix")} />+ ) : null}</div></DevProfiler>)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 9cab2535..675771c0 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,9 @@ 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, FileText, Globe, Maximize2, MoreHorizontal, PanelRight, TextSearch, X, Zap } from "lucide-react";+import { ArrowLeft, Cloud, Code2, FileDiff, FileText, 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";import { resolveExtensionIconSrc } from "@/react-app/design-system/extension-icon-src";import { t } from "../../../../i18n";@@ -1190,6 +1192,10 @@ export function SessionPage(props: SessionPageProps) {(workspace) => workspace.id === props.selectedWorkspaceId && workspace.workspaceType === "remote",);const findButtonSessionId = props.selectedSessionId;+ // Undo, Changes, Status and Review for the chat on screen (commands/).+ const commandSessionId = canRenderReactSurface && !props.primarySlot && !hasMainContentTakeover ? props.selectedSessionId : null;+ const commandBridge = useSessionCommandBridge(commandSessionId);+ const openChangesPanel = useSessionCommandsStore((state) => state.openChanges);const canGoBackInConversationHistory = !pendingConversationHistoryNavigation && canNavigateSelectedConversationHistory(conversationHistory,props.selectedWorkspaceId,@@ -1637,6 +1643,25 @@ export function SessionPage(props: SessionPageProps) {<div className="flex shrink-0 items-center gap-1.5 text-gray-10 mac:titlebar-no-drag"><BuildathonChip /><DesktopUpdateButton />+ {commandSessionId && props.runtimeWorkspaceId ? (+ <SessionCommandControls+ workspaceId={props.runtimeWorkspaceId}+ sessionId={commandSessionId}+ opencodeBaseUrl={reactSessionBaseUrl}+ token={reactSessionToken}+ workspaceRoot={props.surface?.workspaceRoot ?? props.selectedWorkspaceRoot}+ serverClient={props.omnirushServerClient}+ model={props.surface ? {+ selectedModel: props.surface.selectedModel,+ modelLabel: props.surface.modelLabel,+ modelVariant: props.surface.modelVariant,+ modelVariantLabel: props.surface.modelVariantLabel,+ modelBehaviorOptions: props.surface.modelBehaviorOptions,+ providerCatalog: props.surface.providerCatalog,+ onModelVariantChange: props.surface.onModelVariantChange,+ } : null}+ />+ ) : null}{!props.primarySlot && findButtonSessionId && !hasMainContentTakeover ? (<Tooltip><TooltipTrigger@@ -1716,6 +1741,21 @@ export function SessionPage(props: SessionPageProps) {Find in conversation</DropdownMenuItem>) : null}+ {commandSessionId ? (+ <DropdownMenuItem onClick={() => openChangesPanel(commandSessionId)}>+ <FileDiff className="size-4" />+ Changes+ </DropdownMenuItem>+ ) : null}+ {commandSessionId ? (+ <DropdownMenuItem+ disabled={!commandBridge || commandBridge.busy}+ onClick={() => void commandBridge?.runCommand("/review")}+ >+ <ListChecks className="size-4" />+ Review changes+ </DropdownMenuItem>+ ) : null}<DropdownMenuItem onClick={openArtifactRailPane}><FileText className="size-4" />Files{artifactTargetCount > 0 ? ` (${artifactTargetCount})` : ""}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.tsxnew file mode 100644index 00000000..c895a183--- /dev/null+++ b/apps/app/src/react-app/domains/session/commands/changes-panel.tsx@@ -0,0 +1,227 @@+/** @jsxImportSource react */+import { useEffect, useMemo, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { ChevronDown, ChevronRight, FileDiff, ListChecks, RefreshCw } from "lucide-react";++import { Button } from "@/components/ui/button";+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";+import { unwrap } from "@/app/lib/opencode";+import { cn } from "@/lib/utils";+import type { OmniRushSessionSnapshot } from "@/app/lib/omnirush-server";+import { snapshotKey, statusKey } from "@/react-app/domains/session/sync/session-sync";+import {+ CHANGES_EMPTY,+ CHANGES_SOURCE_LABEL,+ changeTotals,+ normalizeChanges,+ patchLines,+ type ChangedFile,+ type ChangesSource,+} from "./changes";+import { useSessionCommandBridge, useSessionCommandsStore } from "./session-commands-store";+import { latestUserMessageId, useCachedQueryData, useOpencodeClient, type SessionCommandTarget } from "./use-session-commands";++const SOURCES: ChangesSource[] = ["chat", "turn", "tree"];++const STATUS_BADGE: Record<ChangedFile["status"], string> = {+ added: "A",+ deleted: "D",+ modified: "M",+};++function DiffBody({ patch }: { patch: string }) {+ const lines = useMemo(() => patchLines(patch), [patch]);+ 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>;+ }+ return (+ <div className="max-h-[50vh] overflow-auto border-t border-border font-mono text-[11.5px] leading-[1.55]" data-testid="changes-diff">+ {lines.map((line, index) => (+ <div+ key={index}+ className={cn(+ "flex min-w-max",+ line.kind === "add" && "bg-green-3/40 text-green-11",+ line.kind === "del" && "bg-red-3/40 text-red-11",+ line.kind === "hunk" && "bg-blue-2/40 text-blue-11",+ line.kind === "meta" && "text-muted-foreground",+ )}+ >+ <span className="w-10 shrink-0 select-none pr-1 text-right text-muted-foreground/70">{line.oldLine ?? ""}</span>+ <span className="w-10 shrink-0 select-none pr-2 text-right text-muted-foreground/70">{line.newLine ?? ""}</span>+ <span className="w-3 shrink-0 select-none">{line.kind === "add" ? "+" : line.kind === "del" ? "-" : ""}</span>+ <span className="whitespace-pre pr-4">{line.kind === "hunk" ? line.text : line.text || " "}</span>+ </div>+ ))}+ </div>+ );+}++function FileRow({ file, defaultOpen }: { file: ChangedFile; defaultOpen: boolean }) {+ const [open, setOpen] = useState(defaultOpen);+ return (+ <div className="overflow-hidden rounded-xl border border-border bg-background/60" data-testid="changes-file" data-path={file.path}>+ <button+ type="button"+ className="flex w-full items-center gap-2 px-3 py-2 text-left text-[12.5px] hover:bg-muted/60"+ aria-expanded={open}+ onClick={() => setOpen((value) => !value)}+ >+ {open ? <ChevronDown className="size-3.5 shrink-0 text-muted-foreground" /> : <ChevronRight className="size-3.5 shrink-0 text-muted-foreground" />}+ <span+ className={cn(+ "flex size-4 shrink-0 items-center justify-center rounded text-[10px] font-semibold",+ file.status === "added" && "bg-green-4 text-green-11",+ file.status === "deleted" && "bg-red-4 text-red-11",+ file.status === "modified" && "bg-amber-4 text-amber-11",+ )}+ title={file.status}+ >+ {STATUS_BADGE[file.status]}+ </span>+ <span className="min-w-0 flex-1 truncate font-mono" title={file.path}>{file.path}</span>+ <span className="shrink-0 font-mono text-[11.5px] text-green-11">+{file.additions}</span>+ <span className="shrink-0 font-mono text-[11.5px] text-red-11">-{file.deletions}</span>+ </button>+ {open ? <DiffBody patch={file.patch} /> : null}+ </div>+ );+}++/**+ * The Changes panel: the files this chat changed (or its last turn, or the+ * whole working tree), with +/- counts and each file's diff, and a Review+ * button that asks the agent to review them in the chat.+ */+export function ChangesPanel(props: SessionCommandTarget) {+ const openFor = useSessionCommandsStore((state) => state.changesOpenFor);+ const closeChanges = useSessionCommandsStore((state) => state.closeChanges);+ const open = openFor === props.sessionId;+ return (+ <Sheet open={open} onOpenChange={(next) => { if (!next) closeChanges(); }}>+ <SheetContent side="right" className="w-[min(720px,92vw)] gap-0 data-[side=right]:sm:max-w-[720px]" data-testid="changes-panel">+ {open ? <ChangesBody {...props} onClose={closeChanges} /> : null}+ </SheetContent>+ </Sheet>+ );+}++function ChangesBody(props: SessionCommandTarget & { onClose: () => void }) {+ const client = useOpencodeClient(props);+ const bridge = useSessionCommandBridge(props.sessionId);+ const [source, setSource] = useState<ChangesSource>("chat");+ const snapshot = useCachedQueryData<OmniRushSessionSnapshot>(snapshotKey(props.workspaceId, props.sessionId));+ const status = useCachedQueryData<{ type: string }>(statusKey(props.workspaceId, props.sessionId));+ const lastUserId = latestUserMessageId(snapshot?.session.id === props.sessionId ? snapshot : null);+ const revertId = snapshot?.session.revert?.messageID ?? null;+ const running = (status?.type ?? "idle") !== "idle";++ const query = useQuery({+ queryKey: ["session-commands-changes", props.workspaceId, props.sessionId, source, source === "turn" ? lastUserId : null, revertId],+ queryFn: async () => {+ if (source === "tree") {+ return normalizeChanges(unwrap(await client.vcs.diff({ mode: "git", directory: props.workspaceRoot || undefined })));+ }+ if (source === "turn") {+ if (!lastUserId) return [];+ return normalizeChanges(unwrap(await client.session.diff({ sessionID: props.sessionId, messageID: lastUserId })));+ }+ return normalizeChanges(unwrap(await client.session.diff({ sessionID: props.sessionId })));+ },+ staleTime: 2_000,+ retry: false,+ });++ // A turn that ends changes what this lists.+ const { refetch } = query;+ useEffect(() => {+ if (!running) void refetch();+ }, [running, refetch]);++ const files = query.data ?? [];+ const totals = changeTotals(files);+ const reviewDisabled = !bridge || bridge.busy || running;++ return (+ <div className="flex h-full min-h-0 flex-col">+ <SheetHeader className="gap-3 border-b border-border p-4 pr-14">+ <div className="flex items-center gap-2">+ <FileDiff className="size-4 text-muted-foreground" />+ <SheetTitle>Changes</SheetTitle>+ <span className="text-xs text-muted-foreground" data-testid="changes-totals">+ {query.isSuccess+ ? `${totals.files} ${totals.files === 1 ? "file" : "files"} · +${totals.additions} -${totals.deletions}`+ : ""}+ </span>+ <div className="ml-auto flex items-center gap-1.5">+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label="Refresh"+ title="Refresh"+ onClick={() => void query.refetch()}+ disabled={query.isFetching}+ >+ <RefreshCw className={cn("size-3.5", query.isFetching && "animate-spin")} />+ </Button>+ <Button+ size="sm"+ 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"}+ onClick={() => {+ if (!bridge) return;+ void bridge.runCommand("/review");+ props.onClose();+ }}+ >+ <ListChecks className="size-3.5" />+ Review+ </Button>+ </div>+ </div>+ <SheetDescription className="sr-only">The files this chat changed and their diffs.</SheetDescription>+ <div className="flex w-fit items-center gap-0.5 rounded-lg bg-muted p-0.5" role="tablist" aria-label="Changes source">+ {SOURCES.map((item) => (+ <button+ key={item}+ type="button"+ role="tab"+ aria-selected={source === item}+ data-testid={`changes-source-${item}`}+ className={cn(+ "rounded-md px-2.5 py-1 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground",+ source === item && "bg-background text-foreground shadow-sm",+ )}+ onClick={() => setSource(item)}+ >+ {CHANGES_SOURCE_LABEL[item]}+ </button>+ ))}+ </div>+ </SheetHeader>+ <div className="min-h-0 flex-1 overflow-auto p-4">+ {query.isLoading ? (+ <div className="text-sm text-muted-foreground">Loading changes…</div>+ ) : query.isError ? (+ <div className="text-sm text-muted-foreground" data-testid="changes-error">+ {source === "tree"+ ? "The working tree's changes could not be read (is this folder a git repository?)."+ : "The changes could not be read."}+ </div>+ ) : files.length === 0 ? (+ <div className="rounded-xl border border-dashed border-border p-6 text-center text-sm text-muted-foreground" data-testid="changes-empty">+ {CHANGES_EMPTY[source]}+ </div>+ ) : (+ <div className="flex flex-col gap-2">+ {files.map((file) => (+ <FileRow key={`${source}:${file.path}`} file={file} defaultOpen={files.length <= 3} />+ ))}+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/apps/app/src/react-app/domains/session/commands/changes.ts b/apps/app/src/react-app/domains/session/commands/changes.tsnew file mode 100644index 00000000..4a5d1481--- /dev/null+++ b/apps/app/src/react-app/domains/session/commands/changes.ts@@ -0,0 +1,85 @@+// The Changes panel's data: the engine's file diffs (session.diff for this+// chat or its last turn, vcs.diff for the working tree), normalized.++export type ChangesSource = "chat" | "turn" | "tree";++export type ChangedFile = {+ path: string;+ status: "added" | "deleted" | "modified";+ additions: number;+ deletions: number;+ patch: string;+};++type RawDiff = { file?: unknown; path?: unknown; patch?: unknown; additions?: unknown; deletions?: unknown; status?: unknown };++const count = (value: unknown) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.round(value) : 0);++/** The engine's diff items as the panel lists them, by path; items without a path are left out. */+export function normalizeChanges(items: unknown): ChangedFile[] {+ if (!Array.isArray(items)) return [];+ const out: ChangedFile[] = [];+ for (const raw of items as RawDiff[]) {+ if (!raw || typeof raw !== "object") continue;+ const path = typeof raw.file === "string" ? raw.file : typeof raw.path === "string" ? raw.path : "";+ if (!path.trim()) continue;+ const status = raw.status === "added" || raw.status === "deleted" ? raw.status : "modified";+ out.push({ path, status, additions: count(raw.additions), deletions: count(raw.deletions), patch: typeof raw.patch === "string" ? raw.patch : "" });+ }+ return out.sort((a, b) => a.path.localeCompare(b.path));+}++export function changeTotals(files: readonly ChangedFile[]) {+ return files.reduce(+ (total, file) => ({ files: total.files + 1, additions: total.additions + file.additions, deletions: total.deletions + file.deletions }),+ { files: 0, additions: 0, deletions: 0 },+ );+}++export const CHANGES_EMPTY: Record<ChangesSource, string> = {+ chat: "This chat has not changed any files yet.",+ turn: "The last turn changed no files.",+ tree: "No changes.",+};++export const CHANGES_SOURCE_LABEL: Record<ChangesSource, string> = {+ chat: "This chat",+ turn: "Last turn",+ tree: "Working tree",+};++export type PatchLine = { kind: "add" | "del" | "hunk" | "context" | "meta"; text: string; oldLine: number | null; newLine: number | null };++/** A unified patch as display lines with old/new line numbers; the file headers are left out. */+export function patchLines(patch: string): PatchLine[] {+ const lines: PatchLine[] = [];+ let oldLine = 0;+ let newLine = 0;+ let inHunk = false;+ for (const text of patch.split("\n")) {+ if (text.startsWith("@@")) {+ const match = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(text);+ oldLine = match ? Number(match[1]) : 0;+ newLine = match ? Number(match[2]) : 0;+ inHunk = true;+ lines.push({ kind: "hunk", text, oldLine: null, newLine: null });+ continue;+ }+ if (!inHunk) continue;+ if (text.startsWith("\\")) {+ lines.push({ kind: "meta", text, oldLine: null, newLine: null });+ } else if (text.startsWith("+")) {+ lines.push({ kind: "add", text: text.slice(1), oldLine: null, newLine: newLine++ });+ } else if (text.startsWith("-")) {+ lines.push({ kind: "del", text: text.slice(1), oldLine: oldLine++, newLine: null });+ } else if (text.startsWith(" ") || text === "") {+ if (text === "" && lines.length && lines[lines.length - 1]?.kind === "hunk") continue;+ lines.push({ kind: "context", text: text.slice(1), oldLine: oldLine++, newLine: newLine++ });+ } else if (text.startsWith("diff --git") || text.startsWith("Index:")) {+ inHunk = false;+ }+ }+ // A trailing newline in the patch leaves one empty context line behind.+ while (lines.length && lines[lines.length - 1]?.kind === "context" && lines[lines.length - 1]?.text === "") lines.pop();+ return lines;+}diff --git a/apps/app/src/react-app/domains/session/commands/context-usage.ts b/apps/app/src/react-app/domains/session/commands/context-usage.tsnew file mode 100644index 00000000..7de0fa9f--- /dev/null+++ b/apps/app/src/react-app/domains/session/commands/context-usage.ts@@ -0,0 +1,56 @@+// The context the chat uses: the newest assistant reply's tokens against its+// model's context window. The same rule and wording as the OmniRush CLI's+// /status (engine tui util/status-rows.ts).++type Tokens = { input?: number; output?: number; reasoning?: number; cache?: { read?: number; write?: number } };+type MessageInfo = { role?: string; tokens?: Tokens; providerID?: string; modelID?: string };++export type ContextUse = {+ used: number;+ max: number | null;+ percent: number | null;+ left: number | null;+ providerID: string | null;+ modelID: string | null;+ /** "21,000 of 400,000 tokens (5%) · 379,000 left", or "21,000 tokens" without a known window. */+ text: string;+ warning: boolean;+};++const num = (value: unknown) => (typeof value === "number" && Number.isFinite(value) ? value : 0);+const fmt = (value: number) => value.toLocaleString("en-US");++/** Context in use for the newest assistant message that produced output; null when there is none yet. */+export function contextUse(+ messages: readonly MessageInfo[],+ limit: (providerID: string, modelID: string) => number | null | undefined,+): ContextUse | null {+ const last = [...messages].reverse().find((item) => item.role === "assistant" && num(item.tokens?.output) > 0);+ if (!last?.tokens) return null;+ const t = last.tokens;+ const used = num(t.input) + num(t.output) + num(t.reasoning) + num(t.cache?.read) + num(t.cache?.write);+ const providerID = last.providerID ?? null;+ const modelID = last.modelID ?? null;+ const rawMax = providerID && modelID ? limit(providerID, modelID) : null;+ const max = typeof rawMax === "number" && rawMax > 0 ? rawMax : null;+ if (!max) return { used, max: null, percent: null, left: null, providerID, modelID, text: `${fmt(used)} tokens`, warning: false };+ const percent = Math.min(100, Math.round((used / max) * 100));+ const left = Math.max(0, max - used);+ return {+ used,+ max,+ percent,+ left,+ providerID,+ modelID,+ text: `${fmt(used)} of ${fmt(max)} tokens (${percent}%) · ${fmt(left)} left`,+ warning: percent >= 85,+ };+}++/** The Uploads row: "nothing waiting" or "N waiting" (sessions and project archives still queued). */+export function uploadsLine(pending: { uploads?: number; archives?: number } | null | undefined): string | null {+ if (!pending) return null;+ const waiting = num(pending.uploads) + num(pending.archives);+ return waiting === 0 ? "nothing waiting" : `${waiting} waiting`;+}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.tsxnew file mode 100644index 00000000..b082ab06--- /dev/null+++ b/apps/app/src/react-app/domains/session/commands/review-fix-bar.tsx@@ -0,0 +1,42 @@+/** @jsxImportSource react */+import { Wrench } from "lucide-react";++import { Button } from "@/components/ui/button";+import { cn } from "@/lib/utils";+import { REVIEW_SEVERITIES, severityLabel, type ReviewSeverity, type ReviewSummary } from "./review-message";++const CHIP: Record<ReviewSeverity, string> = {+ critical: "border-red-6/50 bg-red-3/50 text-red-11",+ high: "border-orange-6/50 bg-orange-3/50 text-orange-11",+ medium: "border-amber-6/50 bg-amber-3/50 text-amber-11",+ low: "border-gray-6/60 bg-gray-3/50 text-gray-11",+};++/** 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;+ 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) => (+ <span+ key={severity}+ className={cn("inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11.5px] font-medium", CHIP[severity])}+ data-review-severity={severity}+ >+ {props.review.counts[severity]} {severityLabel(severity)}+ </span>+ ))}+ <Button+ size="sm"+ className="h-7 rounded-full px-3 text-xs"+ data-testid="review-fix-these"+ disabled={props.disabled}+ onClick={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" />+ Fix these+ </Button>+ </div>+ );+}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.tsnew file mode 100644index 00000000..209f0364--- /dev/null+++ b/apps/app/src/react-app/domains/session/commands/review-message.ts@@ -0,0 +1,92 @@+// Reading the engine's review layout (its `review` command template):+// Reviewed: <what> (<N> files)+// ### Critical | ### High | ### Medium | ### Low+// N. path/to/file.ext:LINE - short title+// one to three lines+// ...+// Reply **fix these** to fix them all (or for example **fix 1, 3**), or run /fix.+// and the user messages the `review` / `fix` commands expand into.++export type ReviewSeverity = "critical" | "high" | "medium" | "low";++export type ReviewIssue = {+ number: number;+ severity: ReviewSeverity;+ path: string;+ line: number | null;+ title: string;+};++export type ReviewSummary = {+ reviewed: string | null;+ issues: ReviewIssue[];+ counts: Record<ReviewSeverity, number>;+ /** The reply offers "fix these" (at least one issue). */+ fixable: boolean;+ clean: boolean;+};++export const REVIEW_SEVERITIES: ReviewSeverity[] = ["critical", "high", "medium", "low"];++const HEADING_RE = /^#{2,4}\s*(Critical|High|Medium|Low)\s*$/i;+const ITEM_RE = /^\s*(\d+)\.\s+`?([^\s`:][^`:]*?)(?::(\d+))?`?\s+[-–—]\s+(.+?)\s*$/;+const FIX_LINE_RE = /reply\s+\*\*fix these\*\*/i;+const REVIEWED_RE = /^\s*Reviewed:\s*(.+?)\s*$/im;++/** The review in an assistant reply, or null when the reply is not one. */+export function parseReviewReply(text: string | null | undefined): ReviewSummary | null {+ if (!text) return null;+ const reviewed = REVIEWED_RE.exec(text)?.[1] ?? null;+ const fixable = FIX_LINE_RE.test(text);+ const clean = /^\s*No issues found\.\s*$/im.test(text);+ const issues: ReviewIssue[] = [];+ let severity: ReviewSeverity | null = null;+ for (const raw of text.split(/\r?\n/)) {+ const heading = HEADING_RE.exec(raw.trim());+ if (heading?.[1]) {+ severity = heading[1].toLowerCase() as ReviewSeverity;+ continue;+ }+ if (!severity) continue;+ const item = ITEM_RE.exec(raw);+ if (!item?.[1] || !item[2] || !item[4]) continue;+ issues.push({+ number: Number(item[1]),+ severity,+ path: item[2].trim(),+ line: item[3] ? Number(item[3]) : null,+ title: item[4].replace(/\*\*/g, "").trim(),+ });+ }+ if (!reviewed && !fixable && issues.length === 0) return null;+ if (!fixable && issues.length === 0 && !clean) return null;+ const counts: Record<ReviewSeverity, number> = { critical: 0, high: 0, medium: 0, low: 0 };+ for (const issue of issues) counts[issue.severity] += 1;+ return { reviewed, issues, counts, fixable: fixable || issues.length > 0, clean: clean && issues.length === 0 };+}++const REVIEW_TEMPLATE_START = "You are a code reviewer.";+const FIX_TEMPLATE_START = "Fix the issues from the code review above.";++/**+ * The short label of a user message the `review` or `fix` command expanded+ * into ("/review", "/review main", "/fix 1, 3"), or null for any other text.+ */+export function commandTemplateLabel(text: string | null | undefined): string | null {+ const value = text?.trimStart() ?? "";+ if (value.startsWith(REVIEW_TEMPLATE_START)) {+ const input = /^Input:[ \t]*(.*)$/m.exec(value)?.[1]?.trim() ?? "";+ return input ? `/review ${input}` : "/review";+ }+ if (value.startsWith(FIX_TEMPLATE_START)) {+ const rest = value.slice(FIX_TEMPLATE_START.length).split(/\r?\n/)[0]?.trim() ?? "";+ return rest ? `/fix ${rest}` : "/fix";+ }+ return null;+}++const SEVERITY_LABEL: Record<ReviewSeverity, string> = { critical: "Critical", high: "High", medium: "Medium", low: "Low" };++export function severityLabel(severity: ReviewSeverity): string {+ return SEVERITY_LABEL[severity];+}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.tsxnew file mode 100644index 00000000..74004ee6--- /dev/null+++ b/apps/app/src/react-app/domains/session/commands/session-command-controls.tsx@@ -0,0 +1,271 @@+/** @jsxImportSource react */+import { useEffect, useState } from "react";+import { FileDiff, Gauge, Redo2, Undo2 } from "lucide-react";++import { Button } from "@/components/ui/button";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { cn } from "@/lib/utils";+import { omnirushAccountStatus } from "@/app/lib/desktop";+import { omnirushUsageSummary } from "@/app/lib/omnirush-usage";+import type { OmniRushServerClient, OmniRushPendingUploads, OmniRushSessionSnapshot } from "@/app/lib/omnirush-server";+import { snapshotKey } from "@/react-app/domains/session/sync/session-sync";+import { getReactQueryClient } from "@/react-app/infra/query-client";+import { refreshAccountStatus, useAccountStatusStore } from "@/app/lib/quality";+import type { ModelRef } from "@/app/types";+import { linuxSandboxView, useLinuxSandbox } from "@/react-app/domains/settings/linux-sandbox";+import { useSessionModelSelection } from "@/react-app/domains/session/surface/session-model-store";+import type { ProviderCatalog } from "@/react-app/domains/session/surface/use-model-behavior";+import { ChangesPanel } from "./changes-panel";+import { contextUse, uploadsLine } from "./context-usage";+import { useSessionCommandsStore } from "./session-commands-store";+import { chatUndoKey } from "./undo-key";+import { useCachedQueryData, useUndoRedo, visibleMessages, type SessionCommandTarget } from "./use-session-commands";++export type SessionCommandModelProps = {+ selectedModel: ModelRef;+ modelLabel: string;+ modelVariant: string | null;+ modelVariantLabel: string;+ modelBehaviorOptions?: { value: string | null; label: string }[];+ providerCatalog?: ProviderCatalog;+ onModelVariantChange: (value: string | null) => void;+};++export type SessionCommandControlsProps = SessionCommandTarget & {+ serverClient: OmniRushServerClient | null;+ model: SessionCommandModelProps | null;+};++const iconButton = "hidden rounded-xl text-gray-10 transition-colors hover:bg-muted hover:text-foreground lg:inline-flex";++function isMac() {+ return typeof navigator !== "undefined" && /Mac/i.test(navigator.platform);+}++/**+ * The session header's chat commands: Undo last turn (and Redo while a turn+ * is undone), the Changes panel, and the Status popover.+ */+export function SessionCommandControls(props: SessionCommandControlsProps) {+ const commands = useUndoRedo(props);+ const openChanges = useSessionCommandsStore((state) => state.openChanges);+ const { undo, redo, canUndo, canRedo } = commands;++ 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 (action === "undo" && !canUndo) return;+ if (action === "redo" && !canRedo) return;+ event.preventDefault();+ void (action === "undo" ? undo() : redo());+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [canRedo, canUndo, redo, undo]);++ const mod = isMac() ? "⌘" : "Ctrl+";+ return (+ <>+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ className={iconButton}+ aria-label="Undo last turn"+ data-testid="session-undo"+ disabled={!canUndo}+ onClick={() => void undo()}+ >+ <Undo2 size={16} className={cn(commands.busyAction === "undo" && "animate-pulse")} />+ </Button>+ }+ />+ <TooltipContent>Undo last turn ({mod}Z)</TooltipContent>+ </Tooltip>+ {canRedo || commands.busyAction === "redo" ? (+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ className={iconButton}+ aria-label="Redo"+ data-testid="session-redo"+ disabled={!canRedo}+ onClick={() => void redo()}+ >+ <Redo2 size={16} className={cn(commands.busyAction === "redo" && "animate-pulse")} />+ </Button>+ }+ />+ <TooltipContent>Redo the undone turn ({mod}{isMac() ? "⇧Z" : "Shift+Z"})</TooltipContent>+ </Tooltip>+ ) : null}+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ className={iconButton}+ aria-label="Changes"+ data-testid="session-changes"+ onClick={() => openChanges(props.sessionId)}+ >+ <FileDiff size={16} />+ </Button>+ }+ />+ <TooltipContent>Changes</TooltipContent>+ </Tooltip>+ <StatusPopover {...props} />+ <ChangesPanel+ workspaceId={props.workspaceId}+ sessionId={props.sessionId}+ opencodeBaseUrl={props.opencodeBaseUrl}+ token={props.token}+ workspaceRoot={props.workspaceRoot}+ />+ </>+ );+}++function StatusPopover(props: SessionCommandControlsProps) {+ const [open, setOpen] = useState(false);+ return (+ <Popover open={open} onOpenChange={setOpen}>+ <Tooltip>+ <TooltipTrigger+ render={+ <PopoverTrigger+ render={+ <Button+ variant="ghost"+ size="icon-sm"+ className={cn(iconButton, open && "bg-primary/10 text-primary")}+ aria-label="Status"+ data-testid="session-status"+ >+ <Gauge size={16} />+ </Button>+ }+ />+ }+ />+ <TooltipContent>Status</TooltipContent>+ </Tooltip>+ <PopoverContent align="end" className="w-[22rem] gap-0 rounded-2xl p-0" data-testid="session-status-popover">+ {open ? <StatusRows {...props} /> : null}+ </PopoverContent>+ </Popover>+ );+}++type Row = { label: string; value: string; detail?: string | null; tone?: "warning" };++function StatusRow({ row }: { row: Row }) {+ return (+ <div className="flex items-start gap-3 px-4 py-2" data-status-row={row.label}>+ <span className="w-24 shrink-0 text-[12px] text-muted-foreground">{row.label}</span>+ <span className="min-w-0 flex-1">+ <span className={cn("block text-[12.5px] text-foreground", row.tone === "warning" && "font-medium text-amber-11")}>{row.value}</span>+ {row.detail ? <span className="block text-[11.5px] text-muted-foreground">{row.detail}</span> : null}+ </span>+ </div>+ );+}++const FALLBACK_MODEL: SessionCommandModelProps = {+ selectedModel: { providerID: "", modelID: "" },+ modelLabel: "",+ modelVariant: null,+ modelVariantLabel: "",+ onModelVariantChange: () => undefined,+};++function StatusRows(props: SessionCommandControlsProps) {+ const model = props.model ?? FALLBACK_MODEL;+ const selection = useSessionModelSelection({+ sessionId: props.sessionId,+ fallbackModel: model.selectedModel,+ fallbackModelLabel: model.modelLabel,+ fallbackVariant: model.modelVariant,+ fallbackVariantLabel: model.modelVariantLabel,+ fallbackBehaviorOptions: model.modelBehaviorOptions,+ providerCatalog: model.providerCatalog,+ onFallbackVariantChange: model.onModelVariantChange,+ });+ const cached = useCachedQueryData<OmniRushSessionSnapshot>(snapshotKey(props.workspaceId, props.sessionId));+ const snapshot = cached?.session.id === props.sessionId ? cached : null;+ const account = useAccountStatusStore((store) => store.status);+ const [pending, setPending] = useState<OmniRushPendingUploads | null>(null);+ const [pendingFailed, setPendingFailed] = useState(false);++ useEffect(() => {+ void refreshAccountStatus(omnirushAccountStatus);+ // The newest reply's token counts (the chat's own query fetches them again).+ void getReactQueryClient().invalidateQueries({ queryKey: snapshotKey(props.workspaceId, props.sessionId) });+ let cancelled = false;+ if (props.serverClient) {+ props.serverClient.getPendingUploads().then(+ (value) => { if (!cancelled) setPending(value); },+ () => { if (!cancelled) setPendingFailed(true); },+ );+ }+ return () => {+ cancelled = true;+ };+ }, [props.serverClient, props.sessionId, props.workspaceId]);++ const rows: Row[] = [];+ const messages = visibleMessages(snapshot).map((message) => message.info as { role?: string; tokens?: never; providerID?: string; modelID?: string });+ const lastModel = [...messages].reverse().find((item) => item.role === "assistant" && item.modelID);+ const modelName = selection.modelLabel || lastModel?.modelID || "";+ if (modelName) {+ rows.push({ label: "Model", value: modelName });+ rows.push({ label: "Effort", value: selection.modelVariantLabel || selection.modelVariant || "default" });+ }+ const context = contextUse(messages, (providerID, modelID) => {+ const limit = (model.providerCatalog?.[providerID]?.[modelID] as { limit?: { context?: number } } | undefined)?.limit?.context;+ return typeof limit === "number" ? limit : null;+ });+ if (context) rows.push({ label: "Context", value: context.text, tone: context.warning ? "warning" : undefined, detail: context.warning ? "The chat is close to its limit; it will be compacted soon." : null });+ else rows.push({ label: "Context", value: "nothing used yet" });++ const usage = account?.connected && account.usage ? omnirushUsageSummary(account.usage) : null;+ rows.push(usage+ ? { label: "Tokens left", value: usage.short, detail: usage.line !== usage.short ? usage.line : null }+ : { label: "Tokens left", value: account?.connected ? "unknown" : "sign in to see" });++ return (+ <div className="flex flex-col py-2">+ <div className="px-4 pb-1 pt-1 text-[13px] font-medium">Status</div>+ {rows.map((row) => <StatusRow key={row.label} row={row} />)}+ <SandboxRow client={props.serverClient} workspaceId={props.workspaceId} />+ <StatusRow+ row={{+ label: "Uploads",+ value: pending ? uploadsLine(pending) ?? "unknown" : pendingFailed ? "unknown" : "checking…",+ }}+ />+ </div>+ );+}++function SandboxRow(props: { client: OmniRushServerClient | null; workspaceId: string }) {+ const sandbox = useLinuxSandbox(props.client, props.workspaceId, { fresh: false });+ const box = sandbox.box;+ if (!props.client) return null;+ if (!box) return <StatusRow row={{ label: "Sandbox", value: sandbox.problem ? "unknown" : "checking…" }} />;+ const view = linuxSandboxView(box, sandbox.pending);+ const backend = box.backend?.label ?? box.backend?.id ?? box.runtime?.name ?? null;+ const value = box.on ? `on${backend ? ` · ${backend}` : ""} · ${view.title.toLowerCase()}` : "off";+ return <StatusRow row={{ label: "Sandbox", value, detail: view.detail }} />;+}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.tsnew file mode 100644index 00000000..d5e8ac97--- /dev/null+++ b/apps/app/src/react-app/domains/session/commands/session-commands-store.ts@@ -0,0 +1,43 @@+import { create } from "zustand";++/**+ * What a mounted chat surface offers the session header and the Changes+ * panel: sending a chat command ("/review", "/fix 1, 3") through the+ * composer's own send path, so it queues, shows and recovers like a typed one.+ */+export type SessionCommandBridge = {+ runCommand: (text: string) => void | Promise<void>;+ /** The chat is working (a turn runs or a send is on its way). */+ busy: boolean;+};++type SessionCommandsStore = {+ bridges: Record<string, SessionCommandBridge>;+ /** The chat whose Changes panel is open, or null. */+ changesOpenFor: string | null;+ register: (sessionId: string, bridge: SessionCommandBridge) => () => void;+ openChanges: (sessionId: string) => void;+ closeChanges: () => void;+};++export const useSessionCommandsStore = create<SessionCommandsStore>((set, get) => ({+ bridges: {},+ changesOpenFor: null,+ register: (sessionId, bridge) => {+ set((state) => ({ bridges: { ...state.bridges, [sessionId]: bridge } }));+ return () => {+ if (get().bridges[sessionId] !== bridge) return;+ set((state) => {+ const next = { ...state.bridges };+ delete next[sessionId];+ return { bridges: next };+ });+ };+ },+ openChanges: (sessionId) => set({ changesOpenFor: sessionId }),+ closeChanges: () => set({ changesOpenFor: null }),+}));++export function useSessionCommandBridge(sessionId: string | null | undefined): SessionCommandBridge | null {+ return useSessionCommandsStore((state) => (sessionId ? state.bridges[sessionId] ?? null : 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.tsnew file mode 100644index 00000000..fd0d93c1--- /dev/null+++ b/apps/app/src/react-app/domains/session/commands/undo-key.ts@@ -0,0 +1,15 @@+// Cmd/Ctrl+Z for the chat: undo the last turn (Shift: redo), never a text field's own undo.++/** A key press Cmd/Ctrl+Z may take for the chat: never from a text field that has text (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;+ 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;+ if (target.isContentEditable && (target.textContent ?? "").replace(/[\u200B\uFEFF]/g, "").trim().length > 0) return null;+ }+ return event.shiftKey ? "redo" : "undo";+}+diff --git a/apps/app/src/react-app/domains/session/commands/undo-notice.ts b/apps/app/src/react-app/domains/session/commands/undo-notice.tsnew file mode 100644index 00000000..4b0dd96c--- /dev/null+++ b/apps/app/src/react-app/domains/session/commands/undo-notice.ts@@ -0,0 +1,56 @@+// What "Undo last turn" and "Redo" say they did to the project's files.+// The same wording as the OmniRush CLI's undo notice (engine tui+// util/undo-notice.ts), with "Redo" for the button in place of "/redo".++export type RevertOutcome = {+ restored?: readonly string[] | null;+ merged?: readonly string[] | null;+ kept?: readonly string[] | null;+};++export type UndoNotice = {+ title: string;+ message: string;+ variant: "success" | "warning";+};++const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? "" : "s"}`;+const list = (files: readonly string[], max = 3) =>+ files.length <= max ? files.join(", ") : `${files.slice(0, max).join(", ")} and ${files.length - max} more`;+const strings = (value: unknown): string[] =>+ Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [];++export const NOT_TRACKED_MESSAGE =+ "The chat was rewound. This folder is not a git repository, so file changes are not tracked and no file was restored.";++/**+ * The toast after an undo. `revert` is the engine's answer (the session's+ * `revert`); `tracked` is false when the folder's file changes are not+ * tracked (it is not a git repository).+ */+export function undoNotice(revert: RevertOutcome | null | undefined, tracked: boolean): UndoNotice {+ if (!tracked) return { title: "Undid the last turn", message: NOT_TRACKED_MESSAGE, variant: "warning" };+ const restored = strings(revert?.restored);+ const merged = strings(revert?.merged);+ const kept = strings(revert?.kept);+ const lines: string[] = [];+ const changed = restored.length + merged.length;+ if (changed) lines.push(`Restored ${plural(changed, "file")}: ${list([...restored, ...merged])}.`);+ if (merged.length) lines.push(`Your own edits in ${list(merged)} were kept.`);+ if (kept.length) {+ lines.push(+ `Left ${plural(kept.length, "file")} as ${kept.length === 1 ? "it is" : "they are"}: ${list(kept)} (changed by you or another program too).`,+ );+ }+ if (!lines.length) lines.push("The last turn changed no files.");+ lines.push("Redo puts it back.");+ return { title: "Undid the last turn", message: lines.join(" "), variant: kept.length ? "warning" : "success" };+}++export const REDO_NOTICE = "Redid the last turn";++/** Whether the engine tracks this project's file changes: a git worktree (an untracked folder's project worktree is "/"). */+export function projectTracksFiles(project: { worktree?: string | null } | null | undefined): boolean {+ const worktree = project?.worktree?.trim() ?? "";+ return Boolean(worktree) && worktree !== "/";+}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.tsnew file mode 100644index 00000000..2fd36268--- /dev/null+++ b/apps/app/src/react-app/domains/session/commands/use-session-commands.ts@@ -0,0 +1,196 @@+import { useCallback, useMemo, useRef, useState, useSyncExternalStore } from "react";+import type { QueryKey } from "@tanstack/react-query";++import { toast } from "@/components/ui/sonner";+import { createClient, unwrap } from "@/app/lib/opencode";+import { createClientV2, isOpencodeV2BaseUrl } from "@/app/lib/opencode-v2-adapter";+import { abortSessionSafe, revertSession, unrevertSession } from "@/app/lib/opencode-session";+import type { OmniRushSessionMessage, OmniRushSessionSnapshot } from "@/app/lib/omnirush-server";+import { getReactQueryClient } from "@/react-app/infra/query-client";+import {+ applySessionRevert,+ applySessionUnrevert,+ snapshotKey,+ statusKey,+ transcriptKey,+} from "@/react-app/domains/session/sync/session-sync";+import { getComposerDraft, useComposerStateStore } from "@/react-app/domains/session/surface/composer-state-store";+import { REDO_NOTICE, projectTracksFiles, undoNotice } from "./undo-notice";++export type SessionCommandTarget = {+ workspaceId: string;+ sessionId: string;+ opencodeBaseUrl: string;+ token: string;+ workspaceRoot: string;+};++export type OpencodeClient = ReturnType<typeof createClient>;++/** A query's cached data, read straight from the cache (never fetched or refetched from here). */+export function useCachedQueryData<T>(queryKey: QueryKey): T | undefined {+ const queryClient = getReactQueryClient();+ const subscribe = useCallback((listener: () => void) => queryClient.getQueryCache().subscribe(listener), [queryClient]);+ const hash = JSON.stringify(queryKey);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ const read = useCallback(() => queryClient.getQueryData<T>(queryKey), [queryClient, hash]);+ return useSyncExternalStore(subscribe, read, read);+}++export function useOpencodeClient(target: Pick<SessionCommandTarget, "opencodeBaseUrl" | "token" | "workspaceRoot">): OpencodeClient {+ return useMemo(+ () => isOpencodeV2BaseUrl(target.opencodeBaseUrl)+ ? createClientV2(target.opencodeBaseUrl, target.workspaceRoot || undefined, { token: target.token })+ : createClient(target.opencodeBaseUrl, target.workspaceRoot.trim() || undefined, { token: target.token, mode: "omnirush" }),+ [target.opencodeBaseUrl, target.token, target.workspaceRoot],+ );+}++const role = (message: OmniRushSessionMessage) => (message.info as { role?: string }).role;++/** The messages the chat shows: those before its revert point (an undo hides the rest until redo). */+export function visibleMessages(snapshot: OmniRushSessionSnapshot | null | undefined): OmniRushSessionMessage[] {+ if (!snapshot) return [];+ const revertId = snapshot.session.revert?.messageID ?? null;+ return revertId ? snapshot.messages.filter((message) => message.info.id < revertId) : snapshot.messages;+}++/** The user message an undo rewinds to: the newest one the chat still shows. */+export function undoTarget(snapshot: OmniRushSessionSnapshot | null | undefined): OmniRushSessionMessage | null {+ return visibleMessages(snapshot).findLast((message) => role(message) === "user") ?? null;+}++/** The text a user message was sent with (what goes back into the composer after an undo). */+export function userMessageText(message: OmniRushSessionMessage | null): string {+ if (!message) return "";+ return message.parts+ .flatMap((part) => {+ const value = part as { type?: string; text?: string; synthetic?: boolean; ignored?: boolean };+ return value.type === "text" && !value.synthetic && !value.ignored && typeof value.text === "string" ? [value.text] : [];+ })+ .join("\n")+ .trim();+}++/** The newest user message's id (the "Last turn" of the Changes panel). */+export function latestUserMessageId(snapshot: OmniRushSessionSnapshot | null | undefined): string | null {+ return undoTarget(snapshot)?.info.id ?? null;+}++/** The chat's session and newest messages as the engine has them now (enough to find its last turn). */+async function freshSnapshot(client: OpencodeClient, sessionId: string): Promise<OmniRushSessionSnapshot> {+ const [session, messages] = await Promise.all([+ client.session.get({ sessionID: sessionId }).then((result) => unwrap(result)),+ client.session.messages({ sessionID: sessionId, limit: 400 }).then((result) => unwrap(result)),+ ]);+ return { session, messages, todos: [], status: { type: "idle" } } as unknown as OmniRushSessionSnapshot;+}++const trackedByRoot = new Map<string, boolean>();++async function tracksFiles(client: OpencodeClient, root: string): Promise<boolean> {+ const known = trackedByRoot.get(root);+ if (known !== undefined) return known;+ try {+ const project = unwrap(await client.project.current({ directory: root || undefined })) as { worktree?: string } | null;+ const tracked = projectTracksFiles(project);+ trackedByRoot.set(root, tracked);+ return tracked;+ } catch {+ // Unknown: say what the engine reported about the files.+ return true;+ }+}++/**+ * Undo of the last turn and its redo, for one chat: the engine rewinds the+ * chat to its newest user message and takes the turn's file changes back+ * (content-checked: the person's own edits are kept), and redo puts it back.+ */+export function useUndoRedo(target: SessionCommandTarget) {+ const client = useOpencodeClient(target);+ const snapshot = useCachedQueryData<OmniRushSessionSnapshot>(snapshotKey(target.workspaceId, target.sessionId));+ const status = useCachedQueryData<{ type: string }>(statusKey(target.workspaceId, target.sessionId));+ const [busyAction, setBusyAction] = useState<"undo" | "redo" | null>(null);+ const restoredTextRef = useRef<{ sessionId: string; text: string } | null>(null);+ const redoRef = useRef<() => Promise<void>>(async () => undefined);++ const current = snapshot?.session.id === target.sessionId ? snapshot : null;+ const transcript = useCachedQueryData<Array<{ role?: string }>>(transcriptKey(target.workspaceId, target.sessionId));+ const canUndo = (Boolean(undoTarget(current)) || Boolean(transcript?.some((message) => message.role === "user"))) && busyAction === null;+ const canRedo = Boolean(current?.session.revert?.messageID) && busyAction === null;+ const running = (status?.type ?? current?.status.type ?? "idle") !== "idle";++ const stopFirst = useCallback(async (source: string) => {+ if (!running) return;+ await abortSessionSafe(client, target.sessionId, target.workspaceRoot || undefined, {+ source,+ initiator: "user",+ reason: "abort active run before undo or redo",+ });+ }, [client, running, target.sessionId, target.workspaceRoot]);++ const redo = useCallback(async () => {+ if (busyAction) return;+ const queryClient = getReactQueryClient();+ setBusyAction("redo");+ try {+ const session = unwrap(await client.session.get({ sessionID: target.sessionId })) as { revert?: { messageID?: string } | null };+ if (!session?.revert?.messageID) return;+ await stopFirst("session.commands.redo");+ await unrevertSession(client, target.sessionId);+ applySessionUnrevert(target.workspaceId, target.sessionId);+ void queryClient.invalidateQueries({ queryKey: snapshotKey(target.workspaceId, target.sessionId) });+ // The text an undo put back goes away with the turn it belongs to.+ const restored = restoredTextRef.current;+ if (restored?.sessionId === target.sessionId) {+ const draft = getComposerDraft(useComposerStateStore.getState(), target.sessionId);+ if (draft.trim() === restored.text.trim()) useComposerStateStore.getState().replaceDraft(target.sessionId, "");+ restoredTextRef.current = null;+ }+ toast.success(REDO_NOTICE, { duration: 4000 });+ } catch (error) {+ toast.error(`Redo failed: ${error instanceof Error ? error.message : String(error)}`);+ } finally {+ setBusyAction(null);+ }+ }, [busyAction, client, stopFirst, target.sessionId, target.workspaceId]);+ redoRef.current = redo;++ const undo = useCallback(async () => {+ if (busyAction) return;+ setBusyAction("undo");+ try {+ await stopFirst("session.commands.undo");+ // The engine's own view, not the screen's cache: the newest user message before its revert point.+ const message = undoTarget(await freshSnapshot(client, target.sessionId));+ if (!message) {+ toast.info("Nothing to undo yet", { duration: 3000 });+ return;+ }+ const reverted = await revertSession(client, target.sessionId, message.info.id);+ applySessionRevert(target.workspaceId, reverted);+ // The turn's prompt goes back into an empty composer (a draft being written is left alone).+ const text = userMessageText(message);+ const draft = getComposerDraft(useComposerStateStore.getState(), target.sessionId);+ if (text && !draft.trim()) {+ useComposerStateStore.getState().replaceDraft(target.sessionId, text);+ restoredTextRef.current = { sessionId: target.sessionId, text };+ }+ const tracked = await tracksFiles(client, target.workspaceRoot);+ const notice = undoNotice((reverted as { revert?: Parameters<typeof undoNotice>[0] } | null)?.revert, tracked);+ const show = notice.variant === "warning" ? toast.warning : toast.success;+ show(notice.title, {+ description: notice.message,+ duration: 9000,+ action: { label: "Redo", onClick: () => void redoRef.current() },+ });+ } catch (error) {+ toast.error(`Undo failed: ${error instanceof Error ? error.message : String(error)}`);+ } finally {+ setBusyAction(null);+ }+ }, [busyAction, client, stopFirst, target.sessionId, target.workspaceId, target.workspaceRoot]);++ return { client, snapshot: current, running, canUndo, canRedo, busyAction, undo, redo };+}diff --git a/apps/app/src/react-app/domains/session/surface/session-surface.tsx b/apps/app/src/react-app/domains/session/surface/session-surface.tsxindex feb1481b..f00b3b01 100644--- a/apps/app/src/react-app/domains/session/surface/session-surface.tsx+++ b/apps/app/src/react-app/domains/session/surface/session-surface.tsx@@ -54,6 +54,7 @@ import { ReactSessionComposer } from "./composer/composer";import { WorkspaceRunModeMenu } from "./composer/workspace-run-mode-menu";import { FullPermissionsToggle } from "./composer/full-permissions-toggle";import { SandboxStatusChip } from "./composer/sandbox-status-chip";+import { useSessionCommandsStore } from "@/react-app/domains/session/commands/session-commands-store";import { SubagentModelMenu } from "./composer/subagent-model-menu";import { useSessionModelSelection } from "./session-model-store";import type { ProviderCatalog } from "./use-model-behavior";@@ -2365,6 +2366,16 @@ export function SessionSurface(props: SessionSurfaceProps) {}}, [attachments, baseRenderedMessages, buildDraft, clearComposer, draft, liveStatus.type, persistedDraftKey, props.onDraftChange, props.sessionId, sendDraft, sessionOwner]);+ // A chat command from a button ("/review", "/fix 1, 3"): sent like a typed one, the composer's draft left alone.+ const runChatCommand = useCallback(async (text: string) => {+ await handleSend({ draft: text, attachments: [], mentions: {}, pasteParts: [], revertMessageId: null });+ }, [handleSend]);+ const chatCommandBusy = chatStreaming || queuedDrainState.phase.kind === "sending" || queuedDrainState.phase.kind === "admission_unknown";+ useEffect(+ () => useSessionCommandsStore.getState().register(props.sessionId, { runCommand: runChatCommand, busy: chatCommandBusy }),+ [chatCommandBusy, props.sessionId, runChatCommand],+ );+// One-step run from the empty-state hero: the route keeps the continuation// in this session's composer and marks the submitted snapshot for auto-send.// Fire the same send path as the send button once the composer is usable;@@ -3387,6 +3398,7 @@ export function SessionSurface(props: SessionSurfaceProps) {onMcpReconnect={handleMcpReconnect}onMcpReopenAuthorization={handleMcpReopenAuthorization}onMcpRetry={handleMcpRetry}+ onRunCommand={runChatCommand}><MessageListmessages={renderedMessages}diff --git a/apps/app/tests/session-commands.test.ts b/apps/app/tests/session-commands.test.tsnew file mode 100644index 00000000..165016ef--- /dev/null+++ b/apps/app/tests/session-commands.test.ts@@ -0,0 +1,159 @@+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 { contextUse, uploadsLine } from "../src/react-app/domains/session/commands/context-usage";+import { changeTotals, normalizeChanges, patchLines } from "../src/react-app/domains/session/commands/changes";+import { chatUndoKey } from "../src/react-app/domains/session/commands/undo-key";++describe("undoNotice", () => {+ test("says what happened to each file, in the CLI's words", () => {+ expect(undoNotice({ restored: ["src/a.ts", "b.md"], merged: [], kept: [] }, true)).toEqual({+ title: "Undid the last turn",+ message: "Restored 2 files: src/a.ts, b.md. Redo puts it back.",+ variant: "success",+ });+ expect(undoNotice({ restored: ["a.ts"], merged: ["c.ts"], kept: ["d.ts"] }, true)).toEqual({+ title: "Undid the last turn",+ message: "Restored 2 files: a.ts, c.ts. Your own edits in c.ts were kept. Left 1 file as it is: d.ts (changed by you or another program too). Redo puts it back.",+ variant: "warning",+ });+ expect(undoNotice({ restored: ["1", "2", "3", "4", "5"] }, true).message).toBe("Restored 5 files: 1, 2, 3 and 2 more. Redo puts it back.");+ expect(undoNotice({ kept: ["x", "y"] }, true).message).toBe("Left 2 files as they are: x, y (changed by you or another program too). Redo puts it back.");+ });++ test("a turn that changed nothing, and a folder that is not a git repository", () => {+ expect(undoNotice({}, true).message).toBe("The last turn changed no files. Redo puts it back.");+ expect(undoNotice(undefined, true).message).toBe("The last turn changed no files. Redo puts it back.");+ expect(undoNotice({ restored: ["a"] }, false)).toEqual({ title: "Undid the last turn", message: NOT_TRACKED_MESSAGE, variant: "warning" });+ expect(NOT_TRACKED_MESSAGE).toBe("The chat was rewound. This folder is not a git repository, so file changes are not tracked and no file was restored.");+ });++ test("a git project is one with a worktree other than /", () => {+ expect(projectTracksFiles({ worktree: "/home/me/app" })).toBe(true);+ expect(projectTracksFiles({ worktree: "/" })).toBe(false);+ expect(projectTracksFiles({})).toBe(false);+ expect(projectTracksFiles(null)).toBe(false);+ });+});++const REVIEW = [+ "Reviewed: uncommitted changes (3 files)",+ "",+ "### High",+ "1. src/server.ts:42 - Missing await on save",+ " The response is sent before the write finishes when the disk is slow.",+ "",+ "### Low",+ "2. `README.md:3` - Typo in the title",+ "3. src/util.ts - Unused import",+ "",+ "Reply **fix these** to fix them all (or for example **fix 1, 3**), or run /fix.",+].join("\n");++describe("parseReviewReply", () => {+ test("reads the issues, their severity and the fix offer", () => {+ const review = parseReviewReply(REVIEW);+ expect(review?.reviewed).toBe("uncommitted changes (3 files)");+ expect(review?.fixable).toBe(true);+ expect(review?.counts).toEqual({ critical: 0, high: 1, medium: 0, low: 2 });+ expect(review?.issues).toEqual([+ { number: 1, severity: "high", path: "src/server.ts", line: 42, title: "Missing await on save" },+ { number: 2, severity: "low", path: "README.md", line: 3, title: "Typo in the title" },+ { number: 3, severity: "low", path: "src/util.ts", line: null, title: "Unused import" },+ ]);+ });++ test("a clean review offers no fix; other replies are not reviews", () => {+ const clean = parseReviewReply("Reviewed: uncommitted changes (1 files)\n\nNo issues found.");+ expect(clean?.clean).toBe(true);+ expect(clean?.fixable).toBe(false);+ expect(parseReviewReply("Here is the plan:\n1. src/a.ts - do this")).toBeNull();+ expect(parseReviewReply("")).toBeNull();+ expect(parseReviewReply(null)).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");+ expect(commandTemplateLabel("You are a code reviewer. Your job is...\n\nInput: main\n")).toBe("/review main");+ expect(commandTemplateLabel("Fix the issues from the code review above. \n\nIf issue numbers...")).toBe("/fix");+ expect(commandTemplateLabel("Fix the issues from the code review above. 1, 3\n\nIf issue numbers...")).toBe("/fix 1, 3");+ expect(commandTemplateLabel("please fix the bug")).toBeNull();+ });+});++describe("contextUse", () => {+ const limit = (providerID: string, modelID: string) => (providerID === "omnirush" && modelID === "m" ? 400_000 : undefined);++ test("the newest reply with output against the model's window", () => {+ const use = contextUse([+ { role: "user" },+ { role: "assistant", providerID: "omnirush", modelID: "m", tokens: { input: 1_000, output: 10, reasoning: 0 } },+ { role: "user" },+ { role: "assistant", providerID: "omnirush", modelID: "m", tokens: { input: 15_000, output: 2_000, reasoning: 1_000, cache: { read: 2_500, write: 500 } } },+ { role: "assistant", providerID: "omnirush", modelID: "m", tokens: { input: 99, output: 0, reasoning: 0 } },+ ], limit);+ expect(use?.used).toBe(21_000);+ expect(use?.text).toBe("21,000 of 400,000 tokens (5%) · 379,000 left");+ expect(use?.warning).toBe(false);+ });++ test("warns from 85%, and counts without a known window", () => {+ expect(contextUse([{ role: "assistant", providerID: "omnirush", modelID: "m", tokens: { input: 340_000, output: 1, reasoning: 0 } }], limit)?.warning).toBe(true);+ expect(contextUse([{ role: "assistant", providerID: "x", modelID: "y", tokens: { input: 5, output: 5, reasoning: 0 } }], limit)?.text).toBe("10 tokens");+ expect(contextUse([{ role: "user" }], limit)).toBeNull();+ });++ test("uploads line", () => {+ expect(uploadsLine({ uploads: 0, archives: 0 })).toBe("nothing waiting");+ expect(uploadsLine({ uploads: 2, archives: 1 })).toBe("3 waiting");+ expect(uploadsLine(null)).toBeNull();+ });+});++describe("changes", () => {+ test("normalizes both diff shapes and totals them", () => {+ const files = normalizeChanges([+ { file: "b.ts", patch: "@@ -1 +1 @@\n-a\n+b\n", additions: 1, deletions: 1, status: "modified" },+ { file: "a.ts", additions: 3, deletions: 0, status: "added" },+ { additions: 1, deletions: 1 },+ ]);+ expect(files.map((file) => file.path)).toEqual(["a.ts", "b.ts"]);+ expect(files[0]?.status).toBe("added");+ expect(changeTotals(files)).toEqual({ files: 2, additions: 4, deletions: 1 });+ expect(normalizeChanges(null)).toEqual([]);+ });++ 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([+ ["hunk", null, null, "@@ -3,3 +3,3 @@"],+ ["context", 3, 3, "keep"],+ ["del", 4, null, "old"],+ ["add", null, 4, "new"],+ ["context", 5, 5, "tail"],+ ]);+ });+});++describe("chatUndoKey", () => {+ const key = (init: Partial<KeyboardEvent> & { target?: unknown }) => ({+ key: "z", metaKey: false, ctrlKey: false, altKey: false, shiftKey: false, defaultPrevented: false, target: null, ...init,+ }) as Parameters<typeof chatUndoKey>[0];++ test("Cmd/Ctrl+Z undoes and Shift redoes outside text fields", () => {+ expect(chatUndoKey(key({ metaKey: true }), true)).toBe("undo");+ expect(chatUndoKey(key({ ctrlKey: true }), false)).toBe("undo");+ expect(chatUndoKey(key({ ctrlKey: true, shiftKey: true }), false)).toBe("redo");+ expect(chatUndoKey(key({ ctrlKey: true }), true)).toBeNull();+ expect(chatUndoKey(key({ metaKey: true, key: "y" }), true)).toBeNull();+ });++ test("a text field keeps its own undo; an empty composer does not", () => {+ 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");+ });+});diff --git a/apps/server/src/capture-client.ts b/apps/server/src/capture-client.tsindex e0ff4b3e..959d4b92 100644--- a/apps/server/src/capture-client.ts+++ b/apps/server/src/capture-client.ts@@ -17,6 +17,7 @@ import { START_GATE_MS } from "./session-archive/capture-v2.js";import { LATE_WRITES_CAP_MS } from "./session-archive/late-writes.js";import type { FilesUsedStatus } from "./session-archive/index.js";import type { BoxCaptureInfo } from "./box/service.js";+import type { CommandEventType } from "./command-events.js";import { CaptureHost, type CaptureDiagnostics, type CaptureHostOptions, type EngineReplacement, type EngineTarget, type LateWritesGate, type PromptRecord } from "./capture-host.js";import {@@ -91,6 +92,8 @@ export type CaptureService = {captureSnapshot(sessionId: string, trigger: "prompt" | "turn_completed", outcome?: "aborted"): void;/** A prompt steered the running turn: its "turn.steer" event (turn-steer.ts steerRecord). */steerTurn(sessionId: string, steer: Record<string, unknown>): void;+ /** An undo / redo / review / fix the person ran: its additive event (command-events.ts). */+ recordCommand(sessionId: string, type: CommandEventType, data: Record<string, unknown>): void;/** The engine took a steer: its turn is followed (if no observer follows it already). */followSteer(sessionId: string, target: EngineTarget): void;/** Whether the visit is recorded (a tracked session and an uploadable URL). */@@ -238,6 +241,10 @@ class CaptureClient implements CaptureService {this.send({ kind: "call", id: null, method: "steerTurn", args: [sessionId, steer] });}+ recordCommand(sessionId: string, type: CommandEventType, data: Record<string, unknown>): void {+ this.send({ kind: "call", id: null, method: "recordCommand", args: [sessionId, type, data] });+ }+followSteer(sessionId: string, target: EngineTarget): void {this.observedTargets.delete(sessionId);this.observedTargets.set(sessionId, target);diff --git a/apps/server/src/capture-host.ts b/apps/server/src/capture-host.tsindex 97e51fef..611c6272 100644--- a/apps/server/src/capture-host.ts+++ b/apps/server/src/capture-host.ts@@ -25,6 +25,7 @@ import {type SessionObservers,} from "./session-upload-observer.js";import type { CaptureStopOptions } from "./capture-protocol.js";+import type { CommandEventType } from "./command-events.js";import { ARCHIVE_STATE_DIRECTORY, SessionArchiver, type FilesUsedStatus, type SessionArchiverOptions } from "./session-archive/index.js";import { archiveOwner } from "./session-archive/account-park.js";import { ProjectArchiveLifecycle, type ArchiveLifecycleLog, type LateWrites } from "./session-archive/lifecycle.js";@@ -300,6 +301,11 @@ export class CaptureHost {this.sessionUploader.steerTurn(sessionId, steer);}+ /** An undo / redo / review / fix the person ran (command-events.ts): its additive event. */+ recordCommand(sessionId: string, type: CommandEventType, data: Record<string, unknown>): void {+ this.sessionUploader.recordCommand(sessionId, type, data);+ }+/*** The engine took a steer: the running turn goes on, followed by its* observer. A turn no observer follows (its observation ended) is followeddiff --git a/apps/server/src/capture-protocol.ts b/apps/server/src/capture-protocol.tsindex bad69007..3ad81b57 100644--- a/apps/server/src/capture-protocol.ts+++ b/apps/server/src/capture-protocol.ts@@ -9,6 +9,7 @@*/import type { CaptureHost, EngineReplacement, EngineTarget, LateWritesGate, PromptRecord } from "./capture-host.js";import type { BoxCaptureInfo } from "./box/service.js";+import type { CommandEventType } from "./command-events.js";import type { FolderGateOptions } from "./session-archive/detect.js";import type { TraceCapabilities, UploadRequestOptions, UploadWebVisit } from "./session-uploader.js";@@ -25,6 +26,7 @@ export type CaptureCalls = {recordPrompt: [sessionId: string, prompt: PromptRecord];captureSnapshot: [sessionId: string, trigger: "prompt" | "turn_completed", outcome?: "aborted"];steerTurn: [sessionId: string, steer: Record<string, unknown>];+ recordCommand: [sessionId: string, type: CommandEventType, data: Record<string, unknown>];followSteer: [sessionId: string, target: EngineTarget];recordWebVisit: [sessionId: string, visit: UploadWebVisit];archiveSessionStarted: [sessionId: string, root: string, target: EngineTarget];@@ -183,6 +185,8 @@ export function invokeCapture(host: CaptureHost, call: CaptureCall): unknown {return host.captureSnapshot(...call.args);case "steerTurn":return host.steerTurn(...call.args);+ case "recordCommand":+ return host.recordCommand(...call.args);case "followSteer":return host.followSteer(...call.args);case "recordWebVisit":diff --git a/apps/server/src/command-events.test.ts b/apps/server/src/command-events.test.tsnew file mode 100644index 00000000..4d12feaf--- /dev/null+++ b/apps/server/src/command-events.test.ts@@ -0,0 +1,135 @@+import { afterEach, describe, expect, test } from "bun:test";+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { zstdDecompressSync } from "node:zlib";++import { commandEvent, revertEvent, revertRequest, reviewTarget } from "./command-events.js";+import { SessionUploader } from "./session-uploader.js";++// The additive events of the review and undo commands: same names and fields as the CLI.++describe("reviewTarget", () => {+ test("names what a review looks at from its arguments", () => {+ expect(reviewTarget("")).toBe("uncommitted");+ expect(reviewTarget(" ")).toBe("uncommitted");+ expect(reviewTarget(undefined)).toBe("uncommitted");+ expect(reviewTarget("a1b2c3d")).toBe("commit");+ expect(reviewTarget("0123456789abcdef0123456789abcdef01234567")).toBe("commit");+ expect(reviewTarget("https://github.com/acme/app/pull/12")).toBe("pr");+ expect(reviewTarget("42")).toBe("pr");+ expect(reviewTarget("#42")).toBe("pr");+ expect(reviewTarget("main")).toBe("branch");+ expect(reviewTarget("feature/login-form")).toBe("branch");+ expect(reviewTarget("the auth changes please")).toBe("other");+ });+});++describe("commandEvent", () => {+ test("review and fix dispatches give their events; other commands give none", () => {+ expect(commandEvent(JSON.stringify({ command: "review", arguments: "" }))).toEqual({ type: "review.run", data: { target: "uncommitted", has_arguments: false } });+ expect(commandEvent(new TextEncoder().encode(JSON.stringify({ command: "/review", arguments: " main " })).buffer)).toEqual({ type: "review.run", data: { target: "branch", has_arguments: true } });+ expect(commandEvent({ command: "fix", arguments: "" })).toEqual({ type: "review.fix", data: { issues: "all" } });+ expect(commandEvent({ command: "fix", arguments: "1, 3" })).toEqual({ type: "review.fix", data: { issues: "some" } });+ expect(commandEvent({ command: "init", arguments: "" })).toBeNull();+ expect(commandEvent("not json")).toBeNull();+ expect(commandEvent(undefined)).toBeNull();+ });+});++describe("revertEvent", () => {+ const session = {+ id: "ses_1",+ revert: { messageID: "msg_4", restored: ["src/a.ts", "b.md"], merged: ["c.ts"], kept: ["d.ts"], snapshot: "x" },+ };++ test("an undo counts what happened to each file", () => {+ expect(revertEvent("revert", session)).toEqual({+ type: "turn.undone",+ data: {+ message_id: "msg_4",+ repeat: false,+ restored: 2,+ merged: 1,+ kept: 1,+ files: { restored: ["src/a.ts", "b.md"], merged: ["c.ts"], kept: ["d.ts"] },+ },+ });+ expect(revertEvent("revert", session, "msg_9")?.data.repeat).toBe(true);+ });++ test("an engine without the file lists records empty ones", () => {+ expect(revertEvent("revert", { revert: { messageID: "msg_1" } })?.data).toMatchObject({ restored: 0, merged: 0, kept: 0, files: { restored: [], merged: [], kept: [] } });+ });++ test("a redo names the revert point before it", () => {+ expect(revertEvent("unrevert", { id: "ses_1" }, "msg_4")).toEqual({ type: "turn.redone", data: { message_id: "msg_4" } });+ expect(revertEvent("unrevert", { id: "ses_1" })).toEqual({ type: "turn.redone", data: { message_id: null } });+ });++ test("no session, or no revert point after an undo, records nothing", () => {+ expect(revertEvent("revert", null)).toBeNull();+ expect(revertEvent("revert", { id: "ses_1" })).toBeNull();+ expect(revertEvent("unrevert", "oops")).toBeNull();+ });+});++describe("revertRequest", () => {+ test("matches only POST undo and redo", () => {+ expect(revertRequest("POST", "/session/ses_1/revert")).toEqual({ sessionId: "ses_1", kind: "revert" });+ expect(revertRequest("POST", "/session/ses_1/unrevert")).toEqual({ sessionId: "ses_1", kind: "unrevert" });+ expect(revertRequest("GET", "/session/ses_1/revert")).toBeNull();+ expect(revertRequest("POST", "/session/ses_1/message")).toBeNull();+ });+});++describe("SessionUploader.recordCommand", () => {+ const roots: string[] = [];+ afterEach(async () => {+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));+ });++ test("records the schema-1 events with upload-safe paths, and nothing for an untracked chat", async () => {+ const root = await mkdtemp(join(tmpdir(), "omnirush-cmd-"));+ roots.push(root);+ const envelopes: Array<Record<string, unknown>> = [];+ const sessionUploader = new SessionUploader({+ upload: async (_sessionId, compressed) => {+ const envelope = JSON.parse(zstdDecompressSync(compressed).toString("utf8")) as Record<string, unknown>;+ const files = Array.isArray(envelope.files) ? envelope.files as Array<{ path?: string; content?: string }> : [];+ const traceFile = files.find((file) => file.path === "__omnirush__/trace.json");+ envelopes.push(traceFile?.content && envelope.trace === undefined ? { ...envelope, trace: (JSON.parse(traceFile.content) as { events?: unknown[] }).events ?? [] } : envelope);+ return Response.json({ ok: true }, { status: 201 });+ },+ changeDebounceMs: 10,+ fallbackScanMs: 60_000,+ });+ 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]"] } });+ sessionUploader.recordCommand(sessionId, undone!.type, undone!.data);+ sessionUploader.recordCommand(sessionId, "turn.redone", { message_id: "msg_2" });+ const review = commandEvent({ command: "review", arguments: "" })!;+ sessionUploader.recordCommand(sessionId, review.type, review.data);+ sessionUploader.recordCommand(sessionId, "review.fix", { issues: "all" });+ sessionUploader.recordCommand("session-unknown-1234", "review.fix", { issues: "all" });+ await sessionUploader.idle(sessionId);+ sessionUploader.flushTrace(sessionId);+ await sessionUploader.stop();++ const events = envelopes.flatMap((envelope) => (Array.isArray(envelope.trace) ? envelope.trace : []) as Array<{ type: string; data?: Record<string, unknown> }>);+ 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 });+ 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[0]).not.toContain("[email protected]");+ 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);+ expect(pick("review.fix")[0]!.data).toEqual({ schema: 1, issues: "all" });+ });+});diff --git a/apps/server/src/command-events.ts b/apps/server/src/command-events.tsnew file mode 100644index 00000000..b2108d0f--- /dev/null+++ b/apps/server/src/command-events.ts@@ -0,0 +1,86 @@+/**+ * What the chat commands "review" and "undo" record in a session's trace, as+ * additive schema-1 events (SessionUploader.recordCommand). PARITY: the same+ * names, fields and rules as omnirush-cli's src/command-events.js.+ *+ * turn.undone {schema, message_id, repeat, restored, merged, kept, files: {restored, merged, kept}}+ * turn.redone {schema, message_id}+ * review.run {schema, target, has_arguments}+ * review.fix {schema, issues}+ *+ * A session that never runs them carries none of these events.+ */++export type CommandEventType = "turn.undone" | "turn.redone" | "review.run" | "review.fix";+export type CommandEvent = { type: CommandEventType; data: Record<string, unknown> };+export type ReviewTarget = "uncommitted" | "commit" | "branch" | "pr" | "other";++/** What a review was asked to look at, from its arguments. */+export function reviewTarget(args: unknown): ReviewTarget {+ const text = String(args ?? "").trim();+ if (!text) return "uncommitted";+ if (/github\.com|\/pull\//i.test(text) || /^#?\d+$/.test(text)) return "pr";+ if (/^[0-9a-f]{7,40}$/i.test(text)) return "commit";+ if (/^[\w./-]+$/.test(text)) return "branch";+ return "other";+}++function parseBody(body: unknown): unknown {+ if (body instanceof ArrayBuffer) body = new TextDecoder().decode(body);+ else if (body instanceof Uint8Array) body = new TextDecoder().decode(body);+ if (typeof body !== "string") return body;+ try {+ return JSON.parse(body);+ } catch {+ return null;+ }+}++/**+ * The event a dispatched engine command records, or null for any other+ * command or prompt. `body` is the POST /session/:id/command body.+ */+export function commandEvent(body: unknown): CommandEvent | null {+ const parsed = parseBody(body) as { command?: unknown; arguments?: unknown } | null;+ if (!parsed || typeof parsed !== "object") return null;+ const name = typeof parsed.command === "string" ? parsed.command.replace(/^\//, "") : null;+ const args = typeof parsed.arguments === "string" ? parsed.arguments.trim() : "";+ if (name === "review") return { type: "review.run", data: { target: reviewTarget(args), has_arguments: Boolean(args) } };+ if (name === "fix") return { type: "review.fix", data: { issues: args ? "some" : "all" } };+ return null;+}++const list = (value: unknown): string[] => (Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : []);++/**+ * The event of a successful undo ("revert") or redo ("unrevert"). `session`+ * is the engine's answer; `previous` the revert point the session had before+ * (null when none). Null when the answer is not a session.+ */+export function revertEvent(kind: "revert" | "unrevert", session: unknown, previous: string | null = null): CommandEvent | null {+ if (!session || typeof session !== "object") return null;+ if (kind === "unrevert") return { type: "turn.redone", data: { message_id: previous ?? null } };+ const revert = (session as { revert?: unknown }).revert;+ if (!revert || typeof revert !== "object") return null;+ const record = revert as Record<string, unknown>;+ const files = { restored: list(record.restored), merged: list(record.merged), kept: list(record.kept) };+ return {+ type: "turn.undone",+ data: {+ message_id: typeof record.messageID === "string" ? record.messageID : null,+ repeat: Boolean(previous),+ restored: files.restored.length,+ merged: files.merged.length,+ kept: files.kept.length,+ files,+ },+ };+}++/** The session and kind of an undo / redo request (POST /session/:id/revert|unrevert), or null. */+export function revertRequest(method: string, normalizedPath: string): { sessionId: string; kind: "revert" | "unrevert" } | null {+ if (method !== "POST") return null;+ const match = normalizedPath.match(/^\/session\/([^/]+)\/(revert|unrevert)$/);+ if (!match?.[1] || !match[2]) return null;+ return { sessionId: match[1], kind: match[2] as "revert" | "unrevert" };+}diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 15c3a297..2e4a0110 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -209,6 +209,7 @@ import type { LateWritesGate } from "./capture-host.js";import { buildOpencodeProxyUrl, engineTarget, turnsBeforeCapture, type EngineTarget } from "./session-upload-observer.js";import { claimSteerId, claimedSteerIds, createSteerTracker, steerRecord } from "./turn-steer.js";import { FOLDER_NOT_WRITABLE, folderWriteGate, readOnlyPrompt } from "./folder-write-check.js";+import { commandEvent, revertEvent, revertRequest } from "./command-events.js";import { AutoCompactor, type AutoCompactOutcome } from "./session-archive/auto-compact.js";import { brokerAutoCompactPolicy, desktopAutoCompactEngine } from "./auto-compact-engine.js";import { OmniRushGatewayBroker } from "./omnirush-gateway-broker.js";@@ -1044,6 +1045,28 @@ export async function engineHasSession(baseUrl: string, auth: string | null, dir}}+/** The message a chat's undo currently rewinds to (its revert point), or null: read before an undo or redo. */+async function engineRevertPoint(baseUrl: string, auth: string | null, directory: string | null, sessionId: string): Promise<string | null> {+ const headers = new Headers();+ if (auth) headers.set("Authorization", auth);+ const scoped = scopeWorkspaceOpencodeRequest(headers, "", directory);+ try {+ const response = await loopbackFetch(buildOpencodeProxyUrl(baseUrl, `/session/${encodeURIComponent(sessionId)}`, scoped.search), {+ method: "GET",+ headers: scoped.headers,+ signal: AbortSignal.timeout(ENGINE_SESSION_CHECK_TIMEOUT_MS),+ });+ if (!response.ok) {+ await response.body?.cancel().catch(() => undefined);+ return null;+ }+ const session = await response.json() as { revert?: { messageID?: unknown } | null } | null;+ return typeof session?.revert?.messageID === "string" ? session.revert.messageID : null;+ } catch {+ return null;+ }+}+const SESSION_STOP_TIMEOUT_MS = 5_000;const SESSION_STOP_MAX_SESSIONS = 100;@@ -2361,6 +2384,19 @@ 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);+ }+ // 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"+ ? revertRequest(method, normalizeOpencodeProxyPath(proxyPath))+ : null;+ const revertSessionId = revertCall ? decodeEngineRouteParam(revertCall.sessionId) : null;+ const revertTracked = Boolean(revertSessionId && capture?.hasSession(revertSessionId));+ const revertBefore = revertTracked && revertSessionId ? await engineRevertPoint(baseUrl, auth, directory, revertSessionId) : null;// The engine took a steer: its turn goes on (followed as before), and the steer's record is found in the background.const steered = (service: CaptureService, sessionId: string, target: EngineTarget) => {service.followSteer(sessionId, target);@@ -2549,6 +2585,14 @@ export async function proxyOpencodeRequest(input: {if (workspace && response.ok) capture.observeSession(uploadedSessionId, engineTarget(served.baseUrl, served.headers, search));}if (capture?.uploadEnabled && deletedUploadedSessionId && response.ok) capture.sessionDeleted(deletedUploadedSessionId);+ if (capture && revertCall && revertTracked && revertSessionId && response.ok) {+ const service = capture;+ const kind = revertCall.kind;+ void response.clone().json().then((session: unknown) => {+ const event = revertEvent(kind, session, revertBefore);+ if (event) service.recordCommand(revertSessionId, event.type, event.data);+ }).catch(() => undefined);+ }return response;};diff --git a/apps/server/src/session-uploader.ts b/apps/server/src/session-uploader.tsindex c4941659..4335b747 100644--- a/apps/server/src/session-uploader.ts+++ b/apps/server/src/session-uploader.ts@@ -5930,6 +5930,27 @@ export class SessionUploader {});}+ /**+ * A chat command that is not a prompt of its own kind (command-events.ts):+ * "turn.undone" / "turn.redone" (undo of the last turn and its redo, with+ * 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.+ */+ recordCommand(sessionId: string, type: "turn.undone" | "turn.redone" | "review.run" | "review.fix", data: Record<string, unknown>): void {+ const state = this.sessions.get(sessionId);+ if (!state || state.finished) return;+ const files = data.files && typeof data.files === "object" ? data.files as Record<string, unknown> : null;+ 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)) : [],+ ]))+ : undefined;+ this.appendTrace(state, type, { schema: 1, ...data, ...(cleanFiles ? { files: cleanFiles } : {}) });+ }+/*** Captures a change snapshot for an engine milestone: right as a prompt is* dispatched, or once a turn completes. When nothing changed since the last