Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: code editor beside the chat

ogsamrat74e5c7fd583f
diff --git a/apps/app/package.json b/apps/app/package.json
index e7d77ad4..6567281e 100644
--- a/apps/app/package.json
+++ b/apps/app/package.json
@@ -78,6 +78,7 @@
"marked-emoji": "^2.0.3",
"marked-katex-extension": "^5.1.10",
"mermaid": "^11.17.1",
+ "monaco-editor": "0.57.0",
"motion": "^12.38.0",
"react": "catalog:",
"react-dom": "catalog:",
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.ts
index a0a30984..bc54c41f 100644
--- a/apps/app/src/app/lib/omnirush-server.ts
+++ b/apps/app/src/app/lib/omnirush-server.ts
@@ -1571,6 +1571,25 @@ async function fetchWithTimeout(
}
}
+export type OmniRushEditorTree = { git: boolean; files: string[]; truncated: boolean; generatedAt: number };
+export type OmniRushEditorFile = {
+ path: string;
+ content: string | null;
+ bytes: number;
+ updatedAt: number;
+ binary?: boolean;
+ tooLarge?: boolean;
+};
+export type OmniRushEditorGitFile = { path: string; from?: string; index: string; worktree: string };
+export type OmniRushEditorGitStatus = {
+ repo: boolean;
+ branch: string | null;
+ upstream: string | null;
+ ahead: number;
+ behind: number;
+ files: OmniRushEditorGitFile[];
+};
+
async function requestJson<T>(
baseUrl: string,
path: string,
@@ -2648,6 +2667,57 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: s
},
),
+ // The desktop editor (server routes/editor.ts).
+ editorTree: (workspaceId: string) =>
+ requestJson<OmniRushEditorTree>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/editor/tree`, { token, hostToken, timeoutMs: 60_000 }),
+
+ editorReadFile: (workspaceId: string, path: string) =>
+ requestJson<OmniRushEditorFile>(
+ baseUrl,
+ `/workspace/${encodeURIComponent(workspaceId)}/editor/file?path=${encodeURIComponent(path)}`,
+ { token, hostToken },
+ ),
+
+ editorWriteFile: (
+ workspaceId: string,
+ payload: { path: string; content?: string; delete?: boolean; baseUpdatedAt?: number | null; force?: boolean; sessionId?: string | null; source?: "editor" | "review" },
+ ) =>
+ requestJson<{ ok: true; path: string; bytes: number; deleted: boolean; updatedAt: number | null }>(
+ baseUrl,
+ `/workspace/${encodeURIComponent(workspaceId)}/editor/file`,
+ { token, hostToken, method: "PUT", body: payload },
+ ),
+
+ editorReview: (
+ workspaceId: string,
+ payload: { sessionId: string; path: string; decision: "accept" | "reject"; added: number; removed: number; scope: "hunk" | "file" },
+ ) =>
+ requestJson<{ ok: true }>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/editor/review`, { token, hostToken, method: "POST", body: payload }),
+
+ editorGitStatus: (workspaceId: string) =>
+ requestJson<OmniRushEditorGitStatus>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/editor/git/status`, { token, hostToken, timeoutMs: 30_000 }),
+
+ editorGitOriginal: (workspaceId: string, path: string, ref: "HEAD" | "index") =>
+ requestJson<{ path: string; ref: string; content: string | null; exists: boolean; binary?: boolean; tooLarge?: boolean }>(
+ baseUrl,
+ `/workspace/${encodeURIComponent(workspaceId)}/editor/git/original?path=${encodeURIComponent(path)}&ref=${ref}`,
+ { token, hostToken },
+ ),
+
+ editorGitStage: (workspaceId: string, paths: string[], stage: boolean) =>
+ requestJson<OmniRushEditorGitStatus>(
+ baseUrl,
+ `/workspace/${encodeURIComponent(workspaceId)}/editor/git/${stage ? "stage" : "unstage"}`,
+ { token, hostToken, method: "POST", body: { paths }, timeoutMs: 60_000 },
+ ),
+
+ editorGitCommit: (workspaceId: string, message: string) =>
+ requestJson<{ ok: true; commit: string; status: OmniRushEditorGitStatus }>(
+ baseUrl,
+ `/workspace/${encodeURIComponent(workspaceId)}/editor/git/commit`,
+ { token, hostToken, method: "POST", body: { message }, timeoutMs: 130_000 },
+ ),
+
deleteWorkspaceFiles: async (
workspaceId: string,
files: Array<{ path: string; recursive?: boolean }>,
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.tsx
index be4d31f8..72b72441 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 } fro
import { usePanelRef } from "react-resizable-panels";
import { DesktopUpdateButton } from "../../settings/state/desktop-updater-provider";
import { BuildathonChip } from "../../buildathon/buildathon";
-import { ArrowLeft, Cloud, FileText, Globe, Maximize2, MoreHorizontal, PanelRight, TextSearch, X, Zap } from "lucide-react";
+import { ArrowLeft, Cloud, Code2, FileText, Globe, Maximize2, MoreHorizontal, PanelRight, TextSearch, X, Zap } from "lucide-react";
import { resolveExtensionIconSrc } from "@/react-app/design-system/extension-icon-src";
import { t } from "../../../../i18n";
@@ -86,6 +86,8 @@ import { SidePanel } from "../panel/side-panel";
import { getSidePanelSessionKey } from "../panel/side-panel-session";
import { useCreateTab } from "../panel/use-side-panel-tabs";
import { TerminalDock } from "../terminal/terminal-dock";
+import { LazyEditorPanel } from "../editor/editor-entry";
+import { useEditorStore } from "../editor/editor-store";
import { useActivePanelTab, usePanelTabStore, useSessionPanelState } from "../panel/panel-tab-store";
import { useWorkspaceShellLayout } from "../../../shell/workspace-shell-layout";
import { useControlAction, type OmniRushControlAction } from "../../../shell/control/control-provider";
@@ -103,6 +105,7 @@ import { isSameWorkbenchSession } from "./workbench-store";
import { ReactSessionRuntime } from "../sync/runtime-sync";
import { useSessionInteractions } from "../sync/use-session-interactions";
import { createClient } from "@/app/lib/opencode";
+import type { Client } from "@/app/types";
import { createQuitGuard, finishGuardKey, leavingRunningTurn, type FinishGuardKind } from "@/app/lib/good-session";
import { FinishGuardDialog, TurnGuardDialog, finishGuardFor, requestFinishIt } from "@/react-app/domains/quality/good-session";
import { createClientV2, isOpencodeV2BaseUrl } from "@/app/lib/opencode-v2-adapter";
@@ -289,6 +292,8 @@ export type SessionPageProps = {
primaryTitle?: string;
terminalOpen?: boolean;
onTerminalOpenChange?: (open: boolean) => void;
+ /** The selected workspace's engine client: the editor reads the agent's per-turn changes from it. */
+ opencodeClient?: Client | null;
onSessionTabsChange?: (tabs: OpenSessionTab[]) => void;
};
@@ -482,6 +487,11 @@ export function SessionPage(props: SessionPageProps) {
const activeSidePanel = sessionSidePanel;
const sidePanelOpen = activeSidePanel !== null;
const panelRailActive = activeSidePanel === "panel";
+ const editorOpen = activeSidePanel === "editor";
+ // The editor needs the local server's file routes: desktop, local workspaces.
+ const editorAvailable = isElectronRuntime()
+ && Boolean(props.omnirushServerClient && props.runtimeWorkspaceId)
+ && props.selectedWorkspaceDisplay.workspaceType !== "remote";
const denControlPlaneConfigured = useDenControlPlaneConfigured();
const showCloudSignIn =
shellConfig.cloudSignin && denControlPlaneConfigured && !denAuth.isSignedIn && denAuth.status !== "checking";
@@ -779,6 +789,20 @@ export function SessionPage(props: SessionPageProps) {
const closeRightPane = useCallback(() => {
setCurrentSidePanel(null);
}, [setCurrentSidePanel]);
+ // Cmd/Ctrl+Shift+E toggles the editor; Cmd/Ctrl+P opens it with quick open (use-shell-shortcuts.ts).
+ const editorShowRequest = useEditorStore((state) => state.showRequest);
+ const editorToggleRequest = useEditorStore((state) => state.toggleRequest);
+ const lastEditorRequests = useRef({ show: editorShowRequest, toggle: editorToggleRequest });
+ useEffect(() => {
+ const last = lastEditorRequests.current;
+ lastEditorRequests.current = { show: editorShowRequest, toggle: editorToggleRequest };
+ if (!editorAvailable) {
+ if (editorShowRequest !== last.show) useEditorStore.getState().setQuickOpen(false);
+ return;
+ }
+ if (editorShowRequest !== last.show) setCurrentSidePanel("editor");
+ else if (editorToggleRequest !== last.toggle) toggleCurrentSidePanel("editor");
+ }, [editorAvailable, editorShowRequest, editorToggleRequest, setCurrentSidePanel, toggleCurrentSidePanel]);
const openGeneralSidePanel = useCallback(() => {
setCurrentSidePanel("panel");
}, [setCurrentSidePanel]);
@@ -1401,6 +1425,26 @@ export function SessionPage(props: SessionPageProps) {
<div className="flex h-full min-h-0 flex-col overflow-y-auto bg-background">
{props.settingsSlot}
</div>
+ ) : activeSidePanel === "editor" && editorAvailable && props.omnirushServerClient && props.runtimeWorkspaceId ? (
+ <LazyEditorPanel
+ client={props.omnirushServerClient}
+ workspaceId={props.runtimeWorkspaceId}
+ workspaceRoot={props.selectedWorkspaceRoot}
+ sessionId={props.selectedSessionId}
+ sessionBusy={sessionTurnRunning(props.selectedSessionId)}
+ opencodeClient={props.opencodeClient ?? null}
+ terminalOpen={Boolean(props.terminalOpen)}
+ onToggleTerminal={() => props.onTerminalOpenChange?.(!props.terminalOpen)}
+ terminal={props.terminalOpen ? (
+ <TerminalDock
+ workspaceId={props.selectedWorkspaceId}
+ workspaceRoot={props.selectedWorkspaceRoot}
+ isRemoteWorkspace={props.selectedWorkspaceDisplay.workspaceType === "remote"}
+ onClose={() => props.onTerminalOpenChange?.(false)}
+ />
+ ) : null}
+ onClose={closeRightPane}
+ />
) : activeSidePanel === "panel" ? (
<SidePanel
sessionId={sidePanelSessionKey}
@@ -1998,7 +2042,7 @@ export function SessionPage(props: SessionPageProps) {
) : null}
</div>
</ResizablePanel>
- {props.terminalOpen && !isMobile ? (
+ {props.terminalOpen && !isMobile && !(editorOpen && editorAvailable) ? (
<>
<ResizableHandle />
<ResizablePanel defaultSize="280px" minSize="160px" maxSize="55%" className="min-h-0">
@@ -2021,8 +2065,8 @@ export function SessionPage(props: SessionPageProps) {
<ResizableHandle className="hidden bg-transparent lg:flex" />
<ResizablePanel
panelRef={browserPanelRef}
- defaultSize={`${activeSidePanel === "extensions" ? Math.max(browserPanelDefaultWidth, 480) : browserPanelDefaultWidth}px`}
- minSize={activeSidePanel === "extensions" ? "420px" : "320px"}
+ defaultSize={`${activeSidePanel === "extensions" ? Math.max(browserPanelDefaultWidth, 480) : activeSidePanel === "editor" ? Math.max(browserPanelDefaultWidth, 640) : browserPanelDefaultWidth}px`}
+ minSize={activeSidePanel === "extensions" ? "420px" : activeSidePanel === "editor" ? "420px" : "320px"}
maxSize="70%"
className="min-h-0 overflow-hidden pl-2 lg:flex lg:flex-col"
>
@@ -2034,6 +2078,23 @@ export function SessionPage(props: SessionPageProps) {
) : null}
</ResizablePanelGroup>
<aside className="hidden w-10 shrink-0 flex-col items-center gap-1 px-1 py-2 text-muted-foreground lg:flex mac:titlebar-no-drag">
+ {editorAvailable ? (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ className={cn(
+ "rounded-xl transition-colors hover:bg-muted hover:text-foreground",
+ editorOpen && "bg-primary/10 text-primary hover:bg-primary/15 hover:text-primary",
+ )}
+ onClick={() => toggleCurrentSidePanel("editor")}
+ title={`Editor (${/Mac/i.test(navigator.platform) ? "⌘⇧E" : "Ctrl+Shift+E"})`}
+ aria-label="Editor"
+ aria-pressed={editorOpen}
+ data-editor-rail
+ >
+ <Code2 size={15} />
+ </Button>
+ ) : null}
{isElectronRuntime() ? (
<Button
variant="ghost"
diff --git a/apps/app/src/react-app/domains/session/editor/editor-entry.tsx b/apps/app/src/react-app/domains/session/editor/editor-entry.tsx
new file mode 100644
index 00000000..ef2e58f4
--- /dev/null
+++ b/apps/app/src/react-app/domains/session/editor/editor-entry.tsx
@@ -0,0 +1,21 @@
+/** @jsxImportSource react */
+import { lazy, Suspense } from "react";
+
+import type { EditorPanelProps } from "./editor-panel";
+
+/** Monaco and the editor load the first time the editor opens, never with the chat. */
+const EditorPanel = lazy(() => import("./editor-panel"));
+
+export function LazyEditorPanel(props: EditorPanelProps) {
+ return (
+ <Suspense
+ fallback={(
+ <div className="flex h-full items-center justify-center text-xs text-muted-foreground" data-editor-loading>
+ Loading editor…
+ </div>
+ )}
+ >
+ <EditorPanel {...props} />
+ </Suspense>
+ );
+}
diff --git a/apps/app/src/react-app/domains/session/editor/editor-models.ts b/apps/app/src/react-app/domains/session/editor/editor-models.ts
new file mode 100644
index 00000000..3a7eb26d
--- /dev/null
+++ b/apps/app/src/react-app/domains/session/editor/editor-models.ts
@@ -0,0 +1,215 @@
+/**
+ * The editor's documents for one workspace: a Monaco model per open file
+ * (shared by its file tab, its review diff and its git diff, so an edit shows
+ * everywhere), when it was read, and whether it has unsaved changes. Kept
+ * while the app runs, so closing the panel keeps unsaved text.
+ */
+import type * as MonacoApi from "monaco-editor/editor/editor.api.js";
+
+import type { OmniRushServerClient } from "@/app/lib/omnirush-server";
+import { languageForPath, type Monaco } from "./monaco";
+import { useEditorStore } from "./editor-store";
+
+export type FileDoc = {
+ path: string;
+ model: MonacoApi.editor.ITextModel;
+ /** The file's mtime when it was last read or saved; null for a file that does not exist yet. */
+ updatedAt: number | null;
+ savedVersion: number;
+ /** The file changed on disk while this document had unsaved changes. */
+ conflict: boolean;
+};
+
+export type OpenResult =
+ | { ok: true; doc: FileDoc }
+ | { ok: false; reason: "binary" | "too_large" | "missing" | "error"; message: string };
+
+export type SaveOptions = { sessionId: string | null; source: "editor" | "review"; force?: boolean };
+export type SaveResult = { ok: true } | { ok: false; conflict: boolean; message: string };
+
+export class EditorDocuments {
+ private docs = new Map<string, FileDoc>();
+ private loading = new Map<string, Promise<OpenResult>>();
+ private baselines = new Map<string, MonacoApi.editor.ITextModel>();
+
+ constructor(
+ readonly monaco: Monaco,
+ public client: OmniRushServerClient,
+ readonly workspaceId: string,
+ ) {}
+
+ uri(path: string, scheme = "omnirush-file"): MonacoApi.Uri {
+ return this.monaco.Uri.from({ scheme, authority: this.workspaceId.replace(/[^A-Za-z0-9_-]/g, "_"), path: `/${path}` });
+ }
+
+ get(path: string): FileDoc | null {
+ return this.docs.get(path) ?? null;
+ }
+
+ isDirty(doc: FileDoc): boolean {
+ return doc.model.getAlternativeVersionId() !== doc.savedVersion;
+ }
+
+ private track(doc: FileDoc): void {
+ doc.model.onDidChangeContent(() => {
+ useEditorStore.getState().setDirty(this.workspaceId, doc.path, this.isDirty(doc));
+ });
+ }
+
+ open(path: string): Promise<OpenResult> {
+ const existing = this.docs.get(path);
+ if (existing) return Promise.resolve({ ok: true, doc: existing });
+ const pending = this.loading.get(path);
+ if (pending) return pending;
+ const load = (async (): Promise<OpenResult> => {
+ try {
+ const file = await this.client.editorReadFile(this.workspaceId, path);
+ if (file.binary) return { ok: false, reason: "binary", message: "This file is binary and cannot be edited here." };
+ if (file.tooLarge || file.content === null) return { ok: false, reason: "too_large", message: "This file is too large to open in the editor (over 5 MB)." };
+ const model = this.monaco.editor.createModel(file.content, languageForPath(path), this.uri(path));
+ const doc: FileDoc = { path, model, updatedAt: file.updatedAt, savedVersion: model.getAlternativeVersionId(), conflict: false };
+ this.docs.set(path, doc);
+ this.track(doc);
+ return { ok: true, doc };
+ } catch (error) {
+ const status = (error as { status?: number }).status;
+ if (status === 404) return { ok: false, reason: "missing", message: "This file no longer exists." };
+ return { ok: false, reason: "error", message: error instanceof Error ? error.message : "Could not open this file." };
+ } finally {
+ this.loading.delete(path);
+ }
+ })();
+ this.loading.set(path, load);
+ return load;
+ }
+
+ /** A document for a file that does not exist on disk (an agent deletion under review): empty, saved state "missing". */
+ openMissing(path: string): FileDoc {
+ const existing = this.docs.get(path);
+ if (existing) return existing;
+ const model = this.monaco.editor.createModel("", languageForPath(path), this.uri(path));
+ const doc: FileDoc = { path, model, updatedAt: null, savedVersion: model.getAlternativeVersionId(), conflict: false };
+ this.docs.set(path, doc);
+ this.track(doc);
+ return doc;
+ }
+
+ async save(path: string, options: SaveOptions): Promise<SaveResult> {
+ const doc = this.docs.get(path);
+ if (!doc) return { ok: false, conflict: false, message: "This file is not open." };
+ const version = doc.model.getAlternativeVersionId();
+ const content = doc.model.getValue(this.monaco.editor.EndOfLinePreference.TextDefined);
+ try {
+ const result = await this.client.editorWriteFile(this.workspaceId, {
+ path,
+ content,
+ baseUpdatedAt: doc.updatedAt,
+ ...(options.force ? { force: true } : {}),
+ ...(options.sessionId ? { sessionId: options.sessionId, source: options.source } : {}),
+ });
+ doc.updatedAt = result.updatedAt;
+ doc.savedVersion = version;
+ doc.conflict = false;
+ useEditorStore.getState().setDirty(this.workspaceId, path, this.isDirty(doc));
+ return { ok: true };
+ } catch (error) {
+ const status = (error as { status?: number }).status;
+ return { ok: false, conflict: status === 409, message: error instanceof Error ? error.message : "Could not save this file." };
+ }
+ }
+
+ async remove(path: string, options: SaveOptions): Promise<SaveResult> {
+ try {
+ await this.client.editorWriteFile(this.workspaceId, {
+ path,
+ delete: true,
+ ...(options.sessionId ? { sessionId: options.sessionId, source: options.source } : {}),
+ });
+ const doc = this.docs.get(path);
+ if (doc) {
+ doc.updatedAt = null;
+ doc.savedVersion = doc.model.getAlternativeVersionId();
+ useEditorStore.getState().setDirty(this.workspaceId, path, false);
+ }
+ return { ok: true };
+ } catch (error) {
+ return { ok: false, conflict: false, message: error instanceof Error ? error.message : "Could not delete this file." };
+ }
+ }
+
+ /**
+ * Reads open files again (after a turn, on focus): a clean document takes
+ * the disk text (one undo step), a dirty one is flagged as a conflict.
+ */
+ async refresh(paths?: string[]): Promise<void> {
+ const targets = (paths ?? [...this.docs.keys()]).map((path) => this.docs.get(path)).filter((doc): doc is FileDoc => Boolean(doc));
+ await Promise.all(targets.map(async (doc) => {
+ let file;
+ try {
+ file = await this.client.editorReadFile(this.workspaceId, doc.path);
+ } catch (error) {
+ if ((error as { status?: number }).status === 404 && doc.updatedAt !== null && !this.isDirty(doc)) {
+ doc.updatedAt = null;
+ }
+ return;
+ }
+ if (file.content === null || file.updatedAt === doc.updatedAt) return;
+ const current = doc.model.getValue(this.monaco.editor.EndOfLinePreference.TextDefined);
+ if (current === file.content) {
+ doc.updatedAt = file.updatedAt;
+ return;
+ }
+ if (this.isDirty(doc)) {
+ doc.conflict = true;
+ return;
+ }
+ doc.model.pushEditOperations([], [{ range: doc.model.getFullModelRange(), text: file.content }], () => null);
+ doc.updatedAt = file.updatedAt;
+ doc.savedVersion = doc.model.getAlternativeVersionId();
+ useEditorStore.getState().setDirty(this.workspaceId, doc.path, false);
+ }));
+ }
+
+ /** Discards unsaved changes: the disk text again. */
+ async revert(path: string): Promise<void> {
+ const doc = this.docs.get(path);
+ if (!doc) return;
+ doc.savedVersion = -1;
+ doc.updatedAt = -1;
+ await this.refresh([path]).catch(() => undefined);
+ }
+
+ /** The read-only "before" model of a review or git diff. */
+ baseline(key: string, path: string, text: string): MonacoApi.editor.ITextModel {
+ const uri = this.uri(`${key}/${path}`, "omnirush-base");
+ let model = this.baselines.get(uri.toString());
+ if (!model || model.isDisposed()) {
+ model = this.monaco.editor.createModel(text, languageForPath(path), uri);
+ this.baselines.set(uri.toString(), model);
+ } else if (model.getValue() !== text) {
+ model.setValue(text);
+ }
+ return model;
+ }
+
+ dispose(): void {
+ for (const doc of this.docs.values()) doc.model.dispose();
+ for (const model of this.baselines.values()) model.dispose();
+ this.docs.clear();
+ this.baselines.clear();
+ }
+}
+
+const byWorkspace = new Map<string, EditorDocuments>();
+
+export function editorDocuments(monaco: Monaco, client: OmniRushServerClient, workspaceId: string): EditorDocuments {
+ const existing = byWorkspace.get(workspaceId);
+ if (existing) {
+ // A new client object for the same server (a re-render, a token refresh) keeps the open documents.
+ existing.client = client;
+ return existing;
+ }
+ const created = new EditorDocuments(monaco, client, workspaceId);
+ byWorkspace.set(workspaceId, created);
+ return created;
+}
diff --git a/apps/app/src/react-app/domains/session/editor/editor-panel.tsx b/apps/app/src/react-app/domains/session/editor/editor-panel.tsx
new file mode 100644
index 00000000..6508cc58
--- /dev/null
+++ b/apps/app/src/react-app/domains/session/editor/editor-panel.tsx
@@ -0,0 +1,1040 @@
+/** @jsxImportSource react */
+/**
+ * The desktop editor beside the chat: file tree, tabs, Monaco, the agent's
+ * changes for review (accept/reject per hunk), a git panel, quick open and
+ * the integrated terminal. Loaded lazily (editor-entry.tsx) so the chat
+ * never pays for Monaco until the editor is opened.
+ */
+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { FileTree, useFileTree, useFileTreeSearch } from "@pierre/trees/react";
+import {
+ Check,
+ ChevronDown,
+ ChevronUp,
+ CircleDot,
+ FileCode2,
+ GitBranch,
+ GitCommitHorizontal,
+ Minus,
+ PanelLeftClose,
+ PanelLeftOpen,
+ Plus,
+ RefreshCw,
+ Search,
+ SquareTerminal,
+ Undo2,
+ X,
+} from "lucide-react";
+
+import type { Client } from "@/app/types";
+import type { OmniRushEditorGitFile, OmniRushEditorGitStatus, OmniRushServerClient } from "@/app/lib/omnirush-server";
+import { Button } from "@/components/ui/button";
+import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group";
+import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable";
+import { toast } from "@/components/ui/sonner";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { cn } from "@/lib/utils";
+
+import { editorDocuments, type EditorDocuments, type FileDoc } from "./editor-models";
+import { editorWorkspaceState, tabId, useEditorStore, type EditorSideView, type EditorTab, type ReviewScope } from "./editor-store";
+import { EditorSurface, type SurfaceDoc } from "./editor-surface";
+import { acceptHunk, hunkCounts, rejectHunk, type LineHunk } from "./hunk-ops";
+import { languageForPath, setupMonaco, type Monaco } from "./monaco";
+import { QuickOpen } from "./quick-open";
+import { baselinesForTurns, turnFileChange, type TurnFileChange } from "./review";
+import "./editor.css";
+
+export type EditorPanelProps = {
+ client: OmniRushServerClient;
+ workspaceId: string;
+ workspaceRoot: string;
+ sessionId: string | null;
+ sessionBusy: boolean;
+ opencodeClient: Client | null;
+ terminal: ReactNode | null;
+ terminalOpen: boolean;
+ onToggleTerminal: () => void;
+ onClose: () => void;
+};
+
+const MAX_REVIEW_FILES = 60;
+const MAX_REVIEW_TURNS = 30;
+const EMPTY_FILES: string[] = [];
+
+type ReviewFile = TurnFileChange & {
+ /** The file before the reviewed turns; null when the turns created it; undefined when it could not be worked out. */
+ baseline: string | null | undefined;
+};
+
+type ReviewData = { key: string; turns: number; files: ReviewFile[] };
+
+/** The engine's per-turn changes for the chat, oldest first, with each file's text before them. */
+async function loadAgentChanges(input: {
+ opencodeClient: Client;
+ sessionId: string;
+ directory: string;
+ scope: ReviewScope;
+ docs: EditorDocuments;
+ workspaceRoot: string;
+}): Promise<ReviewData> {
+ const { opencodeClient, sessionId, directory, scope, docs } = input;
+ const messagesResult = await opencodeClient.session.messages({ sessionID: sessionId, directory });
+ const messages = (messagesResult.data ?? []) as Array<{ info: { id: string; role: string } }>;
+ const userIds = messages.filter((message) => message.info.role === "user").map((message) => message.info.id);
+ const root = input.workspaceRoot.replace(/[/\\]+$/, "").replace(/\\/g, "/");
+ const relativeChange = (change: TurnFileChange): TurnFileChange | null => {
+ let path = change.path;
+ if (root && path.startsWith(`${root}/`)) path = path.slice(root.length + 1);
+ if (/^([A-Za-z]:)?\//.test(path) || path.split("/").includes("..")) return null;
+ return { ...change, path };
+ };
+ const turns: TurnFileChange[][] = [];
+ const turnIds: string[] = [];
+ // Newest first until the scope is filled: the last turn that changed files, or every turn of the chat.
+ for (const id of [...userIds].reverse().slice(0, MAX_REVIEW_TURNS)) {
+ const result = await opencodeClient.session.diff({ sessionID: sessionId, messageID: id, directory });
+ const changes = ((result.data ?? []) as unknown[])
+ .map(turnFileChange)
+ .filter((change): change is TurnFileChange => change !== null)
+ .map(relativeChange)
+ .filter((change): change is TurnFileChange => change !== null);
+ if (changes.length === 0) continue;
+ turns.unshift(changes);
+ turnIds.unshift(id);
+ if (scope === "turn") break;
+ }
+ const paths = [...new Set(turns.flat().map((change) => change.path))].slice(0, MAX_REVIEW_FILES);
+ const current = new Map<string, string | null>();
+ const unreadable = new Set<string>();
+ await Promise.all(paths.map(async (path) => {
+ const opened = await docs.open(path);
+ if (opened.ok) current.set(path, opened.doc.model.getValue());
+ else if (opened.reason === "missing") current.set(path, null);
+ else unreadable.add(path);
+ }));
+ const baselines = baselinesForTurns(turns, (path) => current.get(path) ?? null);
+ // Binary or very large files are listed without a review diff.
+ for (const path of unreadable) baselines.set(path, undefined);
+ const merged = new Map<string, ReviewFile>();
+ for (const turn of turns) {
+ for (const change of turn) {
+ if (!paths.includes(change.path)) continue;
+ const previous = merged.get(change.path);
+ const status = previous?.status === "added" && change.status !== "deleted" ? "added" : change.status;
+ merged.set(change.path, {
+ ...change,
+ status,
+ additions: (previous?.additions ?? 0) + change.additions,
+ deletions: (previous?.deletions ?? 0) + change.deletions,
+ baseline: baselines.get(change.path),
+ });
+ }
+ }
+ return { key: `${sessionId}:${scope}:${turnIds.join(",")}`, turns: turns.length, files: [...merged.values()] };
+}
+
+const REVIEWED_KEY = "omnirush:editor:reviewed:v1";
+const MAX_REVIEWED = 500;
+
+function textHash(text: string): string {
+ // FNV-1a, 32 bit, with the length: enough to tell "the text that was reviewed" from an edit.
+ let hash = 0x811c9dc5;
+ for (let i = 0; i < text.length; i += 1) {
+ hash ^= text.charCodeAt(i);
+ hash = Math.imul(hash, 0x01000193) >>> 0;
+ }
+ return `${text.length.toString(36)}.${hash.toString(36)}`;
+}
+
+function readReviewed(): Record<string, string> {
+ try {
+ const parsed = JSON.parse(localStorage.getItem(REVIEWED_KEY) ?? "{}");
+ return parsed && typeof parsed === "object" ? parsed as Record<string, string> : {};
+ } catch {
+ return {};
+ }
+}
+
+function isReviewed(reviewKey: string, path: string, text: string): boolean {
+ return readReviewed()[`${reviewKey}|${path}`] === textHash(text);
+}
+
+function markReviewed(reviewKey: string, path: string, text: string): void {
+ const all = readReviewed();
+ const key = `${reviewKey}|${path}`;
+ const hash = textHash(text);
+ if (all[key] === hash) return;
+ delete all[key];
+ all[key] = hash;
+ const keys = Object.keys(all);
+ for (const old of keys.slice(0, Math.max(0, keys.length - MAX_REVIEWED))) delete all[old];
+ try {
+ localStorage.setItem(REVIEWED_KEY, JSON.stringify(all));
+ } catch {
+ // Storage full: the review just shows again after a restart.
+ }
+}
+
+function gitBadge(file: OmniRushEditorGitFile, staged: boolean): string {
+ const letter = staged ? file.index : file.worktree;
+ return letter === "?" ? "U" : letter;
+}
+
+function treeGitStatus(status: OmniRushEditorGitStatus | undefined) {
+ if (!status?.repo) return [];
+ return status.files.map((file) => {
+ const letter = file.worktree !== " " ? file.worktree : file.index;
+ const kind = letter === "?" ? "untracked" : letter === "A" ? "added" : letter === "D" ? "deleted" : letter === "R" ? "renamed" : "modified";
+ return { path: file.path, status: kind as "untracked" | "added" | "deleted" | "renamed" | "modified" };
+ });
+}
+
+const TREE_CSS = `
+ :host {
+ --trees-bg-override: transparent;
+ --trees-selected-bg-override: color-mix(in srgb, currentColor 11%, transparent);
+ --trees-hover-bg-override: color-mix(in srgb, currentColor 6%, transparent);
+ --trees-border-color-override: color-mix(in srgb, currentColor 14%, transparent);
+ --trees-font-family-override: var(--font-sans);
+ --trees-font-size-override: 12px;
+ }
+ button[data-type='item'] { border-radius: 5px; }
+`;
+
+function FilesView(props: {
+ files: string[];
+ truncated: boolean;
+ git: OmniRushEditorGitStatus | undefined;
+ selected: string | null;
+ loading: boolean;
+ error: boolean;
+ onOpen: (path: string) => void;
+ onRefresh: () => void;
+}) {
+ const onOpenRef = useRef(props.onOpen);
+ onOpenRef.current = props.onOpen;
+ const fileSet = useMemo(() => new Set(props.files), [props.files]);
+ const fileSetRef = useRef(fileSet);
+ fileSetRef.current = fileSet;
+ const { model } = useFileTree({
+ density: "compact",
+ fileTreeSearchMode: "hide-non-matches",
+ flattenEmptyDirectories: true,
+ initialExpansion: 1,
+ onSelectionChange: (paths) => {
+ const path = paths.at(-1);
+ if (path && fileSetRef.current.has(path)) onOpenRef.current(path);
+ },
+ paths: [],
+ search: false,
+ unsafeCSS: TREE_CSS,
+ });
+ const search = useFileTreeSearch(model);
+ useEffect(() => model.resetPaths(props.files), [model, props.files]);
+ useEffect(() => model.setGitStatus(treeGitStatus(props.git)), [model, props.git, props.files]);
+ useEffect(() => {
+ if (!props.selected) return;
+ const item = model.getItem(props.selected);
+ if (!item) return;
+ for (const path of model.getSelectedPaths()) if (path !== props.selected) model.getItem(path)?.deselect();
+ item.select();
+ }, [model, props.files, props.selected]);
+ return (
+ <div className="flex h-full min-h-0 flex-col" data-editor-files={props.files.length}>
+ <div className="flex h-9 shrink-0 items-center gap-1 px-1.5">
+ <InputGroup className="h-7 min-w-0 flex-1 bg-background">
+ <InputGroupAddon align="inline-start"><Search /></InputGroupAddon>
+ <InputGroupInput
+ aria-label="Filter files"
+ placeholder="Filter files"
+ value={search.value}
+ onChange={(event) => {
+ const value = event.target.value;
+ if (value.trim()) search.setValue(value);
+ else search.close();
+ }}
+ />
+ </InputGroup>
+ <Button variant="ghost" size="icon-xs" aria-label="Refresh files" onClick={props.onRefresh}>
+ <RefreshCw className={cn(props.loading && "animate-spin")} />
+ </Button>
+ </div>
+ {props.error ? (
+ <p className="p-3 text-xs text-destructive">Could not list this folder.</p>
+ ) : (
+ <FileTree
+ model={model}
+ aria-label="Project files"
+ className="min-h-0 flex-1 overflow-hidden"
+ style={{ ["--trees-fg-override" as string]: "var(--foreground)" }}
+ />
+ )}
+ {props.truncated ? (
+ <p className="border-t border-border px-2 py-1 text-[10px] text-muted-foreground">Showing the first 200,000 files.</p>
+ ) : null}
+ </div>
+ );
+}
+
+function ChangesView(props: {
+ data: ReviewData | undefined;
+ loading: boolean;
+ error: string | null;
+ scope: ReviewScope;
+ available: boolean;
+ pending: (file: ReviewFile) => boolean;
+ selected: string | null;
+ onScope: (scope: ReviewScope) => void;
+ onOpen: (file: ReviewFile) => void;
+ onAcceptAll: (files: ReviewFile[]) => void;
+ onRejectAll: (files: ReviewFile[]) => void;
+ onRefresh: () => void;
+}) {
+ const files = props.data?.files ?? [];
+ const pending = files.filter((file) => file.baseline !== undefined && props.pending(file));
+ return (
+ <div className="flex h-full min-h-0 flex-col text-xs" data-editor-changes={files.length}>
+ <div className="flex h-9 shrink-0 items-center gap-1 px-2">
+ <div className="flex rounded-lg bg-muted p-0.5">
+ {(["turn", "chat"] as const).map((scope) => (
+ <button
+ key={scope}
+ type="button"
+ onClick={() => props.onScope(scope)}
+ className={cn("rounded-md px-2 py-0.5", props.scope === scope ? "bg-background text-foreground shadow-sm" : "text-muted-foreground")}
+ >
+ {scope === "turn" ? "Last turn" : "Whole chat"}
+ </button>
+ ))}
+ </div>
+ <span className="flex-1" />
+ <Button variant="ghost" size="icon-xs" aria-label="Refresh changes" onClick={props.onRefresh}>
+ <RefreshCw className={cn(props.loading && "animate-spin")} />
+ </Button>
+ </div>
+ {!props.available ? (
+ <p className="px-3 py-2 text-muted-foreground">Open a chat to review the agent's changes.</p>
+ ) : props.error ? (
+ <p className="px-3 py-2 text-destructive">{props.error}</p>
+ ) : props.loading && !props.data ? (
+ <p className="px-3 py-2 text-muted-foreground">Loading changes…</p>
+ ) : files.length === 0 ? (
+ <p className="px-3 py-2 text-muted-foreground">The agent has not changed any files in this chat yet.</p>
+ ) : (
+ <>
+ <div className="min-h-0 flex-1 overflow-y-auto px-1">
+ {files.map((file) => {
+ const isPending = file.baseline !== undefined && props.pending(file);
+ return (
+ <button
+ key={file.path}
+ type="button"
+ onClick={() => props.onOpen(file)}
+ data-editor-change={file.path}
+ className={cn(
+ "flex w-full items-center gap-2 rounded-md px-2 py-1 text-start hover:bg-muted",
+ props.selected === file.path && "bg-muted",
+ )}
+ title={file.baseline === undefined ? "Changed again since the agent's turn: shown without a review diff" : file.path}
+ >
+ {isPending ? <CircleDot className="size-3 shrink-0 text-primary" /> : <Check className="size-3 shrink-0 text-muted-foreground" />}
+ <span className={cn("min-w-0 flex-1 truncate", !isPending && "text-muted-foreground")}>
+ {file.path.split("/").pop()}
+ <span className="ms-1.5 text-[10.5px] text-muted-foreground">{file.path.includes("/") ? file.path.slice(0, file.path.lastIndexOf("/")) : ""}</span>
+ </span>
+ <span className="shrink-0 font-mono text-[10.5px] text-emerald-600 dark:text-emerald-400">+{file.additions}</span>
+ <span className="shrink-0 font-mono text-[10.5px] text-red-600 dark:text-red-400">−{file.deletions}</span>
+ </button>
+ );
+ })}
+ </div>
+ <div className="flex shrink-0 items-center gap-1.5 border-t border-border p-2">
+ <span className="min-w-0 flex-1 truncate whitespace-nowrap text-muted-foreground">{pending.length ? `${pending.length} left` : "Done"}</span>
+ <Button size="xs" disabled={pending.length === 0} onClick={() => props.onAcceptAll(pending)}>Accept all</Button>
+ <Button size="xs" variant="outline" disabled={pending.length === 0} onClick={() => props.onRejectAll(pending)}>Reject all</Button>
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
+
+function GitView(props: {
+ status: OmniRushEditorGitStatus | undefined;
+ loading: boolean;
+ error: string | null;
+ busy: boolean;
+ selected: string | null;
+ onOpen: (file: OmniRushEditorGitFile, staged: boolean) => void;
+ onStage: (paths: string[], stage: boolean) => void;
+ onCommit: (message: string) => Promise<boolean>;
+ onRefresh: () => void;
+}) {
+ const [message, setMessage] = useState("");
+ const status = props.status;
+ const staged = status?.files.filter((file) => file.index !== " " && file.index !== "?") ?? [];
+ const unstaged = status?.files.filter((file) => file.worktree !== " ") ?? [];
+ const commit = async () => {
+ if (!message.trim() || staged.length === 0) return;
+ if (await props.onCommit(message)) setMessage("");
+ };
+ const row = (file: OmniRushEditorGitFile, isStaged: boolean) => (
+ <div
+ key={`${isStaged ? "s" : "u"}:${file.path}`}
+ className={cn("group flex items-center gap-1.5 rounded-md px-2 py-0.5 hover:bg-muted", props.selected === file.path && "bg-muted")}
+ data-editor-git-file={file.path}
+ data-editor-git-staged={isStaged ? "1" : "0"}
+ >
+ <button type="button" className="flex min-w-0 flex-1 items-center gap-1.5 text-start" onClick={() => props.onOpen(file, isStaged)}>
+ <span className="min-w-0 truncate">{file.path.split("/").pop()}</span>
+ <span className="min-w-0 truncate text-[10.5px] text-muted-foreground">{file.path.includes("/") ? file.path.slice(0, file.path.lastIndexOf("/")) : ""}</span>
+ </button>
+ <Tooltip>
+ <TooltipTrigger
+ render={(
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ className="opacity-60 group-hover:opacity-100"
+ aria-label={isStaged ? `Unstage ${file.path}` : `Stage ${file.path}`}
+ disabled={props.busy}
+ onClick={() => props.onStage([file.path], !isStaged)}
+ >
+ {isStaged ? <Minus /> : <Plus />}
+ </Button>
+ )}
+ />
+ <TooltipContent>{isStaged ? "Unstage" : "Stage"}</TooltipContent>
+ </Tooltip>
+ <span className={cn(
+ "w-3 shrink-0 text-center font-mono text-[10.5px]",
+ gitBadge(file, isStaged) === "U" || gitBadge(file, isStaged) === "A" ? "text-emerald-600 dark:text-emerald-400" : gitBadge(file, isStaged) === "D" ? "text-red-600 dark:text-red-400" : "text-amber-600 dark:text-amber-400",
+ )}>
+ {gitBadge(file, isStaged)}
+ </span>
+ </div>
+ );
+ if (props.error) return <p className="p-3 text-xs text-destructive">{props.error}</p>;
+ if (!status) return <p className="p-3 text-xs text-muted-foreground">{props.loading ? "Reading git status…" : ""}</p>;
+ if (!status.repo) return <p className="p-3 text-xs text-muted-foreground">This folder is not a git repository.</p>;
+ return (
+ <div className="flex h-full min-h-0 flex-col text-xs" data-editor-git>
+ <div className="flex h-9 shrink-0 items-center gap-1.5 px-2">
+ <GitBranch className="size-3.5 text-muted-foreground" />
+ <span className="min-w-0 flex-1 truncate font-medium" data-editor-branch>{status.branch ?? "detached HEAD"}</span>
+ {status.ahead || status.behind ? <span className="text-muted-foreground">↑{status.ahead} ↓{status.behind}</span> : null}
+ <Button variant="ghost" size="icon-xs" aria-label="Refresh git status" onClick={props.onRefresh}>
+ <RefreshCw className={cn(props.loading && "animate-spin")} />
+ </Button>
+ </div>
+ <div className="flex shrink-0 flex-col gap-1.5 px-2 pb-2">
+ <textarea
+ value={message}
+ onChange={(event) => setMessage(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
+ event.preventDefault();
+ void commit();
+ }
+ }}
+ placeholder={staged.length ? "Commit message (Cmd/Ctrl+Enter)" : "Stage changes to commit"}
+ aria-label="Commit message"
+ rows={2}
+ className="w-full resize-none rounded-lg border border-border bg-background px-2 py-1.5 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ />
+ <Button size="xs" disabled={props.busy || staged.length === 0 || !message.trim()} onClick={() => void commit()}>
+ <GitCommitHorizontal /> Commit {staged.length ? `${staged.length} file${staged.length === 1 ? "" : "s"}` : ""}
+ </Button>
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto px-1 pb-2">
+ <div className="flex items-center px-2 pt-1 pb-0.5 text-[10.5px] font-medium uppercase tracking-wide text-muted-foreground">
+ <span className="flex-1">Staged ({staged.length})</span>
+ {staged.length ? <button type="button" className="hover:text-foreground" onClick={() => props.onStage(staged.map((file) => file.path), false)}>Unstage all</button> : null}
+ </div>
+ {staged.map((file) => row(file, true))}
+ <div className="flex items-center px-2 pt-2 pb-0.5 text-[10.5px] font-medium uppercase tracking-wide text-muted-foreground">
+ <span className="flex-1">Changes ({unstaged.length})</span>
+ {unstaged.length ? <button type="button" className="hover:text-foreground" onClick={() => props.onStage(unstaged.map((file) => file.path), true)}>Stage all</button> : null}
+ </div>
+ {unstaged.map((file) => row(file, false))}
+ {staged.length === 0 && unstaged.length === 0 ? <p className="px-2 py-1 text-muted-foreground">No changes.</p> : null}
+ </div>
+ </div>
+ );
+}
+
+export default function EditorPanel(props: EditorPanelProps) {
+ const { client, workspaceId, workspaceRoot, sessionId, sessionBusy, opencodeClient } = props;
+ const monaco = useMemo<Monaco>(() => setupMonaco(), []);
+ const docs = useMemo(() => editorDocuments(monaco, client, workspaceId), [monaco, client, workspaceId]);
+ const queryClient = useQueryClient();
+ const state = useEditorStore((store) => editorWorkspaceState(store, workspaceId));
+ const dirty = useEditorStore((store) => store.dirty[workspaceId]);
+ const quickOpen = useEditorStore((store) => store.quickOpen);
+ const reviewScope = useEditorStore((store) => store.reviewScope);
+ const sideOpen = useEditorStore((store) => store.sideOpen);
+ const activeTab = state.tabs.find((tab) => tab.id === state.activeId) ?? null;
+ const [surface, setSurface] = useState<SurfaceDoc | null>(null);
+ const [tabError, setTabError] = useState<string | null>(null);
+ const [cursor, setCursor] = useState<{ line: number; column: number } | null>(null);
+ const [hunks, setHunks] = useState<LineHunk[]>([]);
+ const [navigate, setNavigate] = useState<{ direction: 1 | -1; nonce: number } | null>(null);
+ const [gitBusy, setGitBusy] = useState(false);
+ const [reviewTick, setReviewTick] = useState(0);
+ const recentRef = useRef<string[]>([]);
+
+ // ── data ───────────────────────────────────────────────────────────────
+ const treeQuery = useQuery({
+ queryKey: ["editor-tree", workspaceId] as const,
+ queryFn: () => client.editorTree(workspaceId),
+ staleTime: 15_000,
+ refetchOnWindowFocus: true,
+ });
+ const gitQuery = useQuery({
+ queryKey: ["editor-git", workspaceId] as const,
+ queryFn: () => client.editorGitStatus(workspaceId),
+ staleTime: 3_000,
+ refetchOnWindowFocus: true,
+ refetchInterval: state.view === "git" ? 10_000 : false,
+ });
+ const changesQuery = useQuery({
+ queryKey: ["editor-changes", workspaceId, sessionId, reviewScope] as const,
+ queryFn: () => loadAgentChanges({ opencodeClient: opencodeClient!, sessionId: sessionId!, directory: workspaceRoot, scope: reviewScope, docs, workspaceRoot }),
+ enabled: Boolean(opencodeClient && sessionId && !sessionBusy),
+ staleTime: Infinity,
+ refetchOnWindowFocus: false,
+ });
+ const review = changesQuery.data;
+ const reviewFiles = review?.files ?? [];
+ const files = treeQuery.data?.files ?? EMPTY_FILES;
+
+ // A turn ended: the agent may have changed files.
+ const wasBusy = useRef(sessionBusy);
+ useEffect(() => {
+ if (wasBusy.current && !sessionBusy) {
+ void docs.refresh();
+ void queryClient.invalidateQueries({ queryKey: ["editor-tree", workspaceId] });
+ void queryClient.invalidateQueries({ queryKey: ["editor-git", workspaceId] });
+ void queryClient.invalidateQueries({ queryKey: ["editor-changes", workspaceId] });
+ }
+ wasBusy.current = sessionBusy;
+ }, [docs, queryClient, sessionBusy, workspaceId]);
+
+ // Back in the window: files may have changed outside the app.
+ useEffect(() => {
+ const onFocus = () => void docs.refresh();
+ window.addEventListener("focus", onFocus);
+ return () => window.removeEventListener("focus", onFocus);
+ }, [docs]);
+
+ // ── review state ───────────────────────────────────────────────────────
+ const reviewKey = review?.key ?? null;
+ const baselineModel = useCallback((file: ReviewFile) => {
+ // Created once per review (key + path): accepting a hunk edits it, and a refetch must not undo that.
+ const uri = docs.uri(`review/${reviewKey}/${file.path}`, "omnirush-base");
+ const existing = monaco.editor.getModel(uri);
+ if (existing) return existing;
+ // A file fully reviewed before a restart stays reviewed while its text is the one that was reviewed.
+ const current = docs.get(file.path)?.model.getValue() ?? null;
+ const reviewed = current !== null && reviewKey !== null && isReviewed(reviewKey, file.path, current);
+ return monaco.editor.createModel(reviewed ? current : file.baseline ?? "", languageForPath(file.path), uri);
+ }, [docs, monaco, reviewKey]);
+ const modifiedFor = useCallback((file: ReviewFile): FileDoc => {
+ return docs.get(file.path) ?? docs.openMissing(file.path);
+ }, [docs]);
+ const isPending = useCallback((file: ReviewFile) => {
+ if (file.baseline === undefined) return false;
+ const base = baselineModel(file).getValue();
+ const now = docs.get(file.path)?.model.getValue() ?? "";
+ return base !== now;
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [baselineModel, docs, reviewTick]);
+
+ // Remembers files whose review is finished (before === now), so a restart does not ask again.
+ useEffect(() => {
+ if (!reviewKey) return;
+ for (const file of reviewFiles) {
+ if (file.baseline === undefined) continue;
+ const uri = docs.uri(`review/${reviewKey}/${file.path}`, "omnirush-base");
+ const base = monaco.editor.getModel(uri)?.getValue();
+ const now = docs.get(file.path)?.model.getValue();
+ if (base !== undefined && now !== undefined && base === now) markReviewed(reviewKey, file.path, now);
+ }
+ }, [docs, monaco, reviewFiles, reviewKey, reviewTick]);
+
+ const reportReview = useCallback((path: string, decision: "accept" | "reject", counts: { added: number; removed: number }, scope: "hunk" | "file") => {
+ if (!sessionId) return;
+ void client.editorReview(workspaceId, { sessionId, path, decision, scope, ...counts }).catch(() => undefined);
+ }, [client, sessionId, workspaceId]);
+
+ const writeReviewed = useCallback(async (file: ReviewFile, doc: FileDoc) => {
+ // A file the agent created that is empty after rejecting goes away again.
+ const result = file.baseline === null && doc.model.getValue() === ""
+ ? await docs.remove(file.path, { sessionId, source: "review" })
+ : await docs.save(file.path, { sessionId, source: "review" });
+ if (!result.ok) toast.error(result.message);
+ void queryClient.invalidateQueries({ queryKey: ["editor-git", workspaceId] });
+ void queryClient.invalidateQueries({ queryKey: ["editor-tree", workspaceId] });
+ }, [docs, queryClient, sessionId, workspaceId]);
+
+ const setLines = (model: import("monaco-editor/editor/editor.api.js").editor.ITextModel, lines: string[], undoable: boolean) => {
+ const text = lines.join(model.getEOL());
+ if (undoable) model.pushEditOperations([], [{ range: model.getFullModelRange(), text }], () => null);
+ else model.setValue(text);
+ };
+
+ const acceptOne = useCallback((file: ReviewFile, hunk: LineHunk) => {
+ const base = baselineModel(file);
+ const doc = modifiedFor(file);
+ setLines(base, acceptHunk(base.getLinesContent(), doc.model.getLinesContent(), hunk), false);
+ reportReview(file.path, "accept", hunkCounts(hunk), "hunk");
+ setReviewTick((value) => value + 1);
+ }, [baselineModel, modifiedFor, reportReview]);
+
+ const rejectOne = useCallback((file: ReviewFile, hunk: LineHunk) => {
+ const base = baselineModel(file);
+ const doc = modifiedFor(file);
+ setLines(doc.model, rejectHunk(base.getLinesContent(), doc.model.getLinesContent(), hunk), true);
+ reportReview(file.path, "reject", hunkCounts(hunk), "hunk");
+ setReviewTick((value) => value + 1);
+ void writeReviewed(file, doc);
+ }, [baselineModel, modifiedFor, reportReview, writeReviewed]);
+
+ const acceptFiles = useCallback((list: ReviewFile[]) => {
+ for (const file of list) {
+ const base = baselineModel(file);
+ base.setValue(modifiedFor(file).model.getValue());
+ reportReview(file.path, "accept", { added: file.additions, removed: file.deletions }, "file");
+ }
+ setReviewTick((value) => value + 1);
+ }, [baselineModel, modifiedFor, reportReview]);
+
+ const rejectFiles = useCallback(async (list: ReviewFile[]) => {
+ for (const file of list) {
+ const doc = modifiedFor(file);
+ doc.model.pushEditOperations([], [{ range: doc.model.getFullModelRange(), text: baselineModel(file).getValue() }], () => null);
+ reportReview(file.path, "reject", { added: file.additions, removed: file.deletions }, "file");
+ await writeReviewed(file, doc);
+ }
+ setReviewTick((value) => value + 1);
+ }, [baselineModel, modifiedFor, reportReview, writeReviewed]);
+
+ // ── tabs ───────────────────────────────────────────────────────────────
+ const openFile = useCallback((path: string) => {
+ useEditorStore.getState().openTab(workspaceId, { id: tabId({ kind: "file", path }), kind: "file", path });
+ recentRef.current = [path, ...recentRef.current.filter((item) => item !== path)].slice(0, 30);
+ }, [workspaceId]);
+ const openReview = useCallback((file: ReviewFile) => {
+ if (file.baseline === undefined) {
+ openFile(file.path);
+ return;
+ }
+ useEditorStore.getState().openTab(workspaceId, { id: tabId({ kind: "review", path: file.path }), kind: "review", path: file.path });
+ }, [openFile, workspaceId]);
+ const openGit = useCallback((file: OmniRushEditorGitFile, staged: boolean) => {
+ const ref = staged ? "HEAD" : "index";
+ useEditorStore.getState().openTab(workspaceId, { id: tabId({ kind: "git", path: file.path, ref }), kind: "git", path: file.path, ref });
+ }, [workspaceId]);
+
+ const closeTab = useCallback((tab: EditorTab) => {
+ const doc = tab.kind === "file" ? docs.get(tab.path) : null;
+ if (doc && docs.isDirty(doc) && !window.confirm(`${tab.path} has unsaved changes. Close it anyway? The changes stay until you reopen the file.`)) return;
+ useEditorStore.getState().closeTab(workspaceId, tab.id);
+ }, [docs, workspaceId]);
+
+ // The active tab's document.
+ useEffect(() => {
+ let cancelled = false;
+ setTabError(null);
+ if (!activeTab) {
+ setSurface(null);
+ return;
+ }
+ const key = `${activeTab.id}`;
+ void (async () => {
+ if (activeTab.kind === "file") {
+ const opened = await docs.open(activeTab.path);
+ if (cancelled) return;
+ if (!opened.ok) {
+ setSurface(null);
+ setTabError(opened.message);
+ return;
+ }
+ setSurface({ kind: "file", key, doc: opened.doc });
+ return;
+ }
+ if (activeTab.kind === "review") {
+ const file = reviewFiles.find((item) => item.path === activeTab.path);
+ if (!file || file.baseline === undefined) {
+ if (!changesQuery.isFetching && review) {
+ setSurface(null);
+ setTabError("This change is no longer in the review. Open the file from the Files view.");
+ }
+ return;
+ }
+ const opened = file.status === "deleted" ? null : await docs.open(file.path);
+ if (cancelled) return;
+ const doc = opened && opened.ok ? opened.doc : docs.openMissing(file.path);
+ setSurface({
+ kind: "diff",
+ key: `${key}:${reviewKey}`,
+ original: baselineModel(file),
+ modified: doc.model,
+ review: { onAccept: (hunk) => acceptOne(file, hunk), onReject: (hunk) => rejectOne(file, hunk) },
+ });
+ return;
+ }
+ // Git: the file against HEAD (staged view) or the index (working-tree view).
+ const [original, opened] = await Promise.all([
+ client.editorGitOriginal(workspaceId, activeTab.path, activeTab.ref).catch(() => null),
+ docs.open(activeTab.path),
+ ]);
+ if (cancelled) return;
+ if (original?.binary || original?.tooLarge) {
+ setSurface(null);
+ setTabError("This file cannot be shown as a text diff.");
+ return;
+ }
+ const base = docs.baseline(`git-${activeTab.ref}`, activeTab.path, original?.content ?? "");
+ const doc = opened.ok ? opened.doc : docs.openMissing(activeTab.path);
+ setSurface({ kind: "diff", key, original: base, modified: doc.model });
+ })();
+ return () => {
+ cancelled = true;
+ };
+ // reviewFiles changes identity per fetch; the key carries what matters.
+ }, [activeTab, docs, client, workspaceId, reviewKey, changesQuery.isFetching]);
+
+ // ── save ───────────────────────────────────────────────────────────────
+ const save = useCallback(async (options: { force?: boolean } = {}) => {
+ if (!activeTab) return;
+ const path = activeTab.path;
+ const doc = docs.get(path);
+ if (!doc) return;
+ const result = await docs.save(path, { sessionId, source: "editor", force: options.force });
+ if (result.ok) {
+ void queryClient.invalidateQueries({ queryKey: ["editor-git", workspaceId] });
+ if (!files.includes(path)) void queryClient.invalidateQueries({ queryKey: ["editor-tree", workspaceId] });
+ return;
+ }
+ if (result.conflict) {
+ toast.error(`${path} changed on disk since you opened it.`, {
+ id: `editor-conflict:${path}`,
+ duration: 20_000,
+ action: { label: "Overwrite", onClick: () => void save({ force: true }) },
+ cancel: { label: "Reload", onClick: () => void docs.revert(path) },
+ });
+ return;
+ }
+ toast.error(result.message);
+ }, [activeTab, docs, files, queryClient, sessionId, workspaceId]);
+
+ // ── git ────────────────────────────────────────────────────────────────
+ const stage = useCallback(async (paths: string[], doStage: boolean) => {
+ setGitBusy(true);
+ try {
+ const status = await client.editorGitStage(workspaceId, paths, doStage);
+ queryClient.setQueryData(["editor-git", workspaceId], status);
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : "Git failed.");
+ } finally {
+ setGitBusy(false);
+ }
+ }, [client, queryClient, workspaceId]);
+ const commit = useCallback(async (message: string) => {
+ setGitBusy(true);
+ try {
+ const result = await client.editorGitCommit(workspaceId, message);
+ queryClient.setQueryData(["editor-git", workspaceId], result.status);
+ toast.success(`Committed ${result.commit}`);
+ return true;
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : "Commit failed.");
+ return false;
+ } finally {
+ setGitBusy(false);
+ }
+ }, [client, queryClient, workspaceId]);
+
+ // ── keys ───────────────────────────────────────────────────────────────
+ const panelRef = useRef<HTMLDivElement | null>(null);
+ useEffect(() => {
+ const onKey = (event: KeyboardEvent) => {
+ const mod = /Mac/i.test(navigator.platform) ? event.metaKey : event.ctrlKey;
+ if (!mod || event.altKey) return;
+ const key = event.key.toLowerCase();
+ // Cmd/Ctrl+S outside Monaco (tab strip, tree) still saves the active file.
+ if (key === "s" && !event.shiftKey && panelRef.current?.contains(document.activeElement)) {
+ event.preventDefault();
+ void save();
+ }
+ };
+ window.addEventListener("keydown", onKey, true);
+ return () => window.removeEventListener("keydown", onKey, true);
+ }, [save]);
+
+ const activePath = activeTab?.path ?? null;
+ const activeDirty = activeTab && dirty?.[activeTab.path];
+ const activeDoc = activePath ? docs.get(activePath) : null;
+ const pendingCount = reviewFiles.filter((file) => isPending(file)).length;
+ const branch = gitQuery.data?.repo ? gitQuery.data.branch : null;
+ const setView = (view: EditorSideView) => {
+ if (state.view === view && sideOpen) useEditorStore.getState().setSideOpen(false);
+ else useEditorStore.getState().setView(workspaceId, view);
+ };
+
+ const side = (
+ <div className="flex h-full min-h-0 flex-col border-e border-border bg-muted/20">
+ {state.view === "files" ? (
+ <FilesView
+ files={files}
+ truncated={Boolean(treeQuery.data?.truncated)}
+ git={gitQuery.data}
+ selected={activePath}
+ loading={treeQuery.isFetching}
+ error={treeQuery.isError}
+ onOpen={openFile}
+ onRefresh={() => void treeQuery.refetch()}
+ />
+ ) : state.view === "changes" ? (
+ <ChangesView
+ data={review}
+ loading={changesQuery.isFetching}
+ error={changesQuery.isError ? (changesQuery.error instanceof Error ? changesQuery.error.message : "Could not load the agent's changes.") : null}
+ scope={reviewScope}
+ available={Boolean(opencodeClient && sessionId)}
+ pending={isPending}
+ selected={activeTab?.kind === "review" ? activeTab.path : null}
+ onScope={(scope) => useEditorStore.getState().setReviewScope(scope)}
+ onOpen={openReview}
+ onAcceptAll={acceptFiles}
+ onRejectAll={(list) => void rejectFiles(list)}
+ onRefresh={() => void changesQuery.refetch()}
+ />
+ ) : (
+ <GitView
+ status={gitQuery.data}
+ loading={gitQuery.isFetching}
+ error={gitQuery.isError ? (gitQuery.error instanceof Error ? gitQuery.error.message : "Could not read git status.") : null}
+ busy={gitBusy}
+ selected={activeTab?.kind === "git" ? activeTab.path : null}
+ onOpen={openGit}
+ onStage={(paths, doStage) => void stage(paths, doStage)}
+ onCommit={commit}
+ onRefresh={() => void gitQuery.refetch()}
+ />
+ )}
+ </div>
+ );
+
+ const main = (
+ <div className="flex h-full min-h-0 min-w-0 flex-col">
+ <div className="flex h-8 shrink-0 items-stretch overflow-x-auto border-b border-border [scrollbar-width:none]" role="tablist" data-editor-tabs>
+ {state.tabs.map((tab) => {
+ const active = tab.id === state.activeId;
+ const name = tab.path.split("/").pop() ?? tab.path;
+ const isDirty = tab.kind === "file" && dirty?.[tab.path];
+ return (
+ <div
+ key={tab.id}
+ role="tab"
+ aria-selected={active}
+ title={tab.path}
+ data-editor-tab={tab.id}
+ onMouseDown={(event) => {
+ if (event.button === 1) {
+ event.preventDefault();
+ closeTab(tab);
+ }
+ }}
+ className={cn(
+ "group flex max-w-48 shrink-0 cursor-pointer items-center gap-1.5 border-e border-border ps-3 pe-1.5 text-xs",
+ active ? "bg-background text-foreground shadow-[inset_0_-2px_0_var(--primary)]" : "text-muted-foreground hover:text-foreground",
+ )}
+ onClick={() => useEditorStore.getState().selectTab(workspaceId, tab.id)}
+ >
+ {tab.kind === "review" ? <CircleDot className="size-3 shrink-0 text-primary" /> : tab.kind === "git" ? <GitBranch className="size-3 shrink-0" /> : null}
+ <span className="truncate">{name}{tab.kind === "git" ? ` (${tab.ref === "HEAD" ? "staged" : "working"})` : ""}</span>
+ <button
+ type="button"
+ aria-label={`Close ${name}`}
+ onClick={(event) => {
+ event.stopPropagation();
+ closeTab(tab);
+ }}
+ className="flex size-4 items-center justify-center rounded hover:bg-muted"
+ >
+ {isDirty ? <span className="size-2 rounded-full bg-foreground group-hover:hidden" /> : null}
+ <X className={cn("size-3", isDirty && "hidden group-hover:block")} />
+ </button>
+ </div>
+ );
+ })}
+ </div>
+ {activeTab?.kind === "review" ? (
+ <div className="flex h-8 shrink-0 items-center gap-2 overflow-hidden whitespace-nowrap border-b border-border bg-primary/5 px-3 text-xs" data-editor-review-bar>
+ <span className="min-w-0 truncate font-medium">{hunks.length ? `${hunks.length} to review` : "All reviewed"}</span>
+ <span className="flex-1" />
+ <Button variant="ghost" size="xs" disabled={!hunks.length} onClick={() => setNavigate({ direction: -1, nonce: Date.now() })}><ChevronUp /> Prev</Button>
+ <Button variant="ghost" size="xs" disabled={!hunks.length} onClick={() => setNavigate({ direction: 1, nonce: Date.now() })}><ChevronDown /> Next</Button>
+ </div>
+ ) : activePath ? (
+ <div className="flex h-6 shrink-0 items-center gap-1 border-b border-border px-3 text-[11px] text-muted-foreground" data-editor-breadcrumb>
+ {activePath.split("/").map((part, index, parts) => (
+ <span key={`${index}:${part}`} className={cn(index === parts.length - 1 && "text-foreground")}>
+ {part}{index < parts.length - 1 ? <span className="mx-1 opacity-60">›</span> : null}
+ </span>
+ ))}
+ {activeDoc?.conflict ? (
+ <button type="button" className="ms-auto flex items-center gap-1 text-amber-600 hover:underline dark:text-amber-400" onClick={() => void docs.revert(activePath)}>
+ <Undo2 className="size-3" /> Changed on disk: reload
+ </button>
+ ) : null}
+ </div>
+ ) : null}
+ {tabError ? (
+ <div className="flex min-h-0 flex-1 items-center justify-center p-6 text-center text-sm text-muted-foreground">{tabError}</div>
+ ) : null}
+ <div className={cn("flex min-h-0 flex-1 flex-col", tabError && "hidden")}>
+ {state.tabs.length === 0 ? (
+ <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-2 p-6 text-center text-sm text-muted-foreground" data-editor-empty>
+ <FileCode2 className="size-8 opacity-40" />
+ <p>Open a file from the tree, or press <kbd className="rounded border border-border px-1 text-xs">{/Mac/i.test(navigator.platform) ? "⌘" : "Ctrl"} P</kbd> to find one.</p>
+ {pendingCount ? (
+ <Button size="sm" variant="outline" onClick={() => useEditorStore.getState().setView(workspaceId, "changes")}>Review {pendingCount} changed file{pendingCount === 1 ? "" : "s"}</Button>
+ ) : null}
+ </div>
+ ) : null}
+ <div className={cn("flex min-h-0 flex-1", state.tabs.length === 0 && "hidden")}>
+ <EditorSurface
+ monaco={monaco}
+ surface={surface}
+ onSave={() => void save()}
+ onCursor={setCursor}
+ onHunks={setHunks}
+ navigate={navigate}
+ />
+ </div>
+ </div>
+ <div className="flex h-6 shrink-0 items-center gap-3 overflow-hidden whitespace-nowrap border-t border-border px-3 text-[11px] text-muted-foreground" data-editor-status>
+ {branch ? <span className="flex items-center gap-1"><GitBranch className="size-3" />{branch}</span> : null}
+ {gitQuery.data?.repo ? <span>{gitQuery.data.files.length} changed</span> : null}
+ <span className="flex-1" />
+ {cursor && activeTab ? <span>Ln {cursor.line}, Col {cursor.column}</span> : null}
+ {activePath ? <span>{languageForPath(activePath)}</span> : null}
+ {activeTab?.kind === "file" ? <span data-editor-saved={activeDirty ? "0" : "1"}>{activeDirty ? "Unsaved" : "Saved"}</span> : null}
+ </div>
+ </div>
+ );
+
+ const segment = (view: EditorSideView, label: string, badge?: number) => (
+ <button
+ type="button"
+ onClick={() => setView(view)}
+ data-editor-view={view}
+ aria-pressed={state.view === view && sideOpen}
+ className={cn(
+ "flex items-center gap-1 rounded-lg px-2.5 py-1 text-xs transition-colors",
+ state.view === view && sideOpen ? "bg-muted text-foreground" : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ {label}
+ {badge ? <span className="rounded-full bg-primary px-1.5 text-[10px] leading-4 text-primary-foreground">{badge}</span> : null}
+ </button>
+ );
+
+ return (
+ <div ref={panelRef} className="relative flex h-full min-h-0 flex-col bg-background" data-editor-panel>
+ <div className="flex h-10 shrink-0 items-center gap-0.5 border-b border-border px-1.5">
+ <Tooltip>
+ <TooltipTrigger
+ render={(
+ <Button variant="ghost" size="icon-sm" aria-label={sideOpen ? "Hide side bar" : "Show side bar"} onClick={() => useEditorStore.getState().setSideOpen(!sideOpen)}>
+ {sideOpen ? <PanelLeftClose /> : <PanelLeftOpen />}
+ </Button>
+ )}
+ />
+ <TooltipContent>{sideOpen ? "Hide side bar" : "Show side bar"}</TooltipContent>
+ </Tooltip>
+ {segment("files", "Files")}
+ {segment("changes", "Changes", pendingCount)}
+ {segment("git", "Git", gitQuery.data?.repo ? gitQuery.data.files.length : undefined)}
+ <span className="flex-1" />
+ <Tooltip>
+ <TooltipTrigger
+ render={(
+ <Button variant="ghost" size="icon-sm" aria-label="Go to file" onClick={() => useEditorStore.getState().setQuickOpen(true)}>
+ <Search />
+ </Button>
+ )}
+ />
+ <TooltipContent>Go to file ({/Mac/i.test(navigator.platform) ? "⌘P" : "Ctrl+P"})</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger
+ render={(
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={props.terminalOpen ? "Hide terminal" : "Show terminal"}
+ aria-pressed={props.terminalOpen}
+ className={cn(props.terminalOpen && "bg-muted text-foreground")}
+ onClick={props.onToggleTerminal}
+ >
+ <SquareTerminal />
+ </Button>
+ )}
+ />
+ <TooltipContent>Terminal ({/Mac/i.test(navigator.platform) ? "⌘J" : "Ctrl+J"})</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger
+ render={(
+ <Button variant="ghost" size="icon-sm" aria-label="Close editor" onClick={props.onClose}>
+ <X />
+ </Button>
+ )}
+ />
+ <TooltipContent>Close editor</TooltipContent>
+ </Tooltip>
+ </div>
+ <ResizablePanelGroup orientation="vertical" className="min-h-0 flex-1">
+ <ResizablePanel minSize="160px" className="min-h-0">
+ <ResizablePanelGroup orientation="horizontal" className="h-full min-h-0">
+ {sideOpen ? (
+ <>
+ <ResizablePanel defaultSize="230px" minSize="160px" maxSize="50%" className="min-h-0">
+ {side}
+ </ResizablePanel>
+ <ResizableHandle />
+ </>
+ ) : null}
+ <ResizablePanel minSize="240px" className="min-h-0 min-w-0">
+ {main}
+ </ResizablePanel>
+ </ResizablePanelGroup>
+ </ResizablePanel>
+ {props.terminalOpen && props.terminal ? (
+ <>
+ <ResizableHandle />
+ <ResizablePanel defaultSize="220px" minSize="120px" maxSize="70%" className="min-h-0" data-editor-terminal>
+ {props.terminal}
+ </ResizablePanel>
+ </>
+ ) : null}
+ </ResizablePanelGroup>
+ {quickOpen ? (
+ <QuickOpen
+ files={files}
+ recent={recentRef.current}
+ onOpen={(path) => {
+ useEditorStore.getState().setQuickOpen(false);
+ openFile(path);
+ }}
+ onClose={() => useEditorStore.getState().setQuickOpen(false)}
+ />
+ ) : null}
+ </div>
+ );
+}
diff --git a/apps/app/src/react-app/domains/session/editor/editor-store.ts b/apps/app/src/react-app/domains/session/editor/editor-store.ts
new file mode 100644
index 00000000..87339e84
--- /dev/null
+++ b/apps/app/src/react-app/domains/session/editor/editor-store.ts
@@ -0,0 +1,123 @@
+import { create } from "zustand";
+import { createJSONStorage, persist } from "zustand/middleware";
+
+/**
+ * The desktop editor's open tabs and side view, per workspace. Tabs are
+ * remembered across restarts (paths only); file text lives in Monaco models
+ * (editor-panel.tsx) and is read again on open.
+ */
+export type EditorTab =
+ | { id: string; kind: "file"; path: string }
+ /** The agent's change to one file, for review (accept/reject per hunk). */
+ | { id: string; kind: "review"; path: string }
+ /** A file against git (HEAD or the index), from the git panel. */
+ | { id: string; kind: "git"; path: string; ref: "HEAD" | "index" };
+
+export type EditorSideView = "files" | "changes" | "git";
+export type ReviewScope = "turn" | "chat";
+
+type WorkspaceEditorState = {
+ tabs: EditorTab[];
+ activeId: string | null;
+ view: EditorSideView;
+};
+
+type EditorStore = {
+ byWorkspace: Record<string, WorkspaceEditorState>;
+ /** Paths with unsaved changes, per workspace (not persisted). */
+ dirty: Record<string, Record<string, true>>;
+ quickOpen: boolean;
+ /** One-shot request to show the editor (Cmd/Ctrl+P while it is closed). */
+ showRequest: number;
+ /** One-shot request to toggle the editor (Cmd/Ctrl+Shift+E). */
+ toggleRequest: number;
+ reviewScope: ReviewScope;
+ sideOpen: boolean;
+ openTab: (workspaceId: string, tab: EditorTab, options?: { preview?: boolean }) => void;
+ closeTab: (workspaceId: string, id: string) => void;
+ selectTab: (workspaceId: string, id: string) => void;
+ setView: (workspaceId: string, view: EditorSideView) => void;
+ setDirty: (workspaceId: string, path: string, dirty: boolean) => void;
+ setQuickOpen: (open: boolean) => void;
+ requestShow: () => void;
+ requestToggle: () => void;
+ setReviewScope: (scope: ReviewScope) => void;
+ setSideOpen: (open: boolean) => void;
+};
+
+const EMPTY: WorkspaceEditorState = { tabs: [], activeId: null, view: "files" };
+const MAX_TABS = 20;
+
+export function tabId(tab: { kind: EditorTab["kind"]; path: string; ref?: "HEAD" | "index" }): string {
+ return tab.kind === "git" ? `git:${tab.ref ?? "HEAD"}:${tab.path}` : `${tab.kind}:${tab.path}`;
+}
+
+export function editorWorkspaceState(state: EditorStore, workspaceId: string): WorkspaceEditorState {
+ return state.byWorkspace[workspaceId] ?? EMPTY;
+}
+
+export const useEditorStore = create<EditorStore>()(
+ persist(
+ (set) => ({
+ byWorkspace: {},
+ dirty: {},
+ quickOpen: false,
+ showRequest: 0,
+ toggleRequest: 0,
+ reviewScope: "turn",
+ sideOpen: true,
+ openTab: (workspaceId, tab) =>
+ set((state) => {
+ const current = state.byWorkspace[workspaceId] ?? EMPTY;
+ const exists = current.tabs.some((item) => item.id === tab.id);
+ let tabs = exists ? current.tabs : [...current.tabs, tab];
+ if (tabs.length > MAX_TABS) {
+ // Drop the oldest tab that has no unsaved changes.
+ const dirty = state.dirty[workspaceId] ?? {};
+ const drop = tabs.find((item) => item.id !== tab.id && !(item.kind === "file" && dirty[item.path]));
+ if (drop) tabs = tabs.filter((item) => item !== drop);
+ }
+ return { byWorkspace: { ...state.byWorkspace, [workspaceId]: { ...current, tabs, activeId: tab.id } } };
+ }),
+ closeTab: (workspaceId, id) =>
+ set((state) => {
+ const current = state.byWorkspace[workspaceId] ?? EMPTY;
+ const index = current.tabs.findIndex((item) => item.id === id);
+ if (index < 0) return state;
+ const tabs = current.tabs.filter((item) => item.id !== id);
+ const activeId = current.activeId === id ? (tabs[Math.min(index, tabs.length - 1)]?.id ?? null) : current.activeId;
+ return { byWorkspace: { ...state.byWorkspace, [workspaceId]: { ...current, tabs, activeId } } };
+ }),
+ selectTab: (workspaceId, id) =>
+ set((state) => {
+ const current = state.byWorkspace[workspaceId] ?? EMPTY;
+ if (!current.tabs.some((item) => item.id === id) || current.activeId === id) return state;
+ return { byWorkspace: { ...state.byWorkspace, [workspaceId]: { ...current, activeId: id } } };
+ }),
+ setView: (workspaceId, view) =>
+ set((state) => {
+ const current = state.byWorkspace[workspaceId] ?? EMPTY;
+ return { byWorkspace: { ...state.byWorkspace, [workspaceId]: { ...current, view } }, sideOpen: true };
+ }),
+ setDirty: (workspaceId, path, dirty) =>
+ set((state) => {
+ const current = state.dirty[workspaceId] ?? {};
+ if (Boolean(current[path]) === dirty) return state;
+ const next = { ...current };
+ if (dirty) next[path] = true;
+ else delete next[path];
+ return { dirty: { ...state.dirty, [workspaceId]: next } };
+ }),
+ setQuickOpen: (quickOpen) => set({ quickOpen }),
+ requestShow: () => set((state) => ({ showRequest: state.showRequest + 1 })),
+ requestToggle: () => set((state) => ({ toggleRequest: state.toggleRequest + 1 })),
+ setReviewScope: (reviewScope) => set({ reviewScope }),
+ setSideOpen: (sideOpen) => set({ sideOpen }),
+ }),
+ {
+ name: "omnirush:editor:v1",
+ storage: createJSONStorage(() => localStorage),
+ partialize: (state) => ({ byWorkspace: state.byWorkspace, reviewScope: state.reviewScope, sideOpen: state.sideOpen }),
+ },
+ ),
+);
diff --git a/apps/app/src/react-app/domains/session/editor/editor-surface.tsx b/apps/app/src/react-app/domains/session/editor/editor-surface.tsx
new file mode 100644
index 00000000..c96f718c
--- /dev/null
+++ b/apps/app/src/react-app/domains/session/editor/editor-surface.tsx
@@ -0,0 +1,287 @@
+/** @jsxImportSource react */
+/**
+ * The editor's Monaco host: one code editor for file tabs and one diff
+ * editor for review and git tabs, created once and switched between
+ * documents (each tab keeps its scroll and cursor). In a review tab every
+ * hunk gets an Accept / Reject bar above it.
+ */
+import { useEffect, useRef, useState } from "react";
+import type * as MonacoApi from "monaco-editor/editor/editor.api.js";
+
+import { applyMonacoTheme, monacoThemeName, type Monaco } from "./monaco";
+import type { FileDoc } from "./editor-models";
+import { hunkCounts, type LineHunk } from "./hunk-ops";
+
+export type SurfaceDoc =
+ | { kind: "file"; key: string; doc: FileDoc }
+ | {
+ kind: "diff";
+ key: string;
+ original: MonacoApi.editor.ITextModel;
+ modified: MonacoApi.editor.ITextModel;
+ /** Review tabs: per-hunk decisions. Git tabs have none. */
+ review?: {
+ onAccept: (hunk: LineHunk) => void;
+ onReject: (hunk: LineHunk) => void;
+ };
+ readOnlyModified?: boolean;
+ };
+
+type EditorSurfaceProps = {
+ monaco: Monaco;
+ surface: SurfaceDoc | null;
+ onSave: () => void;
+ onCursor: (position: { line: number; column: number } | null) => void;
+ onHunks: (hunks: LineHunk[]) => void;
+ /** Bumped to jump to the next / previous hunk. */
+ navigate: { direction: 1 | -1; nonce: number } | null;
+};
+
+const BASE_OPTIONS: MonacoApi.editor.IStandaloneEditorConstructionOptions = {
+ automaticLayout: true,
+ fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",
+ fontSize: 12.5,
+ lineHeight: 19,
+ minimap: { enabled: false },
+ scrollBeyondLastLine: false,
+ renderLineHighlight: "line",
+ smoothScrolling: false,
+ padding: { top: 6, bottom: 6 },
+ stickyScroll: { enabled: true, maxLineCount: 3 },
+ // Large files stay responsive: no tokenisation past 20k chars per line, no word-based suggestions on huge files.
+ maxTokenizationLineLength: 20_000,
+ wordBasedSuggestions: "currentDocument",
+ fixedOverflowWidgets: true,
+};
+
+function hunkBar(
+ hunk: LineHunk,
+ index: number,
+ total: number,
+ review: NonNullable<Extract<SurfaceDoc, { kind: "diff" }>["review"]>,
+): HTMLElement {
+ const bar = document.createElement("div");
+ bar.className = "omnirush-hunk-bar";
+ bar.dataset.editorHunk = String(index);
+ const button = (text: string, primary: boolean, run: () => void) => {
+ const element = document.createElement("button");
+ element.type = "button";
+ element.textContent = text;
+ element.className = primary ? "omnirush-hunk-btn omnirush-hunk-btn-primary" : "omnirush-hunk-btn";
+ element.dataset.editorHunkAction = text.toLowerCase();
+ element.addEventListener("mousedown", (event) => event.stopPropagation());
+ element.addEventListener("click", (event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ run();
+ });
+ return element;
+ };
+ // Buttons first: they stay in view however narrow the panel or long the lines.
+ bar.appendChild(button("Accept", true, () => review.onAccept(hunk)));
+ bar.appendChild(button("Reject", false, () => review.onReject(hunk)));
+ const { added, removed } = hunkCounts(hunk);
+ const label = document.createElement("span");
+ label.className = "omnirush-hunk-label";
+ label.textContent = `Change ${index + 1} of ${total} · +${added} −${removed}`;
+ bar.appendChild(label);
+ return bar;
+}
+
+export function EditorSurface({ monaco, surface, onSave, onCursor, onHunks, navigate }: EditorSurfaceProps) {
+ const codeHostRef = useRef<HTMLDivElement | null>(null);
+ const diffHostRef = useRef<HTMLDivElement | null>(null);
+ const codeRef = useRef<MonacoApi.editor.IStandaloneCodeEditor | null>(null);
+ const diffRef = useRef<MonacoApi.editor.IStandaloneDiffEditor | null>(null);
+ const viewStates = useRef(new Map<string, MonacoApi.editor.ICodeEditorViewState | MonacoApi.editor.IDiffEditorViewState | null>());
+ const currentKey = useRef<string | null>(null);
+ const zoneIds = useRef<string[]>([]);
+ const overlays = useRef<MonacoApi.editor.IOverlayWidget[]>([]);
+ const hunksRef = useRef<LineHunk[]>([]);
+ const onSaveRef = useRef(onSave);
+ onSaveRef.current = onSave;
+ const onCursorRef = useRef(onCursor);
+ onCursorRef.current = onCursor;
+ const onHunksRef = useRef(onHunks);
+ onHunksRef.current = onHunks;
+ const [mode, setMode] = useState<"file" | "diff" | null>(null);
+
+ // The editors, once.
+ useEffect(() => {
+ if (!codeHostRef.current || !diffHostRef.current) return;
+ const code = monaco.editor.create(codeHostRef.current, { ...BASE_OPTIONS, model: null, theme: monacoThemeName() });
+ const diff = monaco.editor.createDiffEditor(diffHostRef.current, {
+ ...BASE_OPTIONS,
+ theme: monacoThemeName(),
+ renderSideBySide: false,
+ useInlineViewWhenSpaceIsLimited: true,
+ renderMarginRevertIcon: false,
+ renderOverviewRuler: false,
+ ignoreTrimWhitespace: false,
+ originalEditable: false,
+ hideUnchangedRegions: { enabled: false },
+ });
+ const save = () => onSaveRef.current();
+ code.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, save);
+ diff.getModifiedEditor().addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, save);
+ const cursor = (editor: MonacoApi.editor.ICodeEditor) => editor.onDidChangeCursorPosition((event) => {
+ onCursorRef.current({ line: event.position.lineNumber, column: event.position.column });
+ });
+ const disposables = [cursor(code), cursor(diff.getModifiedEditor())];
+ codeRef.current = code;
+ diffRef.current = diff;
+ // Light/dark follows the app (`data-theme` on <html>).
+ const observer = new MutationObserver(() => {
+ applyMonacoTheme();
+ // Repaint now: a composited editor layer can otherwise keep the old background until it scrolls.
+ code.render(true);
+ diff.getModifiedEditor().render(true);
+ diff.getOriginalEditor().render(true);
+ });
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "data-theme"] });
+ return () => {
+ observer.disconnect();
+ for (const disposable of disposables) disposable.dispose();
+ code.dispose();
+ diff.dispose();
+ codeRef.current = null;
+ diffRef.current = null;
+ };
+ }, [monaco]);
+
+ // Switching documents.
+ useEffect(() => {
+ const code = codeRef.current;
+ const diff = diffRef.current;
+ if (!code || !diff) return;
+ const previous = currentKey.current;
+ if (previous) {
+ viewStates.current.set(previous, mode === "diff" ? diff.saveViewState() : code.saveViewState());
+ }
+ currentKey.current = surface?.key ?? null;
+ if (!surface) {
+ code.setModel(null);
+ setMode(null);
+ onCursorRef.current(null);
+ onHunksRef.current([]);
+ return;
+ }
+ if (surface.kind === "file") {
+ code.setModel(surface.doc.model);
+ code.updateOptions({ readOnly: false });
+ const state = viewStates.current.get(surface.key);
+ if (state) code.restoreViewState(state as MonacoApi.editor.ICodeEditorViewState);
+ setMode("file");
+ onHunksRef.current([]);
+ requestAnimationFrame(() => code.focus());
+ return;
+ }
+ diff.setModel({ original: surface.original, modified: surface.modified });
+ diff.getModifiedEditor().updateOptions({ readOnly: Boolean(surface.readOnlyModified) });
+ const state = viewStates.current.get(surface.key);
+ if (state) diff.restoreViewState(state as MonacoApi.editor.IDiffEditorViewState);
+ setMode("diff");
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [surface]);
+
+ // Hunk bars (review tabs) and the hunk list, after every diff update.
+ useEffect(() => {
+ const diff = diffRef.current;
+ if (!diff || !surface || surface.kind !== "diff") return;
+ const modifiedEditor = diff.getModifiedEditor();
+ const render = () => {
+ const changes = (diff.getLineChanges() ?? []).map((change) => ({
+ originalStartLineNumber: change.originalStartLineNumber,
+ originalEndLineNumber: change.originalEndLineNumber,
+ modifiedStartLineNumber: change.modifiedStartLineNumber,
+ modifiedEndLineNumber: change.modifiedEndLineNumber,
+ }));
+ hunksRef.current = changes;
+ onHunksRef.current(changes);
+ // Each bar is an overlay widget (above the text layer, so it takes clicks) kept on top of
+ // an empty view zone that makes room for it between the lines.
+ for (const widget of overlays.current) modifiedEditor.removeOverlayWidget(widget);
+ overlays.current = [];
+ modifiedEditor.changeViewZones((accessor) => {
+ for (const id of zoneIds.current) accessor.removeZone(id);
+ zoneIds.current = [];
+ if (!surface.review) return;
+ const layout = modifiedEditor.getLayoutInfo();
+ const left = layout.contentLeft;
+ const width = Math.max(120, layout.width - layout.contentLeft - layout.verticalScrollbarWidth - 8);
+ changes.forEach((hunk, index) => {
+ const after = hunk.modifiedEndLineNumber === 0 ? hunk.modifiedStartLineNumber : hunk.modifiedStartLineNumber - 1;
+ const bar = hunkBar(hunk, index, changes.length, surface.review!);
+ bar.style.position = "absolute";
+ bar.style.left = `${left}px`;
+ bar.style.width = `${width}px`;
+ bar.style.top = "0px";
+ bar.style.visibility = "hidden";
+ const widget: MonacoApi.editor.IOverlayWidget = {
+ getId: () => `omnirush.hunk.${index}`,
+ getDomNode: () => bar,
+ getPosition: () => null,
+ };
+ modifiedEditor.addOverlayWidget(widget);
+ overlays.current.push(widget);
+ const spacer = document.createElement("div");
+ zoneIds.current.push(accessor.addZone({
+ afterLineNumber: after,
+ heightInPx: 26,
+ ordinal: -1,
+ domNode: spacer,
+ onDomNodeTop: (top) => {
+ bar.style.top = `${top}px`;
+ bar.style.visibility = "visible";
+ },
+ onComputedHeight: (height) => {
+ bar.style.display = height > 0 ? "flex" : "none";
+ },
+ }));
+ });
+ });
+ };
+ const subscription = diff.onDidUpdateDiff(render);
+ // A bar whose zone scrolled out of view is hidden until the zone is drawn again.
+ const scroll = modifiedEditor.onDidScrollChange(() => {
+ for (const widget of overlays.current) widget.getDomNode().style.visibility = "hidden";
+ });
+ const layout = modifiedEditor.onDidLayoutChange(() => render());
+ render();
+ return () => {
+ subscription.dispose();
+ scroll.dispose();
+ layout.dispose();
+ modifiedEditor.changeViewZones((accessor) => {
+ for (const id of zoneIds.current) accessor.removeZone(id);
+ });
+ zoneIds.current = [];
+ for (const widget of overlays.current) modifiedEditor.removeOverlayWidget(widget);
+ overlays.current = [];
+ };
+ }, [surface]);
+
+ // Next / previous hunk.
+ useEffect(() => {
+ const diff = diffRef.current;
+ if (!navigate || !diff || mode !== "diff") return;
+ const editor = diff.getModifiedEditor();
+ const line = editor.getPosition()?.lineNumber ?? 0;
+ const starts = hunksRef.current.map((hunk) => Math.max(1, hunk.modifiedStartLineNumber));
+ if (starts.length === 0) return;
+ const target = navigate.direction === 1
+ ? starts.find((start) => start > line) ?? starts[0]!
+ : [...starts].reverse().find((start) => start < line) ?? starts[starts.length - 1]!;
+ editor.setPosition({ lineNumber: target, column: 1 });
+ editor.revealLineInCenter(target);
+ editor.focus();
+ }, [navigate, mode]);
+
+ return (
+ <div className="relative min-h-0 flex-1" data-editor-surface={mode ?? "empty"}>
+ {/* display:none, not visibility: Monaco's layers set their own visibility and would show through. */}
+ <div ref={codeHostRef} className="absolute inset-0" style={{ display: mode === "file" ? "block" : "none" }} />
+ <div ref={diffHostRef} className="absolute inset-0" style={{ display: mode === "diff" ? "block" : "none" }} />
+ </div>
+ );
+}
diff --git a/apps/app/src/react-app/domains/session/editor/editor.css b/apps/app/src/react-app/domains/session/editor/editor.css
new file mode 100644
index 00000000..903be99d
--- /dev/null
+++ b/apps/app/src/react-app/domains/session/editor/editor.css
@@ -0,0 +1,28 @@
+/* The desktop editor's Accept / Reject bar above each agent change (editor-surface.tsx). */
+.omnirush-hunk-bar {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ height: 26px;
+ padding: 0 10px 0 8px;
+ font: 11px/1 var(--font-sans, system-ui, sans-serif);
+ color: var(--muted-foreground);
+ background: color-mix(in srgb, var(--primary) 7%, transparent);
+ border-top: 1px solid color-mix(in srgb, var(--primary) 22%, transparent);
+ box-sizing: border-box;
+ pointer-events: auto;
+}
+.omnirush-hunk-label { margin-left: 4px; white-space: nowrap; }
+.omnirush-hunk-btn {
+ height: 19px;
+ padding: 0 9px;
+ border-radius: 6px;
+ border: 1px solid var(--border);
+ background: var(--background);
+ color: var(--foreground);
+ font: inherit;
+ cursor: pointer;
+}
+.omnirush-hunk-btn:hover { background: var(--muted); }
+.omnirush-hunk-btn-primary { background: var(--primary); border-color: var(--primary); color: var(--primary-foreground, #fff); }
+.omnirush-hunk-btn-primary:hover { background: color-mix(in srgb, var(--primary) 88%, black); }
diff --git a/apps/app/src/react-app/domains/session/editor/hunk-ops.ts b/apps/app/src/react-app/domains/session/editor/hunk-ops.ts
new file mode 100644
index 00000000..138898aa
--- /dev/null
+++ b/apps/app/src/react-app/domains/session/editor/hunk-ops.ts
@@ -0,0 +1,54 @@
+/**
+ * Accepting and rejecting one hunk of a review diff, on line arrays (a
+ * Monaco model's lines; a final newline is a trailing empty line). The hunk
+ * is Monaco's ILineChange: an end line of 0 on one side means no lines there
+ * (an insertion or a deletion after the start line).
+ *
+ * - accept: the "before" side takes the hunk's new lines (the change stays,
+ * and is no longer shown as pending);
+ * - reject: the file takes the hunk's old lines back.
+ */
+export type LineHunk = {
+ originalStartLineNumber: number;
+ originalEndLineNumber: number;
+ modifiedStartLineNumber: number;
+ modifiedEndLineNumber: number;
+};
+
+function sideRange(start: number, end: number): { from: number; count: number } {
+ // An empty side sits after line `start`: insert at index `start`.
+ if (end === 0) return { from: start, count: 0 };
+ return { from: start - 1, count: end - start + 1 };
+}
+
+/** The hunk's lines on each side. */
+export function hunkLines(original: string[], modified: string[], hunk: LineHunk): { old: string[]; new: string[] } {
+ const o = sideRange(hunk.originalStartLineNumber, hunk.originalEndLineNumber);
+ const m = sideRange(hunk.modifiedStartLineNumber, hunk.modifiedEndLineNumber);
+ return { old: original.slice(o.from, o.from + o.count), new: modified.slice(m.from, m.from + m.count) };
+}
+
+/** The "before" lines with the hunk accepted. */
+export function acceptHunk(original: string[], modified: string[], hunk: LineHunk): string[] {
+ const o = sideRange(hunk.originalStartLineNumber, hunk.originalEndLineNumber);
+ const { new: lines } = hunkLines(original, modified, hunk);
+ const next = [...original];
+ next.splice(o.from, o.count, ...lines);
+ return next;
+}
+
+/** The file's lines with the hunk rejected. */
+export function rejectHunk(original: string[], modified: string[], hunk: LineHunk): string[] {
+ const m = sideRange(hunk.modifiedStartLineNumber, hunk.modifiedEndLineNumber);
+ const { old: lines } = hunkLines(original, modified, hunk);
+ const next = [...modified];
+ next.splice(m.from, m.count, ...lines);
+ return next;
+}
+
+/** Added and removed line counts of a hunk. */
+export function hunkCounts(hunk: LineHunk): { added: number; removed: number } {
+ const added = hunk.modifiedEndLineNumber === 0 ? 0 : hunk.modifiedEndLineNumber - hunk.modifiedStartLineNumber + 1;
+ const removed = hunk.originalEndLineNumber === 0 ? 0 : hunk.originalEndLineNumber - hunk.originalStartLineNumber + 1;
+ return { added, removed };
+}
diff --git a/apps/app/src/react-app/domains/session/editor/monaco.ts b/apps/app/src/react-app/domains/session/editor/monaco.ts
new file mode 100644
index 00000000..76ef3c4a
--- /dev/null
+++ b/apps/app/src/react-app/domains/session/editor/monaco.ts
@@ -0,0 +1,206 @@
+/**
+ * Monaco for the desktop editor, loaded on first use only (editor-panel.tsx
+ * imports this module lazily): the core editor and diff editor, the editing
+ * features a code editor needs, and syntax colouring for every language
+ * Monaco ships (each grammar loads when a file of that language opens).
+ * Language services (TypeScript, JSON, CSS, HTML workers) are left out: they
+ * cost hundreds of MB on large projects and the agent already runs the
+ * project's own checks. The one worker is Monaco's editor worker (diffs,
+ * word completion), started on demand.
+ */
+import * as monaco from "monaco-editor/editor/editor.api.js";
+import EditorWorker from "monaco-editor/editor/editor.worker.js?worker";
+
+import "monaco-editor/features/codicon/register.js";
+import "monaco-editor/features/codeEditor/register.js";
+import "monaco-editor/features/diffEditor/register.js";
+import "monaco-editor/features/bracketMatching/register.js";
+import "monaco-editor/features/caretOperations/register.js";
+import "monaco-editor/features/clipboard/register.js";
+import "monaco-editor/features/comment/register.js";
+import "monaco-editor/features/contextmenu/register.js";
+import "monaco-editor/features/cursorUndo/register.js";
+import "monaco-editor/features/find/register.js";
+import "monaco-editor/features/folding/register.js";
+import "monaco-editor/features/gotoLine/register.js";
+import "monaco-editor/features/hover/register.js";
+import "monaco-editor/features/indentation/register.js";
+import "monaco-editor/features/lineSelection/register.js";
+import "monaco-editor/features/linesOperations/register.js";
+import "monaco-editor/features/links/register.js";
+import "monaco-editor/features/multicursor/register.js";
+import "monaco-editor/features/smartSelect/register.js";
+import "monaco-editor/features/stickyScroll/register.js";
+import "monaco-editor/features/suggest/register.js";
+import "monaco-editor/features/tokenization/register.js";
+import "monaco-editor/features/unicodeHighlighter/register.js";
+import "monaco-editor/features/wordHighlighter/register.js";
+import "monaco-editor/features/wordOperations/register.js";
+import "monaco-editor/features/readOnlyMessage/register.js";
+// Syntax colouring only (Monarch grammars, each loaded on first use); not languages/register.all.js,
+// which also starts the CSS/HTML/JSON/TypeScript language-service workers.
+import "monaco-editor/languages/definitions/abap/register.js";
+import "monaco-editor/languages/definitions/apex/register.js";
+import "monaco-editor/languages/definitions/azcli/register.js";
+import "monaco-editor/languages/definitions/bat/register.js";
+import "monaco-editor/languages/definitions/bicep/register.js";
+import "monaco-editor/languages/definitions/cameligo/register.js";
+import "monaco-editor/languages/definitions/clojure/register.js";
+import "monaco-editor/languages/definitions/coffee/register.js";
+import "monaco-editor/languages/definitions/cpp/register.js";
+import "monaco-editor/languages/definitions/csharp/register.js";
+import "monaco-editor/languages/definitions/csp/register.js";
+import "monaco-editor/languages/definitions/css/register.js";
+import "monaco-editor/languages/definitions/cypher/register.js";
+import "monaco-editor/languages/definitions/dart/register.js";
+import "monaco-editor/languages/definitions/dockerfile/register.js";
+import "monaco-editor/languages/definitions/ecl/register.js";
+import "monaco-editor/languages/definitions/elixir/register.js";
+import "monaco-editor/languages/definitions/flow9/register.js";
+import "monaco-editor/languages/definitions/freemarker2/register.js";
+import "monaco-editor/languages/definitions/fsharp/register.js";
+import "monaco-editor/languages/definitions/go/register.js";
+import "monaco-editor/languages/definitions/graphql/register.js";
+import "monaco-editor/languages/definitions/handlebars/register.js";
+import "monaco-editor/languages/definitions/hcl/register.js";
+import "monaco-editor/languages/definitions/html/register.js";
+import "monaco-editor/languages/definitions/ini/register.js";
+import "monaco-editor/languages/definitions/java/register.js";
+import "monaco-editor/languages/definitions/javascript/register.js";
+import "monaco-editor/languages/definitions/julia/register.js";
+import "monaco-editor/languages/definitions/kotlin/register.js";
+import "monaco-editor/languages/definitions/less/register.js";
+import "monaco-editor/languages/definitions/lexon/register.js";
+import "monaco-editor/languages/definitions/liquid/register.js";
+import "monaco-editor/languages/definitions/lua/register.js";
+import "monaco-editor/languages/definitions/m3/register.js";
+import "monaco-editor/languages/definitions/markdown/register.js";
+import "monaco-editor/languages/definitions/mdx/register.js";
+import "monaco-editor/languages/definitions/mips/register.js";
+import "monaco-editor/languages/definitions/msdax/register.js";
+import "monaco-editor/languages/definitions/mysql/register.js";
+import "monaco-editor/languages/definitions/objective-c/register.js";
+import "monaco-editor/languages/definitions/pascal/register.js";
+import "monaco-editor/languages/definitions/pascaligo/register.js";
+import "monaco-editor/languages/definitions/perl/register.js";
+import "monaco-editor/languages/definitions/pgsql/register.js";
+import "monaco-editor/languages/definitions/php/register.js";
+import "monaco-editor/languages/definitions/pla/register.js";
+import "monaco-editor/languages/definitions/postiats/register.js";
+import "monaco-editor/languages/definitions/powerquery/register.js";
+import "monaco-editor/languages/definitions/powershell/register.js";
+import "monaco-editor/languages/definitions/protobuf/register.js";
+import "monaco-editor/languages/definitions/pug/register.js";
+import "monaco-editor/languages/definitions/python/register.js";
+import "monaco-editor/languages/definitions/qsharp/register.js";
+import "monaco-editor/languages/definitions/r/register.js";
+import "monaco-editor/languages/definitions/razor/register.js";
+import "monaco-editor/languages/definitions/redis/register.js";
+import "monaco-editor/languages/definitions/redshift/register.js";
+import "monaco-editor/languages/definitions/restructuredtext/register.js";
+import "monaco-editor/languages/definitions/ruby/register.js";
+import "monaco-editor/languages/definitions/rust/register.js";
+import "monaco-editor/languages/definitions/sb/register.js";
+import "monaco-editor/languages/definitions/scala/register.js";
+import "monaco-editor/languages/definitions/scheme/register.js";
+import "monaco-editor/languages/definitions/scss/register.js";
+import "monaco-editor/languages/definitions/shell/register.js";
+import "monaco-editor/languages/definitions/solidity/register.js";
+import "monaco-editor/languages/definitions/sophia/register.js";
+import "monaco-editor/languages/definitions/sparql/register.js";
+import "monaco-editor/languages/definitions/sql/register.js";
+import "monaco-editor/languages/definitions/st/register.js";
+import "monaco-editor/languages/definitions/swift/register.js";
+import "monaco-editor/languages/definitions/systemverilog/register.js";
+import "monaco-editor/languages/definitions/tcl/register.js";
+import "monaco-editor/languages/definitions/twig/register.js";
+import "monaco-editor/languages/definitions/typescript/register.js";
+import "monaco-editor/languages/definitions/typespec/register.js";
+import "monaco-editor/languages/definitions/vb/register.js";
+import "monaco-editor/languages/definitions/wgsl/register.js";
+import "monaco-editor/languages/definitions/xml/register.js";
+import "monaco-editor/languages/definitions/yaml/register.js";
+
+export type Monaco = typeof monaco;
+
+/** The app's theme: `data-theme` on <html> (app/theme.ts), or a `dark` class. */
+export function appIsDark(): boolean {
+ const root = document.documentElement;
+ return root.dataset.theme === "dark" || root.classList.contains("dark");
+}
+
+let configured = false;
+
+/** The editor's themes, from the app's design tokens (index.css): light and dark follow the app. */
+function defineThemes(): void {
+ const css = getComputedStyle(document.documentElement);
+ const token = (name: string, fallback: string) => {
+ const value = css.getPropertyValue(name).trim();
+ return /^#[0-9a-f]{3,8}$/i.test(value) ? value : fallback;
+ };
+ const dark = appIsDark();
+ const name = dark ? "omnirush-dark" : "omnirush-light";
+ monaco.editor.defineTheme(name, {
+ base: dark ? "vs-dark" : "vs",
+ inherit: true,
+ rules: [],
+ colors: {
+ "editor.background": token("--background", dark ? "#111113" : "#fcfcfd"),
+ "editor.foreground": token("--foreground", dark ? "#edeef0" : "#1c2024"),
+ "editorLineNumber.foreground": dark ? "#5a6169" : "#a0a5ad",
+ "editorLineNumber.activeForeground": dark ? "#b0b4ba" : "#60646c",
+ "editor.lineHighlightBackground": dark ? "#18191b" : "#f5f5f7",
+ "editor.lineHighlightBorder": "#00000000",
+ "editorGutter.background": token("--background", dark ? "#111113" : "#fcfcfd"),
+ "editorWidget.background": dark ? "#18191b" : "#ffffff",
+ "editorWidget.border": dark ? "#2e3135" : "#e0e1e6",
+ "diffEditor.insertedLineBackground": dark ? "#3dd68c1f" : "#30a46c1c",
+ "diffEditor.removedLineBackground": dark ? "#ff95921f" : "#e5484d1a",
+ "diffEditor.insertedTextBackground": dark ? "#3dd68c33" : "#30a46c33",
+ "diffEditor.removedTextBackground": dark ? "#ff959233" : "#e5484d33",
+ "scrollbarSlider.background": dark ? "#ffffff1a" : "#0000001a",
+ "scrollbarSlider.hoverBackground": dark ? "#ffffff29" : "#00000029",
+ },
+ });
+}
+
+export function monacoThemeName(): string {
+ return appIsDark() ? "omnirush-dark" : "omnirush-light";
+}
+
+/** Re-reads the app's tokens and switches the editor theme (light/dark changed). */
+export function applyMonacoTheme(): void {
+ defineThemes();
+ monaco.editor.setTheme(monacoThemeName());
+}
+
+export function setupMonaco(): Monaco {
+ if (!configured) {
+ configured = true;
+ (self as unknown as { MonacoEnvironment: monaco.Environment }).MonacoEnvironment = {
+ getWorker: () => new EditorWorker(),
+ };
+ defineThemes();
+ }
+ return monaco;
+}
+
+/** Monaco's language id for a path, from the extensions and file names its grammars register. */
+export function languageForPath(path: string): string {
+ const name = path.split("/").pop() ?? path;
+ const lower = name.toLowerCase();
+ for (const language of monaco.languages.getLanguages()) {
+ if (language.filenames?.some((candidate) => candidate.toLowerCase() === lower)) return language.id;
+ }
+ let best: { id: string; length: number } | null = null;
+ for (const language of monaco.languages.getLanguages()) {
+ for (const extension of language.extensions ?? []) {
+ const ext = extension.toLowerCase();
+ if (lower.endsWith(ext) && (!best || ext.length > best.length)) best = { id: language.id, length: ext.length };
+ }
+ }
+ if (best) return best.id;
+ // JSON has no grammar without its language-service worker; JavaScript's colours it well.
+ if (/\.(json|jsonc|json5|webmanifest)$/.test(lower) || lower === ".babelrc" || lower === ".eslintrc") return "javascript";
+ return "plaintext";
+}
diff --git a/apps/app/src/react-app/domains/session/editor/quick-open-rank.ts b/apps/app/src/react-app/domains/session/editor/quick-open-rank.ts
new file mode 100644
index 00000000..73dbd036
--- /dev/null
+++ b/apps/app/src/react-app/domains/session/editor/quick-open-rank.ts
@@ -0,0 +1,45 @@
+/**
+ * Quick open's file ranking (Cmd/Ctrl+P): a subsequence match of the query
+ * in the path, scored higher for matches in the file name, at word starts
+ * and in contiguous runs, and for shorter paths. -1 when it does not match.
+ */
+export function fuzzyScore(path: string, query: string): number {
+ const q = query.toLowerCase().replace(/\s+/g, "");
+ if (!q) return 0;
+ const p = path.toLowerCase();
+ const nameStart = p.lastIndexOf("/") + 1;
+ // Try matching inside the file name first, then anywhere.
+ const attempt = (from: number) => {
+ let score = 0;
+ let pi = from;
+ let run = 0;
+ for (let qi = 0; qi < q.length; qi += 1) {
+ const ch = q[qi]!;
+ const found = p.indexOf(ch, pi);
+ if (found < 0) return -1;
+ const prev = found > 0 ? p[found - 1]! : "/";
+ const wordStart = prev === "/" || prev === "." || prev === "-" || prev === "_" || prev === " ";
+ run = found === pi && qi > 0 ? run + 1 : 0;
+ score += 1 + run * 3 + (wordStart ? 4 : 0) + (found >= nameStart ? 2 : 0);
+ pi = found + 1;
+ }
+ return score;
+ };
+ const inName = attempt(nameStart);
+ const anywhere = attempt(0);
+ const best = Math.max(inName >= 0 ? inName + 6 : -1, anywhere);
+ if (best < 0) return -1;
+ return best * 100 - Math.min(path.length, 99);
+}
+
+/** The best `limit` paths for the query, best first; with no query, the given order. */
+export function rankPaths(paths: readonly string[], query: string, limit: number): string[] {
+ if (!query.trim()) return paths.slice(0, limit);
+ const scored: Array<{ path: string; score: number }> = [];
+ for (const path of paths) {
+ const score = fuzzyScore(path, query);
+ if (score >= 0) scored.push({ path, score });
+ }
+ scored.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));
+ return scored.slice(0, limit).map((item) => item.path);
+}
diff --git a/apps/app/src/react-app/domains/session/editor/quick-open.tsx b/apps/app/src/react-app/domains/session/editor/quick-open.tsx
new file mode 100644
index 00000000..89d99890
--- /dev/null
+++ b/apps/app/src/react-app/domains/session/editor/quick-open.tsx
@@ -0,0 +1,101 @@
+/** @jsxImportSource react */
+import { useEffect, useMemo, useRef, useState } from "react";
+import { FileText } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+import { rankPaths } from "./quick-open-rank";
+
+type QuickOpenProps = {
+ files: readonly string[];
+ recent: readonly string[];
+ onOpen: (path: string) => void;
+ onClose: () => void;
+};
+
+const LIMIT = 60;
+
+/** Cmd/Ctrl+P: type part of a file name, arrows to move, Enter to open, Esc to close. */
+export function QuickOpen({ files, recent, onOpen, onClose }: QuickOpenProps) {
+ const [query, setQuery] = useState("");
+ const [index, setIndex] = useState(0);
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const listRef = useRef<HTMLDivElement | null>(null);
+ const results = useMemo(() => {
+ if (!query.trim()) {
+ const known = new Set(files);
+ const first = recent.filter((path) => known.has(path));
+ const rest = files.filter((path) => !first.includes(path));
+ return [...first, ...rest].slice(0, LIMIT);
+ }
+ return rankPaths(files, query, LIMIT);
+ }, [files, recent, query]);
+
+ useEffect(() => inputRef.current?.focus(), []);
+ useEffect(() => setIndex(0), [query]);
+ useEffect(() => {
+ listRef.current?.querySelector<HTMLElement>(`[data-index="${index}"]`)?.scrollIntoView({ block: "nearest" });
+ }, [index]);
+
+ return (
+ <div
+ className="absolute inset-0 z-30 flex justify-center bg-black/10 pt-14 dark:bg-black/30"
+ onMouseDown={(event) => {
+ if (event.target === event.currentTarget) onClose();
+ }}
+ data-editor-quick-open
+ >
+ <div className="flex h-fit max-h-[70%] w-[min(560px,92%)] flex-col overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground shadow-2xl">
+ <input
+ ref={inputRef}
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Escape") {
+ event.preventDefault();
+ onClose();
+ } else if (event.key === "ArrowDown") {
+ event.preventDefault();
+ setIndex((value) => Math.min(value + 1, Math.max(0, results.length - 1)));
+ } else if (event.key === "ArrowUp") {
+ event.preventDefault();
+ setIndex((value) => Math.max(value - 1, 0));
+ } else if (event.key === "Enter") {
+ event.preventDefault();
+ const path = results[index];
+ if (path) onOpen(path);
+ }
+ }}
+ placeholder="Go to file…"
+ aria-label="Go to file"
+ className="h-11 w-full border-b border-border bg-transparent px-4 text-sm outline-none placeholder:text-muted-foreground"
+ />
+ <div ref={listRef} role="listbox" className="min-h-0 flex-1 overflow-y-auto py-1">
+ {results.length === 0 ? (
+ <p className="px-4 py-3 text-xs text-muted-foreground">No matching files.</p>
+ ) : results.map((path, i) => {
+ const slash = path.lastIndexOf("/");
+ return (
+ <button
+ key={path}
+ type="button"
+ role="option"
+ aria-selected={i === index}
+ data-index={i}
+ onMouseEnter={() => setIndex(i)}
+ onClick={() => onOpen(path)}
+ className={cn(
+ "flex w-full items-center gap-2 px-4 py-1.5 text-start text-[12.5px]",
+ i === index ? "bg-primary/10 text-foreground" : "text-foreground/90",
+ )}
+ >
+ <FileText className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate font-medium">{path.slice(slash + 1)}</span>
+ <span className="min-w-0 truncate text-xs text-muted-foreground">{slash > 0 ? path.slice(0, slash) : ""}</span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/app/src/react-app/domains/session/editor/review.ts b/apps/app/src/react-app/domains/session/editor/review.ts
new file mode 100644
index 00000000..ffebe023
--- /dev/null
+++ b/apps/app/src/react-app/domains/session/editor/review.ts
@@ -0,0 +1,182 @@
+/**
+ * The agent's changes for review: the engine records each turn's file
+ * changes as unified patches (session diff per user message). The editor
+ * shows a file's change as a diff of "before" (the file as it was before the
+ * turn) against the file on disk; "before" is the disk text with the turn's
+ * patch undone. A patch that no longer fits the file (edited since) yields
+ * null and the file is listed without a reviewable diff.
+ */
+
+export type PatchLine = { kind: " " | "-" | "+"; text: string };
+export type PatchHunk = { oldStart: number; oldLines: number; newStart: number; newLines: number; lines: PatchLine[] };
+export type ParsedPatch = { hunks: PatchHunk[]; oldNoNewline: boolean; newNoNewline: boolean };
+
+export type TurnFileChange = {
+ path: string;
+ status: "added" | "modified" | "deleted";
+ additions: number;
+ deletions: number;
+ patch: string;
+};
+
+/** The hunks of a unified patch (one file). */
+export function parseUnifiedPatch(patch: string): ParsedPatch {
+ const hunks: PatchHunk[] = [];
+ let current: PatchHunk | null = null;
+ let last: PatchLine["kind"] | null = null;
+ let oldNoNewline = false;
+ let newNoNewline = false;
+ for (const line of patch.split("\n")) {
+ const header = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line);
+ if (header) {
+ current = {
+ oldStart: Number(header[1]),
+ oldLines: header[2] === undefined ? 1 : Number(header[2]),
+ newStart: Number(header[3]),
+ newLines: header[4] === undefined ? 1 : Number(header[4]),
+ lines: [],
+ };
+ hunks.push(current);
+ last = null;
+ continue;
+ }
+ if (!current) continue;
+ if (line.startsWith("\\")) {
+ // "\ No newline at end of file" applies to the line before it.
+ if (last === "-" ) oldNoNewline = true;
+ else if (last === "+") newNoNewline = true;
+ else if (last === " ") {
+ oldNoNewline = true;
+ newNoNewline = true;
+ }
+ continue;
+ }
+ const kind = line[0];
+ if (kind === " " || kind === "-" || kind === "+") {
+ current.lines.push({ kind, text: line.slice(1) });
+ last = kind;
+ } else if (line === "" ) {
+ // A trailing empty line of the patch text, or an empty context line some writers emit without the space.
+ const expectedOld = current.lines.filter((item) => item.kind !== "+").length;
+ const expectedNew = current.lines.filter((item) => item.kind !== "-").length;
+ if (expectedOld < current.oldLines && expectedNew < current.newLines) {
+ current.lines.push({ kind: " ", text: "" });
+ last = " ";
+ }
+ }
+ }
+ return { hunks, oldNoNewline, newNoNewline };
+}
+
+function splitText(text: string): { lines: string[]; finalNewline: boolean } {
+ if (text === "") return { lines: [], finalNewline: false };
+ const finalNewline = text.endsWith("\n");
+ const lines = (finalNewline ? text.slice(0, -1) : text).split("\n");
+ return { lines, finalNewline };
+}
+
+function joinText(lines: string[], finalNewline: boolean): string {
+ if (lines.length === 0) return "";
+ return lines.join("\n") + (finalNewline ? "\n" : "");
+}
+
+function matchesAt(haystack: string[], at: number, needle: string[]): boolean {
+ if (at < 0 || at + needle.length > haystack.length) return false;
+ for (let i = 0; i < needle.length; i += 1) if (haystack[at + i] !== needle[i]) return false;
+ return true;
+}
+
+/** Where `needle` sits in `haystack`, searching outward from `hint`; -1 when absent. */
+function locate(haystack: string[], needle: string[], hint: number): number {
+ if (needle.length === 0) return Math.max(0, Math.min(hint, haystack.length));
+ const limit = haystack.length;
+ for (let offset = 0; offset <= limit; offset += 1) {
+ if (matchesAt(haystack, hint - offset, needle)) return hint - offset;
+ if (offset > 0 && matchesAt(haystack, hint + offset, needle)) return hint + offset;
+ }
+ return -1;
+}
+
+/**
+ * The text before a patch, from the text after it (the patch undone), or
+ * null when the patch does not fit `after`.
+ */
+export function reversePatch(after: string, patch: string): string | null {
+ const parsed = parseUnifiedPatch(patch);
+ if (parsed.hunks.length === 0) return null;
+ const { lines, finalNewline } = splitText(after);
+ const result = [...lines];
+ // Last hunk first: earlier line numbers stay valid.
+ for (const hunk of [...parsed.hunks].reverse()) {
+ const newSide = hunk.lines.filter((line) => line.kind !== "-").map((line) => line.text);
+ const oldSide = hunk.lines.filter((line) => line.kind !== "+").map((line) => line.text);
+ const at = locate(result, newSide, Math.max(0, hunk.newStart - 1));
+ if (at < 0) return null;
+ result.splice(at, newSide.length, ...oldSide);
+ }
+ // The old text's final newline: what the patch says, else the same as now.
+ const oldFinalNewline = result.length === 0 ? false : parsed.oldNoNewline ? false : parsed.newNoNewline ? true : finalNewline || lines.length === 0;
+ return joinText(result, oldFinalNewline);
+}
+
+/** The text after a patch, from the text before it (for a deleted file: its whole old text is in the patch). */
+export function applyPatch(before: string, patch: string): string | null {
+ const parsed = parseUnifiedPatch(patch);
+ if (parsed.hunks.length === 0) return null;
+ const { lines, finalNewline } = splitText(before);
+ const result = [...lines];
+ for (const hunk of [...parsed.hunks].reverse()) {
+ const newSide = hunk.lines.filter((line) => line.kind !== "-").map((line) => line.text);
+ const oldSide = hunk.lines.filter((line) => line.kind !== "+").map((line) => line.text);
+ const at = locate(result, oldSide, Math.max(0, hunk.oldStart - 1));
+ if (at < 0) return null;
+ result.splice(at, oldSide.length, ...newSide);
+ }
+ const newFinalNewline = result.length === 0 ? false : parsed.newNoNewline ? false : parsed.oldNoNewline ? true : finalNewline || lines.length === 0;
+ return joinText(result, newFinalNewline);
+}
+
+/**
+ * Each file's text before the reviewed turns, from its current text: the
+ * turns' patches undone newest first. `turns` is oldest first. A file whose
+ * patches do not fit maps to undefined (no reviewable diff); a file the
+ * turns created maps to null (it did not exist).
+ */
+export function baselinesForTurns(
+ turns: TurnFileChange[][],
+ current: (path: string) => string | null,
+): Map<string, string | null | undefined> {
+ const baselines = new Map<string, string | null | undefined>();
+ const texts = new Map<string, string | null>();
+ for (let index = turns.length - 1; index >= 0; index -= 1) {
+ for (const change of turns[index]!) {
+ if (!texts.has(change.path)) texts.set(change.path, current(change.path));
+ const now = texts.get(change.path);
+ if (now === undefined) continue;
+ if (baselines.get(change.path) === undefined && baselines.has(change.path)) continue;
+ let before: string | null | undefined;
+ if (change.status === "added") before = null;
+ else if (change.status === "deleted") before = reversePatch("", change.patch) ?? undefined;
+ else before = now === null ? undefined : reversePatch(now, change.patch) ?? undefined;
+ baselines.set(change.path, before);
+ if (before !== undefined) texts.set(change.path, before);
+ }
+ }
+ return baselines;
+}
+
+/** One engine `FileDiff`/`SnapshotFileDiff` item as a change, or null when it names no file. */
+export function turnFileChange(raw: unknown): TurnFileChange | null {
+ if (!raw || typeof raw !== "object") return null;
+ const item = raw as Record<string, unknown>;
+ const path = typeof item.file === "string" ? item.file : typeof item.path === "string" ? item.path : null;
+ if (!path || typeof item.patch !== "string") return null;
+ const status = item.status === "added" || item.status === "deleted" ? item.status : "modified";
+ return {
+ path: path.replace(/\\/g, "/").replace(/^\.\//, ""),
+ status,
+ additions: typeof item.additions === "number" ? item.additions : 0,
+ deletions: typeof item.deletions === "number" ? item.deletions : 0,
+ patch: item.patch,
+ };
+}
diff --git a/apps/app/src/react-app/shell/session-route.tsx b/apps/app/src/react-app/shell/session-route.tsx
index 49d8e041..f766957f 100644
--- a/apps/app/src/react-app/shell/session-route.tsx
+++ b/apps/app/src/react-app/shell/session-route.tsx
@@ -3505,6 +3505,7 @@ export function SessionRoute() {
) : undefined}
terminalOpen={terminalOpen}
onTerminalOpenChange={setTerminalOpen}
+ opencodeClient={opencodeClient}
onSessionTabsChange={(tabs) => {
sessionTabNavRef.current = { ...sessionTabNavRef.current, options: tabs };
}}
diff --git a/apps/app/src/react-app/shell/ui-state-store.ts b/apps/app/src/react-app/shell/ui-state-store.ts
index 6152f989..9931ac48 100644
--- a/apps/app/src/react-app/shell/ui-state-store.ts
+++ b/apps/app/src/react-app/shell/ui-state-store.ts
@@ -14,7 +14,7 @@ export const DEFAULT_WORKSPACE_RIGHT_SIDEBAR_EXPANDED_WIDTH = 520;
export const MIN_WORKSPACE_RIGHT_SIDEBAR_WIDTH = 320;
export const MAX_WORKSPACE_RIGHT_SIDEBAR_WIDTH = 960;
-export const SIDE_PANEL_ITEMS = ["panel", "extensions"] as const;
+export const SIDE_PANEL_ITEMS = ["panel", "extensions", "editor"] as const;
export type SidePanelItem = (typeof SIDE_PANEL_ITEMS)[number];
export type SidePanelState = Record<string, SidePanelItem | null>;
diff --git a/apps/app/src/react-app/shell/use-shell-shortcuts.ts b/apps/app/src/react-app/shell/use-shell-shortcuts.ts
index 1874840b..9c564443 100644
--- a/apps/app/src/react-app/shell/use-shell-shortcuts.ts
+++ b/apps/app/src/react-app/shell/use-shell-shortcuts.ts
@@ -23,6 +23,8 @@ import {
} from "./thinking-mode-shortcut";
import { isFavoriteModelShortcut } from "./favorite-model-shortcut";
import { useTerminalTabsStore } from "../domains/session/terminal/terminal-tabs-store";
+import { useEditorStore } from "../domains/session/editor/editor-store";
+import { isElectronRuntime } from "../../app/utils";
export type UseShellShortcutsInput = {
canCreateTask: boolean;
@@ -115,6 +117,8 @@ export function useShellShortcuts(input: UseShellShortcutsInput) {
// Cmd/Ctrl+N -> new task in selected workspace
// Cmd/Ctrl+K -> toggle command palette
// Cmd/Ctrl+J -> toggle terminal panel (matches VS Code)
+ // Cmd/Ctrl+P -> editor: go to file (opens the editor)
+ // Cmd/Ctrl+Shift+E -> show / hide the editor
// Ctrl+Shift+` -> new terminal tab (matches VS Code; Ctrl on macOS too)
// Cmd/Ctrl+F -> find in current conversation (handled by session surface)
// Cmd/Ctrl+Shift+F -> search every session (titles + messages)
@@ -151,6 +155,11 @@ export function useShellShortcuts(input: UseShellShortcutsInput) {
setSessionSearchOpen((value) => !value);
return;
}
+ if (event.shiftKey && !event.altKey && event.key?.toLowerCase() === "e") {
+ event.preventDefault();
+ if (!event.repeat) useEditorStore.getState().requestToggle();
+ return;
+ }
if (event.shiftKey && !event.altKey && event.key?.toLowerCase() === "t") {
event.preventDefault();
onPrevSessionTab?.();
@@ -173,6 +182,14 @@ export function useShellShortcuts(input: UseShellShortcutsInput) {
}
return;
}
+ if (key === "p" && isElectronRuntime()) {
+ // Quick open: shows the editor (session-page) with its file finder.
+ event.preventDefault();
+ const editor = useEditorStore.getState();
+ editor.setQuickOpen(true);
+ editor.requestShow();
+ return;
+ }
if (key === "j" && platform.capabilities.terminal) {
event.preventDefault();
setTerminalOpen((value) => !value);
diff --git a/apps/app/tests/editor-review.test.ts b/apps/app/tests/editor-review.test.ts
new file mode 100644
index 00000000..c926509c
--- /dev/null
+++ b/apps/app/tests/editor-review.test.ts
@@ -0,0 +1,103 @@
+import { describe, expect, test } from "bun:test";
+
+import {
+ applyPatch,
+ baselinesForTurns,
+ parseUnifiedPatch,
+ reversePatch,
+ turnFileChange,
+ type TurnFileChange,
+} from "../src/react-app/domains/session/editor/review";
+import { fuzzyScore, rankPaths } from "../src/react-app/domains/session/editor/quick-open-rank";
+import { acceptHunk, hunkCounts, rejectHunk } from "../src/react-app/domains/session/editor/hunk-ops";
+
+// The engine's patch for the rig's ED turn 1 (session diff of the user message).
+const ORDERS_PATCH = "Index: src/orders.ts\n===================================================================\n--- src/orders.ts\t\n+++ src/orders.ts\t\n@@ -1,6 +1,7 @@\n import { db } from \"./db\";\n \n export async function list(query: { limit?: number }) {\n- const rows = await db.orders.findMany();\n- return rows;\n+ const limit = Math.min(Number(query.limit ?? 50), 200);\n+ const rows = await db.orders.findMany({ take: limit + 1 });\n+ return { items: rows.slice(0, limit), more: rows.length > limit };\n }\n";
+const BEFORE = "import { db } from \"./db\";\n\nexport async function list(query: { limit?: number }) {\n const rows = await db.orders.findMany();\n return rows;\n}\n";
+const AFTER = "import { db } from \"./db\";\n\nexport async function list(query: { limit?: number }) {\n const limit = Math.min(Number(query.limit ?? 50), 200);\n const rows = await db.orders.findMany({ take: limit + 1 });\n return { items: rows.slice(0, limit), more: rows.length > limit };\n}\n";
+
+describe("editor review patches", () => {
+ test("parses hunks", () => {
+ const parsed = parseUnifiedPatch(ORDERS_PATCH);
+ expect(parsed.hunks).toHaveLength(1);
+ expect(parsed.hunks[0]).toMatchObject({ oldStart: 1, oldLines: 6, newStart: 1, newLines: 7 });
+ expect(parsed.hunks[0]!.lines.filter((line) => line.kind === "+")).toHaveLength(3);
+ });
+
+ test("undoes and redoes a turn", () => {
+ expect(reversePatch(AFTER, ORDERS_PATCH)).toBe(BEFORE);
+ expect(applyPatch(BEFORE, ORDERS_PATCH)).toBe(AFTER);
+ });
+
+ test("finds a hunk that moved (lines added above since)", () => {
+ expect(reversePatch(`// header\n// more\n${AFTER}`, ORDERS_PATCH)).toBe(`// header\n// more\n${BEFORE}`);
+ });
+
+ test("a patch that no longer fits gives null", () => {
+ expect(reversePatch(AFTER.replace("take: limit + 1", "take: limit"), ORDERS_PATCH)).toBeNull();
+ });
+
+ test("added and deleted files", () => {
+ const added = "@@ -0,0 +1,2 @@\n+one\n+two\n";
+ expect(reversePatch("one\ntwo\n", added)).toBe("");
+ const deleted = "@@ -1,2 +0,0 @@\n-one\n-two\n";
+ expect(reversePatch("", deleted)).toBe("one\ntwo\n");
+ });
+
+ test("no newline at end of file", () => {
+ const patch = "@@ -1 +1 @@\n-a\n\\ No newline at end of file\n+b\n";
+ expect(reversePatch("b\n", patch)).toBe("a");
+ });
+
+ test("baselines across turns, newest undone first", () => {
+ const turn1: TurnFileChange[] = [{ path: "a.txt", status: "modified", additions: 1, deletions: 1, patch: "@@ -1 +1 @@\n-v0\n+v1\n" }];
+ const turn2: TurnFileChange[] = [
+ { path: "a.txt", status: "modified", additions: 1, deletions: 1, patch: "@@ -1 +1 @@\n-v1\n+v2\n" },
+ { path: "new.txt", status: "added", additions: 1, deletions: 0, patch: "@@ -0,0 +1 @@\n+n\n" },
+ ];
+ const disk: Record<string, string> = { "a.txt": "v2\n", "new.txt": "n\n" };
+ const both = baselinesForTurns([turn1, turn2], (path) => disk[path] ?? null);
+ expect(both.get("a.txt")).toBe("v0\n");
+ expect(both.get("new.txt")).toBeNull();
+ const last = baselinesForTurns([turn2], (path) => disk[path] ?? null);
+ expect(last.get("a.txt")).toBe("v1\n");
+ });
+
+ test("engine diff items", () => {
+ expect(turnFileChange({ file: "./src/x.ts", patch: "@@", additions: 1, deletions: 0, status: "added" })).toEqual({
+ path: "src/x.ts", status: "added", additions: 1, deletions: 0, patch: "@@",
+ });
+ expect(turnFileChange({ file: "x" })).toBeNull();
+ });
+});
+
+describe("quick open ranking", () => {
+ test("prefers file-name matches and contiguous runs", () => {
+ const ranked = rankPaths(["docs/order-status.md", "src/routes/orders.ts", "test/orders.test.ts", "src/other.ts"], "ord", 10);
+ expect(ranked).toHaveLength(3);
+ expect(rankPaths(["docs/order-status.md", "src/routes/orders.ts", "test/orders.test.ts"], "orders.ts", 10)[0]).toBe("src/routes/orders.ts");
+ expect(ranked).not.toContain("src/other.ts");
+ expect(fuzzyScore("src/routes/orders.ts", "sro")).toBeGreaterThan(0);
+ expect(fuzzyScore("abc", "abd")).toBe(-1);
+ });
+});
+
+describe("hunk accept and reject", () => {
+ const original = ["a", "b", "c", "d", ""];
+ const modified = ["a", "B", "c", "x", "d", ""];
+ const change = { originalStartLineNumber: 2, originalEndLineNumber: 2, modifiedStartLineNumber: 2, modifiedEndLineNumber: 2 };
+ const insertion = { originalStartLineNumber: 3, originalEndLineNumber: 0, modifiedStartLineNumber: 4, modifiedEndLineNumber: 4 };
+
+ test("accept moves the before side", () => {
+ expect(acceptHunk(original, modified, change)).toEqual(["a", "B", "c", "d", ""]);
+ expect(acceptHunk(original, modified, insertion)).toEqual(["a", "b", "c", "x", "d", ""]);
+ });
+
+ test("reject restores the file", () => {
+ expect(rejectHunk(original, modified, change)).toEqual(["a", "b", "c", "x", "d", ""]);
+ expect(rejectHunk(original, modified, insertion)).toEqual(["a", "B", "c", "d", ""]);
+ const deletion = { originalStartLineNumber: 2, originalEndLineNumber: 3, modifiedStartLineNumber: 1, modifiedEndLineNumber: 0 };
+ expect(rejectHunk(["a", "b", "c", "d"], ["a", "d"], deletion)).toEqual(["a", "b", "c", "d"]);
+ expect(hunkCounts(deletion)).toEqual({ added: 0, removed: 2 });
+ });
+});
diff --git a/apps/server/src/editor-diff.ts b/apps/server/src/editor-diff.ts
new file mode 100644
index 00000000..6efe02ea
--- /dev/null
+++ b/apps/server/src/editor-diff.ts
@@ -0,0 +1,181 @@
+/**
+ * Line diff for the desktop editor's user edits (routes/editor.ts): how many
+ * lines a save added and removed, and the unified diff text of the change.
+ * Myers' O(ND) algorithm over the lines that differ after the common prefix
+ * and suffix are cut; past `maxEdits` differing lines it stops and reports
+ * the counts from a cheap multiset comparison instead, without a diff.
+ */
+
+export type LineDiffStats = {
+ added: number;
+ removed: number;
+ /** Unified diff text (`--- a/path`, `+++ b/path`, `@@` hunks), or null when the change was too large to diff. */
+ diff: string | null;
+};
+
+/** Diffs larger than this many edit steps are summarised by counts only. */
+export const MAX_EDITOR_DIFF_EDITS = 1_500;
+const CONTEXT_LINES = 3;
+
+function splitLines(text: string): string[] {
+ if (text === "") return [];
+ const lines = text.split("\n");
+ if (lines.at(-1) === "") lines.pop();
+ return lines;
+}
+
+type Op = { kind: " " | "-" | "+"; line: string };
+
+/** Myers' greedy diff of two line arrays, or null past `maxEdits` edit steps. */
+function myers(a: string[], b: string[], maxEdits: number): Op[] | null {
+ const n = a.length;
+ const m = b.length;
+ const max = Math.min(n + m, maxEdits);
+ const offset = max + 1;
+ const v = new Int32Array(2 * max + 3);
+ // Per step, the slice of `v` for diagonals -d-1..d+1 (what backtracking reads): O(D^2) memory.
+ const trace: Int32Array[] = [];
+ let found = -1;
+ for (let d = 0; d <= max; d += 1) {
+ trace.push(v.slice(offset - d - 1, offset + d + 2));
+ for (let k = -d; k <= d; k += 2) {
+ let x = k === -d || (k !== d && v[offset + k - 1]! < v[offset + k + 1]!) ? v[offset + k + 1]! : v[offset + k - 1]! + 1;
+ let y = x - k;
+ while (x < n && y < m && a[x] === b[y]) {
+ x += 1;
+ y += 1;
+ }
+ v[offset + k] = x;
+ if (x >= n && y >= m) {
+ found = d;
+ break;
+ }
+ }
+ if (found >= 0) break;
+ }
+ if (found < 0) return null;
+ const ops: Op[] = [];
+ let x = n;
+ let y = m;
+ for (let d = found; d > 0; d -= 1) {
+ const prev = trace[d]!;
+ const at = (diagonal: number) => prev[diagonal + d + 1]!;
+ const k = x - y;
+ const prevK = k === -d || (k !== d && at(k - 1) < at(k + 1)) ? k + 1 : k - 1;
+ const prevX = at(prevK);
+ const prevY = prevX - prevK;
+ while (x > prevX && y > prevY) {
+ ops.push({ kind: " ", line: a[x - 1]! });
+ x -= 1;
+ y -= 1;
+ }
+ if (x === prevX) ops.push({ kind: "+", line: b[y - 1]! });
+ else ops.push({ kind: "-", line: a[x - 1]! });
+ x = prevX;
+ y = prevY;
+ }
+ while (x > 0 && y > 0) {
+ ops.push({ kind: " ", line: a[x - 1]! });
+ x -= 1;
+ y -= 1;
+ }
+ return ops.reverse();
+}
+
+/** Lines in `a` not matched in `b` (as a multiset), and the other way round. */
+function multisetCounts(a: string[], b: string[]): { added: number; removed: number } {
+ const counts = new Map<string, number>();
+ for (const line of a) counts.set(line, (counts.get(line) ?? 0) + 1);
+ let added = 0;
+ for (const line of b) {
+ const left = counts.get(line) ?? 0;
+ if (left > 0) counts.set(line, left - 1);
+ else added += 1;
+ }
+ let removed = 0;
+ for (const left of counts.values()) removed += left;
+ return { added, removed };
+}
+
+function hunkHeader(oldStart: number, oldCount: number, newStart: number, newCount: number): string {
+ const range = (start: number, count: number) => (count === 1 ? `${start}` : `${count === 0 ? start - 1 : start},${count}`);
+ return `@@ -${range(oldStart, oldCount)} +${range(newStart, newCount)} @@`;
+}
+
+/** The unified diff of `before` -> `after` for `path`, with line counts. */
+export function editorLineDiff(path: string, before: string, after: string, maxEdits = MAX_EDITOR_DIFF_EDITS): LineDiffStats {
+ if (before === after) return { added: 0, removed: 0, diff: "" };
+ const a = splitLines(before);
+ const b = splitLines(after);
+ let prefix = 0;
+ while (prefix < a.length && prefix < b.length && a[prefix] === b[prefix]) prefix += 1;
+ let suffix = 0;
+ while (suffix < a.length - prefix && suffix < b.length - prefix && a[a.length - 1 - suffix] === b[b.length - 1 - suffix]) suffix += 1;
+ const midA = a.slice(prefix, a.length - suffix);
+ const midB = b.slice(prefix, b.length - suffix);
+ const middle = myers(midA, midB, maxEdits);
+ if (!middle) return { ...multisetCounts(midA, midB), diff: null };
+ const ops: Op[] = [
+ ...a.slice(0, prefix).map((line) => ({ kind: " " as const, line })),
+ ...middle,
+ ...a.slice(a.length - suffix).map((line) => ({ kind: " " as const, line })),
+ ];
+ let added = 0;
+ let removed = 0;
+ for (const op of ops) {
+ if (op.kind === "+") added += 1;
+ else if (op.kind === "-") removed += 1;
+ }
+ // Only a final-newline change: the lines match but the texts do not.
+ if (added === 0 && removed === 0) {
+ return { added: 0, removed: 0, diff: `--- a/${path}\n+++ b/${path}\n\\ final newline changed\n` };
+ }
+ const lines: string[] = [`--- a/${path}`, `+++ b/${path}`];
+ let i = 0;
+ let oldLine = 1;
+ let newLine = 1;
+ while (i < ops.length) {
+ if (ops[i]!.kind === " ") {
+ oldLine += 1;
+ newLine += 1;
+ i += 1;
+ continue;
+ }
+ // A hunk: up to CONTEXT_LINES before, changes joined while the gap is at most 2 * CONTEXT_LINES.
+ const start = Math.max(0, i - CONTEXT_LINES);
+ let end = i;
+ while (end < ops.length) {
+ if (ops[end]!.kind !== " ") {
+ end += 1;
+ continue;
+ }
+ let gap = end;
+ while (gap < ops.length && ops[gap]!.kind === " ") gap += 1;
+ if (gap >= ops.length || gap - end > 2 * CONTEXT_LINES) {
+ end = Math.min(ops.length, end + CONTEXT_LINES);
+ break;
+ }
+ end = gap;
+ }
+ const lead = i - start;
+ const hunkOldStart = oldLine - lead;
+ const hunkNewStart = newLine - lead;
+ let oldCount = 0;
+ let newCount = 0;
+ const body: string[] = [];
+ for (let j = start; j < end; j += 1) {
+ const op = ops[j]!;
+ body.push(`${op.kind}${op.line}`);
+ if (op.kind !== "+") oldCount += 1;
+ if (op.kind !== "-") newCount += 1;
+ }
+ lines.push(hunkHeader(hunkOldStart, oldCount, hunkNewStart, newCount), ...body);
+ for (let j = i; j < end; j += 1) {
+ const op = ops[j]!;
+ if (op.kind !== "+") oldLine += 1;
+ if (op.kind !== "-") newLine += 1;
+ }
+ i = end;
+ }
+ return { added, removed, diff: `${lines.join("\n")}\n` };
+}
diff --git a/apps/server/src/editor-events.ts b/apps/server/src/editor-events.ts
new file mode 100644
index 00000000..5ea55a9e
--- /dev/null
+++ b/apps/server/src/editor-events.ts
@@ -0,0 +1,54 @@
+/**
+ * The trace events the desktop editor adds to a chat it is used beside
+ * (documented for the converter in e2e/harness-new-events.md):
+ *
+ * - "user_edit": the user saved a file in the editor (or rejected an agent
+ * change, `source: "review"`) between turns. `{path, source, added,
+ * removed, created?, deleted?, diff?, diff_truncated?}`. `diff` is the
+ * unified diff of the save, as `{path, diff}` the same file-aware shape the
+ * trace scrub already redacts per file (a "turn.diff" `files[]` item);
+ * left out when the change is too large to diff or the file is binary.
+ * - "user_review": the user accepted or rejected an agent change in the
+ * review view. `{path, decision, scope, added, removed}` (the hunk's line
+ * counts; no text).
+ *
+ * A chat whose editor is never used carries neither.
+ */
+import { editorLineDiff } from "./editor-diff.js";
+import type { EditorUserEdit, EditorUserReview } from "./routes/editor.js";
+import { isKnownBinaryPath } from "./session-archive/binary.js";
+
+/** A save's diff larger than this is left out of the event (the counts stay). */
+export const MAX_USER_EDIT_DIFF_BYTES = 64 * 1024;
+
+export type UserEditEvent = {
+ path: string;
+ source: "editor" | "review";
+ added: number;
+ removed: number;
+ created?: true;
+ deleted?: true;
+ diff?: string;
+ diff_truncated?: true;
+};
+
+export function editorUserEditEvent(edit: Pick<EditorUserEdit, "path" | "before" | "after" | "source">): UserEditEvent | null {
+ const before = edit.before ?? "";
+ const after = edit.after ?? "";
+ if (edit.before !== null && edit.after !== null && before === after) return null;
+ const stats = editorLineDiff(edit.path, before, after);
+ const event: UserEditEvent = { path: edit.path, source: edit.source, added: stats.added, removed: stats.removed };
+ if (edit.before === null && edit.after !== null) event.created = true;
+ if (edit.after === null) event.deleted = true;
+ if (isKnownBinaryPath(edit.path)) return event;
+ if (stats.diff === null || Buffer.byteLength(stats.diff, "utf8") > MAX_USER_EDIT_DIFF_BYTES) {
+ event.diff_truncated = true;
+ return event;
+ }
+ if (stats.diff) event.diff = stats.diff;
+ return event;
+}
+
+export function editorUserReviewEvent(review: Pick<EditorUserReview, "path" | "decision" | "scope" | "added" | "removed">) {
+ return { path: review.path, decision: review.decision, scope: review.scope, added: review.added, removed: review.removed };
+}
diff --git a/apps/server/src/editor-routes.e2e.test.ts b/apps/server/src/editor-routes.e2e.test.ts
new file mode 100644
index 00000000..5d9c5c59
--- /dev/null
+++ b/apps/server/src/editor-routes.e2e.test.ts
@@ -0,0 +1,205 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { execFileSync } from "node:child_process";
+import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { editorLineDiff } from "./editor-diff.js";
+import { editorUserEditEvent, MAX_USER_EDIT_DIFF_BYTES } from "./editor-events.js";
+import { parsePorcelainStatus } from "./routes/editor.js";
+import { startServer } from "./server.js";
+import type { ServerConfig } from "./types.js";
+
+type Served = { port: number; stop: (closeActiveConnections?: boolean) => void | Promise<void> };
+
+const stops: Array<() => void | Promise<void>> = [];
+const roots: string[] = [];
+
+afterEach(async () => {
+ while (stops.length) await stops.pop()?.();
+ while (roots.length) await rm(roots.pop()!, { recursive: true, force: true });
+});
+
+function git(root: string, ...args: string[]) {
+ return execFileSync("git", ["-c", "[email protected]", "-c", "user.name=e2e", ...args], { cwd: root, encoding: "utf8" });
+}
+
+async function project(options: { git?: boolean } = {}) {
+ const root = await mkdtemp(join(tmpdir(), "omnirush-editor-"));
+ roots.push(root);
+ await mkdir(join(root, "src"), { recursive: true });
+ await mkdir(join(root, "node_modules", "pkg"), { recursive: true });
+ await mkdir(join(root, "dist"), { recursive: true });
+ await writeFile(join(root, ".gitignore"), "dist/\n*.log\n", "utf8");
+ await writeFile(join(root, "src", "main.ts"), "export const a = 1;\n", "utf8");
+ await writeFile(join(root, "src", "notes.log"), "ignored\n", "utf8");
+ await writeFile(join(root, "dist", "out.js"), "ignored\n", "utf8");
+ await writeFile(join(root, "node_modules", "pkg", "index.js"), "ignored\n", "utf8");
+ await writeFile(join(root, "image.bin"), new Uint8Array([1, 0, 2, 3]));
+ if (options.git !== false) {
+ git(root, "init", "-q", "-b", "main");
+ // node_modules is ignored by git only through the .gitignore of real projects; this one relies on ls-files --others honoring .gitignore.
+ await writeFile(join(root, ".gitignore"), "dist/\n*.log\nnode_modules/\n", "utf8");
+ git(root, "add", ".");
+ git(root, "commit", "-q", "-m", "init");
+ }
+ return root;
+}
+
+async function serve(root: string) {
+ const config: ServerConfig = {
+ host: "127.0.0.1",
+ port: 0,
+ token: "owt_test_token",
+ hostToken: "owt_host_token",
+ approval: { mode: "auto", timeoutMs: 1000 },
+ corsOrigins: ["*"],
+ workspaces: [{ id: "ws_1", name: "Workspace", path: root, preset: "starter", workspaceType: "local" }],
+ authorizedRoots: [root],
+ readOnly: false,
+ startedAt: Date.now(),
+ tokenSource: "cli",
+ hostTokenSource: "cli",
+ logFormat: "pretty",
+ logRequests: false,
+ };
+ const server = await startServer(config) as Served;
+ stops.push(() => server.stop(true));
+ const base = `http://127.0.0.1:${server.port}/workspace/ws_1/editor`;
+ const call = async (method: string, path: string, body?: unknown) => {
+ const response = await fetch(`${base}${path}`, {
+ method,
+ headers: { Authorization: `Bearer ${config.token}`, "Content-Type": "application/json", Connection: "close" },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ return { status: response.status, body: await response.json() as any };
+ };
+ return call;
+}
+
+describe("editor routes", () => {
+ test("the tree follows git: ignored files and node_modules stay out", async () => {
+ const root = await project();
+ await writeFile(join(root, "src", "new.ts"), "untracked\n", "utf8");
+ const call = await serve(root);
+ const tree = await call("GET", "/tree");
+ expect(tree.status).toBe(200);
+ expect(tree.body.git).toBe(true);
+ expect(tree.body.files).toEqual([".gitignore", "image.bin", "src/main.ts", "src/new.ts"]);
+ });
+
+ test("without git the walk applies .gitignore and skips node_modules", async () => {
+ const root = await project({ git: false });
+ const call = await serve(root);
+ const tree = await call("GET", "/tree");
+ expect(tree.body.git).toBe(false);
+ expect(tree.body.files).toEqual([".gitignore", "image.bin", "src/main.ts"]);
+ });
+
+ test("reads text, flags binary, saves, and refuses a stale save", async () => {
+ const root = await project();
+ const call = await serve(root);
+ const read = await call("GET", "/file?path=src/main.ts");
+ expect(read.body.content).toBe("export const a = 1;\n");
+ expect((await call("GET", "/file?path=image.bin")).body.binary).toBe(true);
+ expect((await call("GET", "/file?path=missing.ts")).status).toBe(404);
+ const saved = await call("PUT", "/file", { path: "src/main.ts", content: "export const a = 2;\n", baseUpdatedAt: read.body.updatedAt });
+ expect(saved.status).toBe(200);
+ expect(await readFile(join(root, "src", "main.ts"), "utf8")).toBe("export const a = 2;\n");
+ const stale = await call("PUT", "/file", { path: "src/main.ts", content: "x", baseUpdatedAt: read.body.updatedAt - 1000 });
+ expect(stale.status).toBe(409);
+ const created = await call("PUT", "/file", { path: "src/deep/new.ts", content: "new\n" });
+ expect(created.status).toBe(200);
+ expect(await readFile(join(root, "src", "deep", "new.ts"), "utf8")).toBe("new\n");
+ const removed = await call("PUT", "/file", { path: "src/deep/new.ts", delete: true });
+ expect(removed.body.deleted).toBe(true);
+ });
+
+ test("paths outside the workspace are refused", async () => {
+ const root = await project();
+ const outside = await mkdtemp(join(tmpdir(), "omnirush-editor-outside-"));
+ roots.push(outside);
+ await writeFile(join(outside, "secret.txt"), "nope\n", "utf8");
+ await symlink(outside, join(root, "link"));
+ const call = await serve(root);
+ expect((await call("GET", "/file?path=../secret.txt")).status).toBe(400);
+ expect((await call("GET", "/file?path=link/secret.txt")).status).toBe(400);
+ expect((await call("PUT", "/file", { path: "link/evil.txt", content: "x" })).status).toBe(400);
+ expect((await call("PUT", "/file", { path: ".git/config", content: "x" })).status).toBe(400);
+ });
+
+ test("git panel: status, stage, unstage, commit, original text", async () => {
+ const root = await project();
+ const call = await serve(root);
+ await writeFile(join(root, "src", "main.ts"), "export const a = 3;\n", "utf8");
+ await writeFile(join(root, "src", "b.ts"), "b\n", "utf8");
+ const status = await call("GET", "/git/status");
+ expect(status.body.repo).toBe(true);
+ expect(status.body.branch).toBe("main");
+ expect(status.body.files).toEqual([
+ { path: "src/b.ts", index: "?", worktree: "?" },
+ { path: "src/main.ts", index: " ", worktree: "M" },
+ ]);
+ const staged = await call("POST", "/git/stage", { paths: ["src/b.ts", "src/main.ts"] });
+ expect(staged.body.files.map((file: any) => `${file.index}${file.worktree} ${file.path}`)).toEqual(["A src/b.ts", "M src/main.ts"]);
+ const unstaged = await call("POST", "/git/unstage", { paths: ["src/b.ts"] });
+ expect(unstaged.body.files.map((file: any) => `${file.index}${file.worktree} ${file.path}`)).toEqual(["?? src/b.ts", "M src/main.ts"]);
+ const original = await call("GET", "/git/original?path=src/main.ts&ref=HEAD");
+ expect(original.body.content).toBe("export const a = 1;\n");
+ expect((await call("POST", "/git/commit", { message: "" })).status).toBe(400);
+ const commit = await call("POST", "/git/commit", { message: "--amend is just text\n\nbody" });
+ // The rig's git may have no identity: then the error is git's own.
+ if (commit.status === 200) {
+ expect(commit.body.status.files).toEqual([{ path: "src/b.ts", index: "?", worktree: "?" }]);
+ expect(git(root, "log", "-1", "--format=%s")).toBe("--amend is just text\n");
+ } else {
+ expect(commit.body.code ?? commit.body.error).toBeTruthy();
+ }
+ });
+
+ test("a folder that is not a repository has no git panel", async () => {
+ const root = await project({ git: false });
+ const call = await serve(root);
+ expect((await call("GET", "/git/status")).body.repo).toBe(false);
+ expect((await call("POST", "/git/stage", { paths: ["src/main.ts"] })).status).toBe(400);
+ });
+});
+
+describe("editor diff and events", () => {
+ test("porcelain parsing: branch, tracking, renames", () => {
+ const parsed = parsePorcelainStatus("## main...origin/main [ahead 2, behind 1]\0R new.ts\0old.ts\0 M a.ts\0?? b.ts\0");
+ expect(parsed).toEqual({
+ branch: "main",
+ upstream: "origin/main",
+ ahead: 2,
+ behind: 1,
+ files: [
+ { path: "new.ts", from: "old.ts", index: "R", worktree: " " },
+ { path: "a.ts", index: " ", worktree: "M" },
+ { path: "b.ts", index: "?", worktree: "?" },
+ ],
+ });
+ expect(parsePorcelainStatus("## No commits yet on main\0").branch).toBe("main");
+ });
+
+ test("line diff counts and hunks", () => {
+ const result = editorLineDiff("x.txt", "a\nb\nc\n", "a\nB\nc\nd\n");
+ expect(result.added).toBe(2);
+ expect(result.removed).toBe(1);
+ expect(result.diff).toBe("--- a/x.txt\n+++ b/x.txt\n@@ -1,3 +1,4 @@\n a\n-b\n+B\n c\n+d\n");
+ const big = editorLineDiff("x", Array.from({ length: 3000 }, (_, i) => `a${i}`).join("\n"), Array.from({ length: 3000 }, (_, i) => `b${i}`).join("\n"));
+ expect(big).toEqual({ added: 3000, removed: 3000, diff: null });
+ });
+
+ test("user_edit events", () => {
+ expect(editorUserEditEvent({ path: "a.ts", before: "x\n", after: "x\n", source: "editor" })).toBeNull();
+ expect(editorUserEditEvent({ path: "a.ts", before: null, after: "x\n", source: "editor" })).toEqual({
+ path: "a.ts", source: "editor", added: 1, removed: 0, created: true, diff: "--- a/a.ts\n+++ b/a.ts\n@@ -0,0 +1 @@\n+x\n",
+ });
+ expect(editorUserEditEvent({ path: "a.ts", before: "x\n", after: null, source: "review" })).toMatchObject({ deleted: true, removed: 1, source: "review" });
+ const huge = editorUserEditEvent({ path: "a.ts", before: "", after: `${"y".repeat(MAX_USER_EDIT_DIFF_BYTES)}\n`, source: "editor" });
+ expect(huge).toMatchObject({ added: 1, diff_truncated: true });
+ expect(huge?.diff).toBeUndefined();
+ expect(editorUserEditEvent({ path: "logo.png", before: "a", after: "b", source: "editor" })?.diff).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/routes/editor.ts b/apps/server/src/routes/editor.ts
new file mode 100644
index 00000000..c9e3ed28
--- /dev/null
+++ b/apps/server/src/routes/editor.ts
@@ -0,0 +1,454 @@
+/**
+ * The desktop editor's routes (the code editor beside the chat): the project
+ * file list (git's view of it, so .gitignore'd files stay out), reading and
+ * saving any text file, and a small git panel (status, stage, unstage,
+ * commit, the HEAD/index text of a file for its diff).
+ *
+ * Nothing here runs unless the editor asks. A save that names a chat the
+ * session uploader is tracking reports a "user_edit" (and a hunk review
+ * decision a "user_review") through `onUserEdit` / `onUserReview`; a save
+ * without one, or for a chat that is not tracked, reports nothing.
+ */
+import { spawn } from "node:child_process";
+import { chmod, readdir, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
+import { dirname, join, relative, resolve, sep } from "node:path";
+import { ApiError } from "../errors.js";
+import { ignoredByRules, parseGitignoreRules, scopedIgnoreRules } from "../session-uploader.js";
+import type { ApprovalRequest, ServerConfig, TokenScope, WorkspaceInfo } from "../types.js";
+import { ensureDir, shortId } from "../utils.js";
+import { normalizeWorkspaceRelativePath } from "./files.js";
+import { addRoute, type RequestContext, type Route } from "./registry.js";
+
+/** The largest file the editor opens or saves. */
+export const EDITOR_MAX_FILE_BYTES = 5_000_000;
+/** The most files the tree lists; a larger project says it was cut. */
+export const EDITOR_MAX_TREE_FILES = 200_000;
+const GIT_TIMEOUT_MS = 20_000;
+const GIT_MAX_OUTPUT_BYTES = 64 * 1024 * 1024;
+const WALK_SKIPPED_DIRECTORIES = new Set([".git", "node_modules"]);
+const COMMIT_MESSAGE_MAX = 20_000;
+const MAX_PATHS_PER_CALL = 5_000;
+
+export type EditorUserEdit = {
+ workspace: WorkspaceInfo;
+ sessionId: string;
+ path: string;
+ before: string | null;
+ after: string | null;
+ source: "editor" | "review";
+};
+
+export type EditorUserReview = {
+ workspace: WorkspaceInfo;
+ sessionId: string;
+ path: string;
+ decision: "accept" | "reject";
+ added: number;
+ removed: number;
+ scope: "hunk" | "file";
+};
+
+type RegisterEditorRoutesOptions = {
+ routes: Route[];
+ config: ServerConfig;
+ jsonResponse: (data: unknown, status?: number) => Response;
+ readJsonBody: (request: Request) => Promise<Record<string, unknown>>;
+ ensureWritable: (config: ServerConfig) => void;
+ requireApproval: (ctx: RequestContext, input: Omit<ApprovalRequest, "id" | "createdAt" | "actor">) => Promise<void>;
+ requireClientScope: (ctx: RequestContext, required: TokenScope) => void;
+ resolveWorkspace: (config: ServerConfig, id: string) => Promise<WorkspaceInfo>;
+ onUserEdit?: (edit: EditorUserEdit) => void;
+ onUserReview?: (review: EditorUserReview) => void;
+};
+
+type GitResult = { code: number | null; stdout: Buffer; stderr: string };
+
+export function runEditorGit(root: string, args: string[], options: { input?: string; timeoutMs?: number } = {}): Promise<GitResult> {
+ return new Promise((resolvePromise) => {
+ let child;
+ try {
+ child = spawn("git", ["-c", "core.quotePath=false", "-c", "color.ui=false", ...args], {
+ cwd: root,
+ stdio: ["pipe", "pipe", "pipe"],
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0", LC_ALL: "C" },
+ windowsHide: true,
+ });
+ } catch (error) {
+ resolvePromise({ code: null, stdout: Buffer.alloc(0), stderr: error instanceof Error ? error.message : String(error) });
+ return;
+ }
+ const chunks: Buffer[] = [];
+ let size = 0;
+ let stderr = "";
+ let settled = false;
+ const finish = (result: GitResult) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolvePromise(result);
+ };
+ const timer = setTimeout(() => {
+ child.kill("SIGKILL");
+ finish({ code: null, stdout: Buffer.concat(chunks), stderr: "git timed out" });
+ }, options.timeoutMs ?? GIT_TIMEOUT_MS);
+ child.stdout.on("data", (chunk: Buffer) => {
+ size += chunk.length;
+ if (size > GIT_MAX_OUTPUT_BYTES) {
+ child.kill("SIGKILL");
+ finish({ code: null, stdout: Buffer.concat(chunks), stderr: "git output too large" });
+ return;
+ }
+ chunks.push(chunk);
+ });
+ child.stderr.on("data", (chunk: Buffer) => {
+ if (stderr.length < 16_000) stderr += chunk.toString("utf8");
+ });
+ child.on("error", (error) => finish({ code: null, stdout: Buffer.alloc(0), stderr: error.message }));
+ child.on("close", (code) => finish({ code, stdout: Buffer.concat(chunks), stderr }));
+ child.stdin.on("error", () => undefined);
+ child.stdin.end(options.input ?? "");
+ });
+}
+
+function splitNul(buffer: Buffer): string[] {
+ return buffer.toString("utf8").split("\0").filter((item) => item.length > 0);
+}
+
+/** The workspace-relative path, checked (no `..`, no absolute paths, no reserved names). */
+function editorPath(input: unknown): string {
+ const path = normalizeWorkspaceRelativePath(String(input ?? ""), { allowSubdirs: true });
+ if (path === ".git" || path.startsWith(".git/")) throw new ApiError(400, "invalid_path", "The .git folder is not editable");
+ return path;
+}
+
+/** The file's absolute path inside the workspace; a symlinked folder that leads out of it is refused. */
+async function resolveInside(root: string, relativePath: string): Promise<string> {
+ const rootResolved = resolve(root);
+ const candidate = resolve(rootResolved, relativePath);
+ if (candidate === rootResolved || !candidate.startsWith(rootResolved + sep)) {
+ throw new ApiError(400, "invalid_path", "Path must point inside the workspace");
+ }
+ const rootReal = await realpath(rootResolved).catch(() => rootResolved);
+ // The nearest existing ancestor must stay inside the workspace once symlinks are followed.
+ let probe = candidate;
+ for (;;) {
+ const real = await realpath(probe).catch(() => null);
+ if (real !== null) {
+ if (real !== rootReal && !real.startsWith(rootReal + sep)) {
+ throw new ApiError(400, "invalid_path", "Path leads outside the workspace");
+ }
+ break;
+ }
+ const parent = dirname(probe);
+ if (parent === probe) break;
+ probe = parent;
+ }
+ return candidate;
+}
+
+function looksBinary(buffer: Buffer): boolean {
+ const end = Math.min(buffer.length, 8000);
+ for (let i = 0; i < end; i += 1) if (buffer[i] === 0) return true;
+ return false;
+}
+
+function sessionIdOf(value: unknown): string | null {
+ return typeof value === "string" && /^[A-Za-z0-9._:-]{8,128}$/.test(value) ? value : null;
+}
+
+function pathsOf(value: unknown): string[] {
+ if (!Array.isArray(value) || value.length === 0) throw new ApiError(400, "invalid_payload", "paths must be a non-empty array");
+ if (value.length > MAX_PATHS_PER_CALL) throw new ApiError(400, "invalid_payload", "Too many paths");
+ return value.map((item) => editorPath(item));
+}
+
+async function isGitWorkTree(root: string): Promise<boolean> {
+ const result = await runEditorGit(root, ["rev-parse", "--is-inside-work-tree"], { timeoutMs: 5_000 });
+ return result.code === 0 && result.stdout.toString("utf8").trim() === "true";
+}
+
+/** The project's files as git sees them: tracked and untracked, .gitignore'd ones left out. */
+async function gitTree(root: string): Promise<string[] | null> {
+ const listed = await runEditorGit(root, ["ls-files", "-z", "--cached", "--others", "--exclude-standard", "--deduplicate"]);
+ if (listed.code !== 0) return null;
+ const deleted = await runEditorGit(root, ["ls-files", "-z", "--deleted"]);
+ const gone = new Set(deleted.code === 0 ? splitNul(deleted.stdout) : []);
+ return splitNul(listed.stdout).filter((path) => !gone.has(path));
+}
+
+/** Without git: a walk that skips .git and node_modules and applies the .gitignore files it meets. */
+async function walkTree(root: string, limit: number): Promise<{ files: string[]; truncated: boolean }> {
+ const files: string[] = [];
+ let truncated = false;
+ const walk = async (dir: string, rules: string[]) => {
+ if (truncated) return;
+ const rel = relative(root, dir).replace(/\\/g, "/");
+ const local = await readFile(join(dir, ".gitignore"), "utf8").then(parseGitignoreRules).catch(() => [] as string[]);
+ const scoped = [...rules, ...scopedIgnoreRules(rel, local)];
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
+ entries.sort((a, b) => a.name.localeCompare(b.name));
+ for (const entry of entries) {
+ if (truncated) return;
+ const path = rel ? `${rel}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) {
+ if (WALK_SKIPPED_DIRECTORIES.has(entry.name) || ignoredByRules(`${path}/`, scoped)) continue;
+ await walk(join(dir, entry.name), scoped);
+ } else if (entry.isFile() || entry.isSymbolicLink()) {
+ if (ignoredByRules(path, scoped)) continue;
+ if (files.length >= limit) {
+ truncated = true;
+ return;
+ }
+ files.push(path);
+ }
+ }
+ };
+ await walk(root, []);
+ return { files, truncated };
+}
+
+export type EditorGitFile = {
+ path: string;
+ /** The rename's source path. */
+ from?: string;
+ /** Porcelain v1 letters: X (index) and Y (work tree), "?" for untracked. */
+ index: string;
+ worktree: string;
+};
+
+export type EditorGitStatus = {
+ repo: boolean;
+ branch: string | null;
+ upstream: string | null;
+ ahead: number;
+ behind: number;
+ files: EditorGitFile[];
+};
+
+/** `git status --porcelain=v1 -z -b` as data. */
+export function parsePorcelainStatus(output: string): Omit<EditorGitStatus, "repo"> {
+ const entries = output.split("\0");
+ let branch: string | null = null;
+ let upstream: string | null = null;
+ let ahead = 0;
+ let behind = 0;
+ const files: EditorGitFile[] = [];
+ for (let i = 0; i < entries.length; i += 1) {
+ const entry = entries[i]!;
+ if (!entry) continue;
+ if (entry.startsWith("## ")) {
+ const head = entry.slice(3);
+ const tracking = /^(.*?)(?:\.\.\.(\S+))?(?: \[(.*)\])?$/.exec(head);
+ const name = tracking?.[1] ?? head;
+ branch = name.startsWith("No commits yet on ") ? name.slice("No commits yet on ".length)
+ : name.startsWith("HEAD (no branch)") ? null
+ : name;
+ upstream = tracking?.[2] ?? null;
+ const counts = tracking?.[3] ?? "";
+ ahead = Number(/ahead (\d+)/.exec(counts)?.[1] ?? 0);
+ behind = Number(/behind (\d+)/.exec(counts)?.[1] ?? 0);
+ continue;
+ }
+ const index = entry[0] ?? " ";
+ const worktree = entry[1] ?? " ";
+ const path = entry.slice(3);
+ if (index === "R" || index === "C") {
+ const from = entries[i + 1] ?? "";
+ i += 1;
+ files.push({ path, from, index, worktree });
+ } else {
+ files.push({ path, index, worktree });
+ }
+ }
+ return { branch, upstream, ahead, behind, files };
+}
+
+async function gitStatus(root: string): Promise<EditorGitStatus> {
+ if (!(await isGitWorkTree(root))) return { repo: false, branch: null, upstream: null, ahead: 0, behind: 0, files: [] };
+ // Paths relative to the workspace folder (which may sit inside a larger repository).
+ const result = await runEditorGit(root, ["status", "--porcelain=v1", "-z", "-b", "--untracked-files=all", "--", "."]);
+ if (result.code !== 0) throw new ApiError(500, "git_failed", result.stderr.trim() || "git status failed");
+ const prefix = (await runEditorGit(root, ["rev-parse", "--show-prefix"], { timeoutMs: 5_000 })).stdout.toString("utf8").trim();
+ const parsed = parsePorcelainStatus(result.stdout.toString("utf8"));
+ const strip = (path: string) => (prefix && path.startsWith(prefix) ? path.slice(prefix.length) : path);
+ return {
+ repo: true,
+ ...parsed,
+ files: parsed.files
+ .filter((file) => !prefix || file.path.startsWith(prefix))
+ .map((file) => ({ ...file, path: strip(file.path), ...(file.from ? { from: strip(file.from) } : {}) }))
+ .sort((a, b) => a.path.localeCompare(b.path)),
+ };
+}
+
+export function registerEditorRoutes(options: RegisterEditorRoutesOptions): void {
+ const { routes, config, jsonResponse, readJsonBody, ensureWritable, requireApproval, requireClientScope, resolveWorkspace } = options;
+
+ addRoute(routes, "GET", "/workspace/:id/editor/tree", "client", async (ctx) => {
+ const workspace = await resolveWorkspace(config, ctx.params.id);
+ const root = resolve(workspace.path);
+ const info = await stat(root).catch(() => null);
+ if (!info?.isDirectory()) throw new ApiError(404, "workspace_not_found", "The workspace folder no longer exists.");
+ const git = await isGitWorkTree(root);
+ const listed = git ? await gitTree(root) : null;
+ let files: string[];
+ let truncated = false;
+ if (listed) {
+ files = listed.slice(0, EDITOR_MAX_TREE_FILES);
+ truncated = listed.length > files.length;
+ } else {
+ ({ files, truncated } = await walkTree(root, EDITOR_MAX_TREE_FILES));
+ }
+ files.sort((a, b) => a.localeCompare(b));
+ return jsonResponse({ git: Boolean(listed), files, truncated, generatedAt: Date.now() });
+ });
+
+ addRoute(routes, "GET", "/workspace/:id/editor/file", "client", async (ctx) => {
+ const workspace = await resolveWorkspace(config, ctx.params.id);
+ const path = editorPath(ctx.url.searchParams.get("path"));
+ const absolute = await resolveInside(workspace.path, path);
+ const info = await stat(absolute).catch(() => null);
+ if (!info?.isFile()) throw new ApiError(404, "file_not_found", "File not found");
+ if (info.size > EDITOR_MAX_FILE_BYTES) {
+ return jsonResponse({ path, content: null, tooLarge: true, bytes: info.size, maxBytes: EDITOR_MAX_FILE_BYTES, updatedAt: info.mtimeMs });
+ }
+ const buffer = await readFile(absolute);
+ if (looksBinary(buffer)) return jsonResponse({ path, content: null, binary: true, bytes: info.size, updatedAt: info.mtimeMs });
+ return jsonResponse({ path, content: buffer.toString("utf8"), bytes: info.size, updatedAt: info.mtimeMs });
+ });
+
+ addRoute(routes, "PUT", "/workspace/:id/editor/file", "client", async (ctx) => {
+ ensureWritable(config);
+ requireClientScope(ctx, "collaborator");
+ const workspace = await resolveWorkspace(config, ctx.params.id);
+ const body = await readJsonBody(ctx.request);
+ const path = editorPath(body.path);
+ const remove = body.delete === true;
+ if (!remove && typeof body.content !== "string") throw new ApiError(400, "invalid_payload", "content must be a string");
+ const content = remove ? "" : (body.content as string);
+ const bytes = Buffer.byteLength(content, "utf8");
+ if (bytes > EDITOR_MAX_FILE_BYTES) throw new ApiError(413, "file_too_large", "File exceeds size limit", { maxBytes: EDITOR_MAX_FILE_BYTES, size: bytes });
+ const baseUpdatedAt = typeof body.baseUpdatedAt === "number" && Number.isFinite(body.baseUpdatedAt) ? body.baseUpdatedAt : null;
+ const absolute = await resolveInside(workspace.path, path);
+ const current = await stat(absolute).catch(() => null);
+ if (current && !current.isFile()) throw new ApiError(400, "invalid_path", "Path must point to a file");
+ if (body.force !== true && current && baseUpdatedAt !== null && current.mtimeMs !== baseUpdatedAt) {
+ throw new ApiError(409, "conflict", "File changed on disk since it was opened", { baseUpdatedAt, currentUpdatedAt: current.mtimeMs });
+ }
+ const sessionId = sessionIdOf(body.sessionId);
+ // The text before the save, only when a tracked chat may want the change.
+ let before: string | null = null;
+ if (sessionId && options.onUserEdit && current && current.size <= EDITOR_MAX_FILE_BYTES) {
+ const buffer = await readFile(absolute).catch(() => null);
+ before = buffer && !looksBinary(buffer) ? buffer.toString("utf8") : null;
+ }
+ await requireApproval(ctx, {
+ workspaceId: workspace.id,
+ action: "workspace.file.write",
+ summary: remove ? `Delete ${path}` : `Write ${path}`,
+ paths: [absolute],
+ });
+ if (remove) {
+ await rm(absolute, { force: true });
+ } else {
+ await ensureDir(dirname(absolute));
+ const tmp = `${absolute}.tmp-${shortId()}`;
+ await writeFile(tmp, content, "utf8");
+ if (current) await chmod(tmp, current.mode & 0o7777).catch(() => undefined);
+ await rename(tmp, absolute);
+ }
+ const after = remove ? null : await stat(absolute);
+ // A file whose old text could not be read (binary, too large) is not reported.
+ if (sessionId && options.onUserEdit && (!current || before !== null)) {
+ const source = body.source === "review" ? "review" : "editor";
+ try {
+ options.onUserEdit({ workspace, sessionId, path, before, after: remove ? null : content, source });
+ } catch {
+ // Reporting never fails a save.
+ }
+ }
+ return jsonResponse({ ok: true, path, bytes, deleted: remove, updatedAt: after?.mtimeMs ?? null });
+ });
+
+ addRoute(routes, "POST", "/workspace/:id/editor/review", "client", async (ctx) => {
+ const workspace = await resolveWorkspace(config, ctx.params.id);
+ const body = await readJsonBody(ctx.request);
+ const sessionId = sessionIdOf(body.sessionId);
+ const path = editorPath(body.path);
+ const decision = body.decision === "accept" ? "accept" : body.decision === "reject" ? "reject" : null;
+ if (!sessionId || !decision) throw new ApiError(400, "invalid_payload", "sessionId and decision are required");
+ const count = (value: unknown) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : 0);
+ try {
+ options.onUserReview?.({ workspace, sessionId, path, decision, added: count(body.added), removed: count(body.removed), scope: body.scope === "file" ? "file" : "hunk" });
+ } catch {
+ // Reporting never fails the review.
+ }
+ return jsonResponse({ ok: true });
+ });
+
+ addRoute(routes, "GET", "/workspace/:id/editor/git/status", "client", async (ctx) => {
+ const workspace = await resolveWorkspace(config, ctx.params.id);
+ return jsonResponse(await gitStatus(resolve(workspace.path)));
+ });
+
+ addRoute(routes, "GET", "/workspace/:id/editor/git/original", "client", async (ctx) => {
+ const workspace = await resolveWorkspace(config, ctx.params.id);
+ const path = editorPath(ctx.url.searchParams.get("path"));
+ const ref = ctx.url.searchParams.get("ref") === "index" ? "index" : "HEAD";
+ const root = resolve(workspace.path);
+ // `./path` keeps the pathspec relative to the workspace folder inside a larger repository.
+ const spec = ref === "index" ? `:./${path}` : `HEAD:./${path}`;
+ const result = await runEditorGit(root, ["show", spec]);
+ if (result.code !== 0) return jsonResponse({ path, ref, content: null, exists: false });
+ if (result.stdout.length > EDITOR_MAX_FILE_BYTES) return jsonResponse({ path, ref, content: null, exists: true, tooLarge: true });
+ if (looksBinary(result.stdout)) return jsonResponse({ path, ref, content: null, exists: true, binary: true });
+ return jsonResponse({ path, ref, content: result.stdout.toString("utf8"), exists: true });
+ });
+
+ const gitWrite = async (ctx: RequestContext, summary: string) => {
+ ensureWritable(config);
+ requireClientScope(ctx, "collaborator");
+ const workspace = await resolveWorkspace(config, ctx.params.id);
+ const root = resolve(workspace.path);
+ if (!(await isGitWorkTree(root))) throw new ApiError(400, "not_a_repository", "This folder is not a git repository");
+ await requireApproval(ctx, { workspaceId: workspace.id, action: "workspace.git", summary, paths: [root] });
+ return root;
+ };
+ const gitFailure = (result: GitResult, fallback: string) =>
+ new ApiError(400, "git_failed", (result.stderr || result.stdout.toString("utf8")).trim().slice(0, 2_000) || fallback);
+
+ addRoute(routes, "POST", "/workspace/:id/editor/git/stage", "client", async (ctx) => {
+ const body = await readJsonBody(ctx.request);
+ const paths = pathsOf(body.paths);
+ const root = await gitWrite(ctx, `Stage ${paths.length} file(s)`);
+ const result = await runEditorGit(root, ["add", "-A", "--", ...paths.map((path) => `./${path}`)]);
+ if (result.code !== 0) throw gitFailure(result, "git add failed");
+ return jsonResponse(await gitStatus(root));
+ });
+
+ addRoute(routes, "POST", "/workspace/:id/editor/git/unstage", "client", async (ctx) => {
+ const body = await readJsonBody(ctx.request);
+ const paths = pathsOf(body.paths);
+ const root = await gitWrite(ctx, `Unstage ${paths.length} file(s)`);
+ const hasHead = (await runEditorGit(root, ["rev-parse", "--verify", "-q", "HEAD"], { timeoutMs: 5_000 })).code === 0;
+ const specs = paths.map((path) => `./${path}`);
+ const result = hasHead
+ ? await runEditorGit(root, ["reset", "-q", "HEAD", "--", ...specs])
+ : await runEditorGit(root, ["rm", "-r", "-q", "--cached", "--", ...specs]);
+ if (result.code !== 0) throw gitFailure(result, "git unstage failed");
+ return jsonResponse(await gitStatus(root));
+ });
+
+ addRoute(routes, "POST", "/workspace/:id/editor/git/commit", "client", async (ctx) => {
+ const body = await readJsonBody(ctx.request);
+ const message = typeof body.message === "string" ? body.message.replace(/\r\n/g, "\n").trim() : "";
+ if (!message) throw new ApiError(400, "invalid_payload", "A commit message is required");
+ if (message.length > COMMIT_MESSAGE_MAX) throw new ApiError(400, "invalid_payload", "The commit message is too long");
+ const root = await gitWrite(ctx, "Commit staged changes");
+ // The message goes in on stdin: never parsed as an option, any length.
+ const result = await runEditorGit(root, ["commit", "-q", "-F", "-"], { input: `${message}\n`, timeoutMs: 120_000 });
+ if (result.code !== 0) throw gitFailure(result, "git commit failed");
+ const head = await runEditorGit(root, ["rev-parse", "--short", "HEAD"], { timeoutMs: 5_000 });
+ return jsonResponse({ ok: true, commit: head.stdout.toString("utf8").trim(), status: await gitStatus(root) });
+ });
+}
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 6a27f143..15c3a297 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -118,6 +118,7 @@ import { serveStaticUi } from "./static-ui.js";
import { externalFetch, loopbackFetch } from "./server-fetch.js";
import { registerCoreRoutes } from "./routes/core.js";
import { registerFileRoutes } from "./routes/files.js";
+import { registerEditorRoutes } from "./routes/editor.js";
import { registerOperationRoutes } from "./routes/operations.js";
import { addRoute, matchRoute, type AuthMode, type RequestContext, type Route } from "./routes/registry.js";
import { registerSessionGroupRoutes } from "./routes/session-groups.js";
@@ -201,7 +202,8 @@ import { findManagedEngineWorkspace } from "./workspaces.js";
import { startThreadApprovalReplayer, type ThreadApprovalReplayer } from "./thread-approvals.js";
import { CloudProviderSync, parseCloudProviderDenSession } from "./cloud-provider-sync.js";
import { createEngineV2Preview, type EngineV2Preview } from "./engine-v2-preview.js";
-import { sessionUploaderEnabled } from "./session-uploader.js";
+import { isUploadFileDenied, sessionUploaderEnabled } from "./session-uploader.js";
+import { editorUserEditEvent, editorUserReviewEvent } from "./editor-events.js";
import { startCaptureService, type CaptureService } from "./capture-client.js";
import type { LateWritesGate } from "./capture-host.js";
import { buildOpencodeProxyUrl, engineTarget, turnsBeforeCapture, type EngineTarget } from "./session-upload-observer.js";
@@ -4664,6 +4666,31 @@ function createRoutes(
scopeRank,
});
+ // The desktop editor. A save or a hunk review that names a chat the session
+ // uploader is tracking adds a "user_edit" / "user_review" trace event to it;
+ // nothing else in a chat's upload changes (editor-events.ts).
+ registerEditorRoutes({
+ routes,
+ config,
+ jsonResponse,
+ readJsonBody,
+ ensureWritable,
+ requireApproval,
+ requireClientScope,
+ resolveWorkspace,
+ onUserEdit: (edit) => {
+ const capture = captureServicesByServer.get(config);
+ if (!capture?.uploadEnabled || !capture.hasSession(edit.sessionId) || isUploadFileDenied(edit.path)) return;
+ const event = editorUserEditEvent(edit);
+ if (event) capture.recordTrace(edit.sessionId, "user_edit", event);
+ },
+ onUserReview: (review) => {
+ const capture = captureServicesByServer.get(config);
+ if (!capture?.uploadEnabled || !capture.hasSession(review.sessionId) || isUploadFileDenied(review.path)) return;
+ capture.recordTrace(review.sessionId, "user_review", editorUserReviewEvent(review));
+ },
+ });
+
addRoute(routes, "GET", "/workspace/:id/plugins", "client", async (ctx) => {
const workspace = await resolveWorkspace(config, ctx.params.id);
const includeGlobal = ctx.url.searchParams.get("includeGlobal") === "true";
diff --git a/packages/types/src/omnirush-context.ts b/packages/types/src/omnirush-context.ts
index 09b51962..098bb36f 100644
--- a/packages/types/src/omnirush-context.ts
+++ b/packages/types/src/omnirush-context.ts
@@ -95,7 +95,7 @@ export const omnirushContextSnapshotSchema = z.object({
sidePanel: z.object({
open: z.boolean(),
ownerSessionId: z.string().nullable(),
- kind: z.enum(["panel", "extensions"]).nullable(),
+ kind: z.enum(["panel", "extensions", "editor"]).nullable(),
tabs: z.array(omnirushPanelTabSchema),
activeTabId: z.string().nullable(),
}),
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 11d98d2d..dda728ae 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -252,6 +252,9 @@ importers:
mermaid:
specifier: ^11.17.1
version: 11.17.1
+ monaco-editor:
+ specifier: 0.57.0
+ version: 0.57.0
motion:
specifier: ^12.38.0
@@ -6191,6 +6194,9 @@ packages:
resolution: {integrity: sha512-2vmYIoqjze2d+kakP8S/nS5shfsl587kzwEjcGlTdiksUVgFHnFCsLYDVj/JNqJVOQZGSYBTmuycv0PodwmnMQ==}
+ resolution: {integrity: sha512-EUBjM+B+lkDE41iE82DDSCfkoPGfXx8IxFxPMjNzm/Uk4xDet77rTN9wqlxlVg71kK7XGuUMv6wUxJUwwv+Xyw==}
+
resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==}
@@ -7460,6 +7466,11 @@ packages:
katex: '>=0.16 <0.18'
marked: '>=4 <19'
+ resolution: {integrity: sha512-uIj4+faQ+MgHgwUW1l2PsPglZLOLOT1uErt06dAPtx2kjteLAkbsd/0FiYg/MGS+i7ZKLb7w2WClxHkzOOuryQ==}
+ engines: {node: '>= 18'}
+ hasBin: true
+
resolution: {integrity: sha512-8dD6FusOQSrpv9Z1rdNMdlSgQOIP880DHqnohobOmYLElGEqAL/JvxvuxZO16r4HtjTlfPRDC1hbvxC9dPN2nA==}
engines: {node: '>= 18'}
@@ -7751,6 +7762,9 @@ packages:
resolution: {integrity: sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==}
+ resolution: {integrity: sha512-5BkI9KGoqrNvBGUe15/QlZq3OooZ8WLg1AxTpaqHRCP3HNpzPPZKE2EDz8M7c+VRmCeUw1Brp4cx/PWm3kI/5A==}
+
resolution: {integrity: sha512-7n6r7TtNOsH2UFSAXzTkfzOeO5616v9B178qBIjmu/WgEyJK0uqwytCEhwKBTuM/HJA40ptAw7hLFpxtPAMRZQ==}
@@ -14684,6 +14698,10 @@ snapshots:
optionalDependencies:
'@types/trusted-types': 2.0.7
+ optionalDependencies:
+ '@types/trusted-types': 2.0.7
+
dependencies:
dom-serializer: 2.0.0
@@ -15956,6 +15974,8 @@ snapshots:
katex: 0.18.1
marked: 17.0.1
+
@@ -16390,6 +16410,11 @@ snapshots:
+ dependencies:
+ dompurify: 3.4.15
+ marked: 14.0.0
+
dependencies:
motion-utils: 12.29.2