A desktop coding agent with free access to frontier models.
TypeScript
feat: editor settings page, auto save, format on save and git gutter
ogsamrat9365c735e98d
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.tsindex 1d22ab02..1df7b56a 100644--- a/apps/app/src/app/lib/omnirush-server.ts+++ b/apps/app/src/app/lib/omnirush-server.ts@@ -2846,6 +2846,24 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: ssignal,}),+ /** The formatters the project sets up itself (Prettier, gofmt, Ruff, Black, rustfmt), for Settings → Editor. */+ editorFormatters: (workspaceId: string) =>+ requestJson<{ formatters: string[] }>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/editor/formatters`, {+ token,+ hostToken,+ timeoutMs: 10_000,+ }),++ /** The project's formatter on the editor's text (a user action): the formatted text, or null when none is set up. */+ editorFormat: (workspaceId: string, path: string, text: string, timeoutMs = 3_000) =>+ requestJson<{ formatter: string | null; text: string | null }>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/editor/format`, {+ token,+ hostToken,+ method: "POST",+ body: { path, text },+ timeoutMs,+ }),+editorGitStatus: (workspaceId: string) =>requestJson<OmniRushEditorGitStatus>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/editor/git/status`, { token, hostToken, timeoutMs: 30_000 }),diff --git a/apps/app/src/app/types.ts b/apps/app/src/app/types.tsindex 7a4eb6d5..7eb0cc2f 100644--- a/apps/app/src/app/types.ts+++ b/apps/app/src/app/types.ts@@ -199,6 +199,7 @@ export const SETTINGS_TAB_VALUES = ["environment","advanced","appearance",+ "editor","voice","updates","recovery",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.tsindex 4b456321..0ceeb1af 100644--- a/apps/app/src/react-app/domains/session/editor/editor-models.ts+++ b/apps/app/src/react-app/domains/session/editor/editor-models.ts@@ -4,6 +4,7 @@* everywhere), when it was read, and whether it has unsaved changes. Kept* while the app runs, so closing the panel keeps unsaved text.*/+import { useEditorSettings } from "./editor-settings";import type * as MonacoApi from "monaco-editor/editor/editor.api.js";import { onFilesRewound } from "@/app/lib/files-rewound";@@ -72,6 +73,7 @@ export class EditorDocuments {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));+ model.detectIndentation(true, useEditorSettings.getState().tabSize);const doc: FileDoc = { path, model, updatedAt: file.updatedAt, savedVersion: model.getAlternativeVersionId(), conflict: false, missing: false };this.docs.set(path, doc);this.track(doc);@@ -93,6 +95,7 @@ export class EditorDocuments {const existing = this.docs.get(path);if (existing) return existing;const model = this.monaco.editor.createModel("", languageForPath(path), this.uri(path));+ model.updateOptions({ tabSize: useEditorSettings.getState().tabSize, insertSpaces: true });const doc: FileDoc = { path, model, updatedAt: null, savedVersion: model.getAlternativeVersionId(), conflict: false, missing: true };this.docs.set(path, doc);this.track(doc);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.tsxindex 171b6508..83831213 100644--- a/apps/app/src/react-app/domains/session/editor/editor-panel.tsx+++ b/apps/app/src/react-app/domains/session/editor/editor-panel.tsx@@ -70,6 +70,8 @@ import {import type { AgentAction, SurfaceHandle } from "./editor-surface";import { baselinesForTurns, turnFileChange, type TurnFileChange } from "./review";import "./editor.css";+import { AUTO_SAVE_DELAY_MS, useEditorSettings } from "./editor-settings";+import { GitGutter } from "./git-gutter";/** How long a file stays the active one before its language features start. */const LSP_DWELL_MS = 2500;@@ -542,6 +544,7 @@ export default function EditorPanel(props: EditorPanelProps) {const activeTab = state.tabs.find((tab) => tab.id === state.activeId) ?? null;const [surface, setSurface] = useState<SurfaceDoc | null>(null);const surfaceHandle = useRef<SurfaceHandle | null>(null);+ const [surfaceReady, setSurfaceReady] = useState(false);const pendingReveal = useRef<{ path: string; line: number; column: number; endColumn?: number } | null>(null);const [searchFocus, setSearchFocus] = useState(0);const [problemsLoading, setProblemsLoading] = useState(false);@@ -989,6 +992,21 @@ export default function EditorPanel(props: EditorPanelProps) {};}, [surface, lspActive, agentBusy]);+ // The git gutter for the file shown (git-gutter.ts): HEAD texts are read again when git's state changes.+ const gutter = useMemo(() => new GitGutter(client, workspaceId), [client, workspaceId]);+ const gitFiles = gitQuery.data?.repo ? gitQuery.data.files : null;+ useEffect(() => {+ gutter.reset();+ }, [gutter, gitQuery.dataUpdatedAt]);+ useEffect(() => {+ if (!surfaceReady || !surface || surface.kind !== "file" || !gitFiles) return;+ const editor = surfaceHandle.current?.activeEditor();+ if (!editor || editor.getModel() !== surface.doc.model) return;+ const doc = surface.doc;+ const changedInGit = gitFiles.some((file) => file.path === doc.path);+ return gutter.attach(editor, doc.model, doc.path, changedInGit, () => docs.isDirty(doc));+ }, [docs, gitFiles, gutter, surface, surfaceReady]);+// Breadcrumbs: the symbols around the cursor.useEffect(() => {if (!surface || surface.kind !== "file" || !cursor) {@@ -1008,11 +1026,47 @@ export default function EditorPanel(props: EditorPanelProps) {}, [cursor, surface, lspActive]);// ── save ───────────────────────────────────────────────────────────────- const save = useCallback(async (options: { force?: boolean } = {}) => {- if (!activeTab) return;- const path = activeTab.path;+ /** No formatter for these extensions in this project: said once. */+ const noFormatterNoted = useRef(new Set<string>());+ /**+ * Format on save: the project's own formatter on the buffer's text, applied as one undoable edit before writing.+ * A formatter that fails or takes longer than 3 s never blocks the save: the file is saved as it is.+ */+ const formatBeforeSave = useCallback(async (path: string) => {+ const doc = docs.get(path);+ if (!doc) return;+ const model = doc.model;+ const version = model.getAlternativeVersionId();+ const extension = path.includes(".") ? path.slice(path.lastIndexOf(".")) : path;+ try {+ const outcome = await client.editorFormat(workspaceId, path, model.getValue(), 3_000);+ if (outcome.formatter === null || outcome.text === null) {+ if (!noFormatterNoted.current.has(extension)) {+ noFormatterNoted.current.add(extension);+ toast(`No formatter set up for ${extension} files in this project; saved as is.`);+ }+ return;+ }+ // Typed while the formatter ran: that text wins, unformatted.+ if (model.getAlternativeVersionId() !== version || outcome.text === model.getValue()) return;+ model.pushStackElement();+ model.pushEditOperations([], [{ range: model.getFullModelRange(), text: outcome.text }], () => null);+ model.pushStackElement();+ } catch {+ toast("Couldn't format this file; it was saved as is.");+ }+ }, [client, docs, workspaceId]);++ /**+ * Saves one file. `manual` (Cmd/Ctrl+S, Save) and `focus` (auto save when focus leaves) also run the project's+ * formatter when Format on save is on; `delay` (auto save after a delay) never formats. A file that changed on+ * disk since it was loaded is never overwritten by an automatic save: it shows the Reload / Keep mine choice.+ */+ const saveFile = useCallback(async (path: string, trigger: "manual" | "delay" | "focus", options: { force?: boolean } = {}) => {const doc = docs.get(path);if (!doc) return;+ if (trigger !== "manual" && (doc.conflict || !docs.isDirty(doc))) return;+ if (useEditorSettings.getState().formatOnSave && trigger !== "delay") await formatBeforeSave(path);const result = await docs.save(path, { sessionId, source: "editor", force: options.force });if (result.ok) {void refreshFileDiagnostics(path);@@ -1021,11 +1075,61 @@ export default function EditorPanel(props: EditorPanelProps) {return;}if (result.conflict) {- showConflict(path, { reload: () => void docs.revert(path), overwrite: () => void save({ force: true }), reason: "save" });+ doc.conflict = true;+ showConflict(path, { reload: () => void docs.revert(path), overwrite: () => void saveFile(path, "manual", { force: true }), reason: "save" });return;}toast.error(result.message);- }, [activeTab, docs, files, queryClient, sessionId, workspaceId]);+ }, [docs, files, formatBeforeSave, queryClient, sessionId, workspaceId]);++ const save = useCallback(async (options: { force?: boolean } = {}) => {+ if (!activeTab) return;+ await saveFile(activeTab.path, "manual", options);+ }, [activeTab, saveFile]);++ // Auto save. After a delay: a second after the last edit of a file, held while any chat's agent works (saved when+ // the turn ends). When focus leaves: the editor or the window losing focus. Both skip files in conflict.+ const autoSave = useEditorSettings((state) => state.autoSave);+ const autoSaveTimers = useRef(new Map<string, number>());+ const heldForAgent = useRef(new Set<string>());+ const agentBusyRef = useRef(agentBusy);+ useEffect(() => {+ if (autoSave !== "afterDelay" || !surface || surface.kind !== "file") return;+ const doc = surface.doc;+ const subscription = doc.model.onDidChangeContent(() => {+ const timers = autoSaveTimers.current;+ window.clearTimeout(timers.get(doc.path));+ timers.set(doc.path, window.setTimeout(() => {+ timers.delete(doc.path);+ if (agentBusyRef.current) heldForAgent.current.add(doc.path);+ else void saveFile(doc.path, "delay");+ }, AUTO_SAVE_DELAY_MS));+ });+ return () => subscription.dispose();+ }, [autoSave, saveFile, surface]);+ useEffect(() => {+ agentBusyRef.current = agentBusy;+ if (agentBusy || !heldForAgent.current.size) return;+ const held = [...heldForAgent.current];+ heldForAgent.current.clear();+ for (const path of held) void saveFile(path, "delay");+ }, [agentBusy, saveFile]);+ useEffect(() => {+ if (autoSave !== "onFocusChange") return;+ const saveDirty = () => {+ for (const path of Object.keys(useEditorStore.getState().dirty[workspaceId] ?? {})) void saveFile(path, "focus");+ };+ const onBlur = () => saveDirty();+ window.addEventListener("blur", onBlur);+ window.addEventListener("omnirush:editor-blur", onBlur);+ return () => {+ window.removeEventListener("blur", onBlur);+ window.removeEventListener("omnirush:editor-blur", onBlur);+ };+ }, [autoSave, saveFile, workspaceId]);+ useEffect(() => () => {+ for (const timer of autoSaveTimers.current.values()) window.clearTimeout(timer);+ }, []);// ── git ────────────────────────────────────────────────────────────────const stage = useCallback(async (paths: string[], doStage: boolean) => {@@ -1270,6 +1374,7 @@ export default function EditorPanel(props: EditorPanelProps) {onAgentAction={agentAction}onReady={(handle) => {surfaceHandle.current = handle;+ setSurfaceReady(Boolean(handle));}}/></div>diff --git a/apps/app/src/react-app/domains/session/editor/editor-settings.ts b/apps/app/src/react-app/domains/session/editor/editor-settings.tsnew file mode 100644index 00000000..5a1de2b3--- /dev/null+++ b/apps/app/src/react-app/domains/session/editor/editor-settings.ts@@ -0,0 +1,89 @@+/**+ * The code editor's settings (Settings → Editor): text, saving and keys. One set for every project on this+ * computer, kept in localStorage. Language features stay in the editor store (`languageFeatures`).+ */+import { create } from "zustand";+import { createJSONStorage, persist } from "zustand/middleware";++export type AutoSave = "off" | "afterDelay" | "onFocusChange";++export type EditorSettings = {+ fontSize: number;+ /** Used when a file shows no indentation of its own. */+ tabSize: 2 | 4 | 8;+ wordWrap: boolean;+ minimap: boolean;+ stickyScroll: boolean;+ autoSave: AutoSave;+ formatOnSave: boolean;+};++export const DEFAULT_EDITOR_SETTINGS: EditorSettings = {+ fontSize: 13,+ tabSize: 4,+ wordWrap: false,+ minimap: false,+ stickyScroll: true,+ autoSave: "off",+ formatOnSave: false,+};++export const EDITOR_FONT_SIZES = [12, 13, 14, 15, 16, 18, 20, 22, 24] as const;+/** "After a delay": this long after the last keystroke. */+export const AUTO_SAVE_DELAY_MS = 1000;++type EditorSettingsStore = EditorSettings & {+ set: <K extends keyof EditorSettings>(key: K, value: EditorSettings[K]) => void;+ reset: () => void;+};++export const useEditorSettings = create<EditorSettingsStore>()(+ persist(+ (set) => ({+ ...DEFAULT_EDITOR_SETTINGS,+ set: (key, value) => set({ [key]: value } as Pick<EditorSettings, typeof key>),+ reset: () => set(DEFAULT_EDITOR_SETTINGS),+ }),+ {+ name: "omnirush:editor-settings:v1",+ storage: createJSONStorage(() => localStorage),+ partialize: ({ fontSize, tabSize, wordWrap, minimap, stickyScroll, autoSave, formatOnSave }) => ({+ fontSize, tabSize, wordWrap, minimap, stickyScroll, autoSave, formatOnSave,+ }),+ },+ ),+);++/** Monaco options for the current settings (editor-level; tab size applies per model). */+export function monacoOptionsFor(settings: EditorSettings) {+ return {+ fontSize: settings.fontSize,+ lineHeight: Math.round(settings.fontSize * 1.5),+ wordWrap: settings.wordWrap ? ("on" as const) : ("off" as const),+ minimap: { enabled: settings.minimap },+ stickyScroll: { enabled: settings.stickyScroll, maxLineCount: 3, defaultModel: "indentationModel" as const },+ };+}++/** The editor keys, VS Code's defaults (the Keys list in Settings → Editor). */+export const EDITOR_SHORTCUTS: Array<{ keys: string; action: string }> = [+ { keys: "Cmd/Ctrl+P", action: "Go to file" },+ { keys: "Cmd/Ctrl+Shift+P", action: "Command palette" },+ { keys: "Cmd/Ctrl+Shift+F", action: "Search in files" },+ { keys: "Cmd/Ctrl+Shift+O", action: "Go to symbol in file" },+ { keys: "F12 / Cmd/Ctrl+click", action: "Go to definition" },+ { keys: "Shift+F12", action: "Find references" },+ { keys: "F2", action: "Rename symbol" },+ { keys: "F8", action: "Next problem" },+ { keys: "Cmd/Ctrl+S", action: "Save" },+ { keys: "Cmd/Ctrl+\\", action: "Split editor" },+ { keys: "Cmd/Ctrl+K Cmd/Ctrl+Left / Right", action: "Focus the other editor group" },+ { keys: "Cmd/Ctrl+K V", action: "Markdown preview in the other group" },+ { keys: "Cmd/Ctrl+Shift+V", action: "Markdown preview in this group" },+ { keys: "Cmd/Ctrl+L", action: "Ask about selection" },+ { keys: "Cmd/Ctrl+J", action: "Show or hide the bottom panel" },+ { keys: "Ctrl+`", action: "Terminal" },+ { keys: "Cmd/Ctrl+F / Cmd/Ctrl+H", action: "Find / replace in file" },+ { keys: "Cmd/Ctrl+/", action: "Toggle line comment" },+ { keys: "Alt+Up / Alt+Down", action: "Move line" },+];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.tsxindex 5104cc56..53c3a667 100644--- a/apps/app/src/react-app/domains/session/editor/editor-surface.tsx+++ b/apps/app/src/react-app/domains/session/editor/editor-surface.tsx@@ -12,6 +12,7 @@ import { subscribeToTheme } from "@/app/theme";import { applyMonacoTheme, monacoThemeName, type Monaco } from "./monaco";import type { FileDoc } from "./editor-models";import { hunkCounts, type LineHunk } from "./hunk-ops";+import { monacoOptionsFor, useEditorSettings } from "./editor-settings";export type SurfaceDoc =| { kind: "file"; key: string; doc: FileDoc }@@ -52,15 +53,12 @@ export type SurfaceHandle = {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 },- // Indentation, not the outline: the outline would ask the language servers for symbols as soon as a file opens.- stickyScroll: { enabled: true, maxLineCount: 3, defaultModel: "indentationModel" },+ // Font size, wrap, minimap and sticky scroll come from Settings → Editor (editor-settings.ts). Sticky scroll uses+ // indentation, not the outline: the outline would ask the language servers for symbols as soon as a file opens.// Large files stay responsive: no tokenisation past 20k chars per line, no word-based suggestions on huge files.maxTokenizationLineLength: 20_000,wordBasedSuggestions: "currentDocument",@@ -132,9 +130,11 @@ export function EditorSurface({ monaco, surface, onSave, onCursor, onHunks, naviuseEffect(() => {if (!codeHostRef.current || !diffHostRef.current) return;const themeName = monacoThemeName();- const code = monaco.editor.create(codeHostRef.current, { ...BASE_OPTIONS, model: null, theme: themeName });+ const settingsOptions = monacoOptionsFor(useEditorSettings.getState());+ const code = monaco.editor.create(codeHostRef.current, { ...BASE_OPTIONS, ...settingsOptions, model: null, theme: themeName });const diff = monaco.editor.createDiffEditor(diffHostRef.current, {...BASE_OPTIONS,+ ...settingsOptions,theme: themeName,renderSideBySide: false,useInlineViewWhenSpaceIsLimited: true,@@ -179,6 +179,16 @@ export function EditorSurface({ monaco, surface, onSave, onCursor, onHunks, navi},activeEditor: () => (modeRef.current === "diff" ? diff.getModifiedEditor() : modeRef.current === "file" ? code : null),});+ // Auto save "when focus leaves": the panel listens for this.+ const blurEvent = () => window.dispatchEvent(new Event("omnirush:editor-blur"));+ disposables.push(code.onDidBlurEditorWidget(blurEvent), diff.getModifiedEditor().onDidBlurEditorWidget(blurEvent));+ // Settings → Editor, live.+ const unsubscribeSettings = useEditorSettings.subscribe((settings, previous) => {+ const next = monacoOptionsFor(settings);+ if (JSON.stringify(next) === JSON.stringify(monacoOptionsFor(previous))) return;+ code.updateOptions(next);+ diff.updateOptions(next);+ });// Follows the app theme: light/dark, presets and custom themes (app/theme.ts).const unsubscribeTheme = subscribeToTheme(() => {applyMonacoTheme();@@ -192,6 +202,7 @@ export function EditorSurface({ monaco, surface, onSave, onCursor, onHunks, naviif (key) VIEW_STATES.set(key, modeRef.current === "diff" ? diff.saveViewState() : code.saveViewState());onReadyRef.current?.(null);unsubscribeTheme();+ unsubscribeSettings();for (const disposable of disposables) disposable.dispose();code.dispose();diff.dispose();diff --git a/apps/app/src/react-app/domains/session/editor/editor.css b/apps/app/src/react-app/domains/session/editor/editor.cssindex e77a2d52..d0f5b5cf 100644--- a/apps/app/src/react-app/domains/session/editor/editor.css+++ b/apps/app/src/react-app/domains/session/editor/editor.css@@ -27,3 +27,29 @@.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); }.omnirush-hunk-bar-busy { opacity: 0.55; pointer-events: none; }++/* Git gutter (git-gutter.ts): added = solid bar, changed = striped bar, removed = wedge. Read-only: no pointer. */+.monaco-editor .omnirush-gutter-add,+.monaco-editor .omnirush-gutter-change {+ margin-left: 3px;+ width: 3px !important;+}+.monaco-editor .omnirush-gutter-add { background: var(--omnirush-success, #30a46c); }+.monaco-editor .omnirush-gutter-change {+ background: repeating-linear-gradient(+ to bottom,+ var(--blue-9, #0090ff) 0 3px,+ transparent 3px 5px+ );+}+.monaco-editor .omnirush-gutter-delete::after,+.monaco-editor .omnirush-gutter-delete-top::after {+ content: "";+ position: absolute;+ left: 2px;+ border-left: 5px solid var(--destructive, #e5484d);+ border-top: 4px solid transparent;+ border-bottom: 4px solid transparent;+}+.monaco-editor .omnirush-gutter-delete::after { bottom: -4px; }+.monaco-editor .omnirush-gutter-delete-top::after { top: -4px; }diff --git a/apps/app/src/react-app/domains/session/editor/git-gutter.ts b/apps/app/src/react-app/domains/session/editor/git-gutter.tsnew file mode 100644index 00000000..878dcbcc--- /dev/null+++ b/apps/app/src/react-app/domains/session/editor/git-gutter.ts@@ -0,0 +1,99 @@+/**+ * The git gutter: marks next to lines added (solid bar), changed (striped bar) or removed (wedge) since HEAD, for+ * the text in the editor including unsaved changes. Read-only in this batch. Nothing for files git does not track,+ * binary or very large files, or folders that are not repositories. The diff runs in a worker, started on first use.+ */+import type * as MonacoApi from "monaco-editor/editor/editor.api.js";++import type { OmniRushServerClient } from "@/app/lib/omnirush-server";+import { gutterLabel, type GutterMark } from "./line-diff";++const MAX_CHARS = 2_000_000;+const DEBOUNCE_MS = 300;++let worker: Worker | null = null;+let nextId = 0;+const pending = new Map<number, (marks: GutterMark[] | null) => void>();++function diffInWorker(head: string, current: string): Promise<GutterMark[] | null> {+ if (!worker) {+ worker = new Worker(new URL("./line-diff.worker.ts", import.meta.url), { type: "module" });+ worker.onmessage = (event: MessageEvent<{ id: number; marks: GutterMark[] | null }>) => {+ pending.get(event.data.id)?.(event.data.marks);+ pending.delete(event.data.id);+ };+ }+ const id = (nextId += 1);+ return new Promise((resolve) => {+ pending.set(id, resolve);+ worker!.postMessage({ id, head, current });+ });+}++/** HEAD text per workspace file; dropped when git's state changes (a commit, checkout, stage). */+export class GitGutter {+ private heads = new Map<string, Promise<string | null>>();++ constructor(private client: OmniRushServerClient, private workspaceId: string) {}++ /** Git's state changed: HEAD texts are read again. */+ reset() {+ this.heads.clear();+ }++ private head(path: string): Promise<string | null> {+ let head = this.heads.get(path);+ if (!head) {+ head = this.client.editorGitOriginal(this.workspaceId, path, "HEAD").then(+ (file) => (file.exists && !file.binary && !file.tooLarge && typeof file.content === "string" ? file.content : null),+ () => null,+ );+ this.heads.set(path, head);+ }+ return head;+ }++ /** Marks for `model` (the file `path`) in `editor`, kept up to date while it is shown. */+ attach(editor: MonacoApi.editor.ICodeEditor, model: MonacoApi.editor.ITextModel, path: string, changedInGit: boolean, isDirty: () => boolean): () => void {+ const decorations = editor.createDecorationsCollection();+ let timer = 0;+ let disposed = false;+ let generation = 0;+ const update = async () => {+ const mine = (generation += 1);+ // Not changed in git and not edited here: nothing to mark, nothing to fetch.+ if (!changedInGit && !isDirty()) {+ decorations.clear();+ return;+ }+ const head = await this.head(path);+ const current = model.getValue();+ if (disposed || mine !== generation) return;+ if (head === null || head.length > MAX_CHARS || current.length > MAX_CHARS) {+ decorations.clear();+ return;+ }+ const marks = await diffInWorker(head, current);+ if (disposed || mine !== generation || model.isDisposed()) return;+ decorations.set((marks ?? []).map((mark) => ({+ range: { startLineNumber: Math.max(1, mark.startLine), startColumn: 1, endLineNumber: Math.max(1, mark.endLine), endColumn: 1 },+ options: {+ isWholeLine: true,+ linesDecorationsClassName: mark.kind === "add" ? "omnirush-gutter-add" : mark.kind === "change" ? "omnirush-gutter-change" : mark.startLine === 0 ? "omnirush-gutter-delete-top" : "omnirush-gutter-delete",+ linesDecorationsTooltip: gutterLabel(mark),+ },+ })));+ };+ void update();+ const subscription = model.onDidChangeContent(() => {+ window.clearTimeout(timer);+ timer = window.setTimeout(() => void update(), DEBOUNCE_MS);+ });+ return () => {+ disposed = true;+ window.clearTimeout(timer);+ subscription.dispose();+ decorations.clear();+ };+ }+}diff --git a/apps/app/src/react-app/domains/session/editor/line-diff.ts b/apps/app/src/react-app/domains/session/editor/line-diff.tsnew file mode 100644index 00000000..32349420--- /dev/null+++ b/apps/app/src/react-app/domains/session/editor/line-diff.ts@@ -0,0 +1,145 @@+/**+ * Line diff for the editor's git gutter: which lines of the current text were added or changed since HEAD, and+ * where lines were removed. Myers' O(ND) diff on whole lines, with a cap so a huge rewrite costs a bounded amount.+ */+export type GutterMark = {+ kind: "add" | "change" | "delete";+ /** 1-based line range in the current text. A deletion sits on the line before the removed lines (0 = top). */+ startLine: number;+ endLine: number;+ /** Lines removed from HEAD at this spot (change and delete). */+ removed: number;+};++/** Beyond this many differing lines the gutter gives up (null): a whole-file rewrite needs no per-line marks. */+export const MAX_EDIT_DISTANCE = 4_000;++type Edit = { kind: "equal" | "insert" | "delete"; count: number };++/** Myers diff of two line arrays as runs of equal / inserted / deleted lines, or null past the cap. */+export function diffLines(before: readonly string[], after: readonly string[], maxD = MAX_EDIT_DISTANCE): Edit[] | null {+ // Common prefix and suffix first: most edits touch a small region.+ let prefix = 0;+ while (prefix < before.length && prefix < after.length && before[prefix] === after[prefix]) prefix += 1;+ let suffix = 0;+ while (+ suffix < before.length - prefix+ && suffix < after.length - prefix+ && before[before.length - 1 - suffix] === after[after.length - 1 - suffix]+ ) suffix += 1;+ const a = before.slice(prefix, before.length - suffix);+ const b = after.slice(prefix, after.length - suffix);+ const n = a.length;+ const m = b.length;+ const middle: Edit[] = [];+ if (n === 0 && m > 0) middle.push({ kind: "insert", count: m });+ else if (m === 0 && n > 0) middle.push({ kind: "delete", count: n });+ else if (n > 0 && m > 0) {+ const max = n + m;+ const offset = max;+ const v = new Int32Array(2 * max + 2);+ const trace: Int32Array[] = [];+ let found = -1;+ for (let d = 0; d <= Math.min(max, maxD); d += 1) {+ trace.push(v.slice());+ 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;+ // Walk back through the trace.+ const steps: Array<"equal" | "insert" | "delete"> = [];+ let x = n;+ let y = m;+ for (let d = found; d > 0; d -= 1) {+ const vd = trace[d]!;+ const k = x - y;+ const prevK = k === -d || (k !== d && vd[offset + k - 1]! < vd[offset + k + 1]!) ? k + 1 : k - 1;+ const prevX = vd[offset + prevK]!;+ const prevY = prevX - prevK;+ while (x > prevX && y > prevY) {+ steps.push("equal");+ x -= 1;+ y -= 1;+ }+ steps.push(x === prevX ? "insert" : "delete");+ x = prevX;+ y = prevY;+ }+ while (x > 0 && y > 0) {+ steps.push("equal");+ x -= 1;+ y -= 1;+ }+ steps.reverse();+ for (const step of steps) {+ const last = middle[middle.length - 1];+ if (last && last.kind === step) last.count += 1;+ else middle.push({ kind: step, count: 1 });+ }+ }+ const edits: Edit[] = [];+ if (prefix) edits.push({ kind: "equal", count: prefix });+ edits.push(...middle);+ if (suffix) edits.push({ kind: "equal", count: suffix });+ return edits;+}++/** Gutter marks for the current text against HEAD, or null when the difference is too large to mark line by line. */+export function gutterMarks(head: string, current: string): GutterMark[] | null {+ const edits = diffLines(splitLines(head), splitLines(current));+ if (!edits) return null;+ const marks: GutterMark[] = [];+ let line = 0; // lines of the current text consumed+ for (let i = 0; i < edits.length; i += 1) {+ const edit = edits[i]!;+ if (edit.kind === "equal") {+ line += edit.count;+ continue;+ }+ // A delete followed by an insert (or the reverse) is a change of the overlapping lines.+ const next = edits[i + 1];+ const removed = edit.kind === "delete" ? edit.count : next?.kind === "delete" ? next.count : 0;+ const added = edit.kind === "insert" ? edit.count : next?.kind === "insert" ? next.count : 0;+ if (next && next.kind !== "equal") i += 1;+ if (added && removed) {+ const changed = Math.min(added, removed);+ marks.push({ kind: "change", startLine: line + 1, endLine: line + changed, removed });+ if (added > changed) marks.push({ kind: "add", startLine: line + changed + 1, endLine: line + added, removed: 0 });+ line += added;+ } else if (added) {+ marks.push({ kind: "add", startLine: line + 1, endLine: line + added, removed: 0 });+ line += added;+ } else {+ marks.push({ kind: "delete", startLine: line, endLine: line, removed });+ }+ }+ return marks;+}++function splitLines(text: string): string[] {+ const lines = text.split(/\r\n|\r|\n/);+ // A final newline is not an extra empty line.+ if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop();+ return lines;+}++/** The hover text of a mark. */+export function gutterLabel(mark: GutterMark): string {+ const count = mark.endLine - mark.startLine + 1;+ const lines = (n: number) => `${n} line${n === 1 ? "" : "s"}`;+ if (mark.kind === "add") return `${lines(count)} added since the last commit`;+ if (mark.kind === "change") return `${lines(count)} changed since the last commit`;+ return `${lines(mark.removed)} removed here since the last commit`;+}diff --git a/apps/app/src/react-app/domains/session/editor/line-diff.worker.ts b/apps/app/src/react-app/domains/session/editor/line-diff.worker.tsnew file mode 100644index 00000000..09854257--- /dev/null+++ b/apps/app/src/react-app/domains/session/editor/line-diff.worker.ts@@ -0,0 +1,8 @@+/// <reference lib="webworker" />+/** The git gutter's diff, off the main thread (line-diff.ts). */+import { gutterMarks } from "./line-diff";++self.onmessage = (event: MessageEvent<{ id: number; head: string; current: string }>) => {+ const { id, head, current } = event.data;+ self.postMessage({ id, marks: gutterMarks(head, current) });+};diff --git a/apps/app/src/react-app/domains/settings/pages/editor-settings-view.tsx b/apps/app/src/react-app/domains/settings/pages/editor-settings-view.tsxnew file mode 100644index 00000000..665b8dc1--- /dev/null+++ b/apps/app/src/react-app/domains/settings/pages/editor-settings-view.tsx@@ -0,0 +1,232 @@+/** @jsxImportSource react */+/** Settings → Editor: the IDE layout's code editor (text, saving, language features, keys). */+import { useEffect, useMemo, useState } from "react";++import type { OmniRushServerClient } from "@/app/lib/omnirush-server";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Separator } from "@/components/ui/separator";+import { Switch } from "@/components/ui/switch";+import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";+import { useEditorStore } from "../../session/editor/editor-store";+import {+ EDITOR_FONT_SIZES,+ EDITOR_SHORTCUTS,+ useEditorSettings,+ type AutoSave,+ type EditorSettings,+} from "../../session/editor/editor-settings";+import {+ LayoutSection,+ LayoutSectionDescription,+ LayoutSectionHeader,+ LayoutSectionItem,+ LayoutSectionItemDescription,+ LayoutSectionItemHeader,+ LayoutSectionItemHeaderActions,+ LayoutSectionItemTitle,+ LayoutSectionTitle,+ LayoutStack,+} from "../settings-layout";++const SEGMENT =+ "h-7 rounded-md border border-transparent px-3 text-sm text-muted-foreground aria-pressed:border-foreground/70 aria-pressed:bg-background aria-pressed:font-medium aria-pressed:text-foreground aria-pressed:shadow-xs";+const GROUP = "w-fit gap-0.5 rounded-lg border border-border bg-muted/40 p-0.5";++function SwitchRow(props: { title: string; description: string; checked: boolean; onChange: (value: boolean) => void; id: string }) {+ return (+ <LayoutSectionItem>+ <LayoutSectionItemHeader>+ <LayoutSectionItemTitle>+ <label htmlFor={props.id}>{props.title}</label>+ </LayoutSectionItemTitle>+ <LayoutSectionItemDescription>{props.description}</LayoutSectionItemDescription>+ <LayoutSectionItemHeaderActions>+ <Switch id={props.id} aria-label={props.title} checked={props.checked} onCheckedChange={props.onChange} />+ </LayoutSectionItemHeaderActions>+ </LayoutSectionItemHeader>+ </LayoutSectionItem>+ );+}++/** Which formatters the open project has, for the "Format on save" row. */+function useProjectFormatters(client: OmniRushServerClient | null, workspaceId: string | null) {+ const [names, setNames] = useState<string[] | null>(null);+ useEffect(() => {+ let cancelled = false;+ setNames(null);+ if (!client || !workspaceId) return;+ client.editorFormatters(workspaceId).then(+ (result) => {+ if (!cancelled) setNames(result.formatters);+ },+ () => undefined,+ );+ return () => {+ cancelled = true;+ };+ }, [client, workspaceId]);+ return names;+}++export function EditorSettingsView(props: { client: OmniRushServerClient | null; workspaceId: string | null }) {+ const settings = useEditorSettings();+ const languageFeatures = useEditorStore((state) => state.languageFeatures);+ const setLanguageFeatures = useEditorStore((state) => state.setLanguageFeatures);+ const formatters = useProjectFormatters(props.client, props.workspaceId);+ const [keysOpen, setKeysOpen] = useState(false);+ const [filter, setFilter] = useState("");+ const set = <K extends keyof EditorSettings>(key: K, value: EditorSettings[K]) => settings.set(key, value);+ const shortcuts = useMemo(() => {+ const needle = filter.trim().toLowerCase();+ return needle ? EDITOR_SHORTCUTS.filter((item) => `${item.keys} ${item.action}`.toLowerCase().includes(needle)) : EDITOR_SHORTCUTS;+ }, [filter]);++ const formatterNote = !props.workspaceId+ ? "Open a project to see its formatter."+ : formatters === null+ ? "Looking for the project's formatter…"+ : formatters.length+ ? `This project: ${formatters.join(", ")}.`+ : "This project: none found. Files are saved as they are.";++ return (+ <LayoutStack>+ <LayoutSection>+ <LayoutSectionHeader>+ <LayoutSectionTitle>Text</LayoutSectionTitle>+ <LayoutSectionDescription>The code editor in the IDE layout, for every project on this computer.</LayoutSectionDescription>+ </LayoutSectionHeader>+ <LayoutSectionItem>+ <LayoutSectionItemHeader>+ <LayoutSectionItemTitle>+ <label htmlFor="editor-font-size">Font size</label>+ </LayoutSectionItemTitle>+ <LayoutSectionItemDescription>Text size in the editor.</LayoutSectionItemDescription>+ <LayoutSectionItemHeaderActions>+ <select+ id="editor-font-size"+ value={settings.fontSize}+ onChange={(event) => set("fontSize", Number(event.target.value))}+ className="h-8 rounded-md border border-border bg-background px-2 text-sm"+ data-editor-setting="fontSize"+ >+ {EDITOR_FONT_SIZES.map((size) => <option key={size} value={size}>{size} px</option>)}+ </select>+ </LayoutSectionItemHeaderActions>+ </LayoutSectionItemHeader>+ </LayoutSectionItem>+ <LayoutSectionItem>+ <LayoutSectionItemHeader className="w-full">+ <LayoutSectionItemTitle>Tab size</LayoutSectionItemTitle>+ <LayoutSectionItemDescription>For files without indentation of their own; others keep theirs.</LayoutSectionItemDescription>+ </LayoutSectionItemHeader>+ <ToggleGroup+ value={[String(settings.tabSize)]}+ onValueChange={(value) => value[0] && set("tabSize", Number(value[0]) as EditorSettings["tabSize"])}+ aria-label="Tab size"+ className={GROUP}+ >+ {["2", "4", "8"].map((size) => (+ <ToggleGroupItem key={size} value={size} aria-label={`${size} spaces`} className={SEGMENT}>{size}</ToggleGroupItem>+ ))}+ </ToggleGroup>+ </LayoutSectionItem>+ <SwitchRow id="editor-word-wrap" title="Word wrap" description="Long lines wrap at the editor's edge." checked={settings.wordWrap} onChange={(value) => set("wordWrap", value)} />+ <SwitchRow id="editor-minimap" title="Minimap" description="A small overview of the file at the right edge." checked={settings.minimap} onChange={(value) => set("minimap", value)} />+ <SwitchRow id="editor-sticky-scroll" title="Sticky scroll" description="The first lines of the block you are in stay at the top while you scroll." checked={settings.stickyScroll} onChange={(value) => set("stickyScroll", value)} />+ </LayoutSection>++ <Separator />++ <LayoutSection>+ <LayoutSectionHeader>+ <LayoutSectionTitle>Saving</LayoutSectionTitle>+ <LayoutSectionDescription>Automatic saves count as your own edits, like Cmd/Ctrl+S. A file the agent changed is never overwritten.</LayoutSectionDescription>+ </LayoutSectionHeader>+ <LayoutSectionItem>+ <LayoutSectionItemHeader className="w-full">+ <LayoutSectionItemTitle>Auto save</LayoutSectionItemTitle>+ <LayoutSectionItemDescription>After a delay: one second after you stop typing. When focus leaves: when you click away from the editor.</LayoutSectionItemDescription>+ </LayoutSectionItemHeader>+ <ToggleGroup+ value={[settings.autoSave]}+ onValueChange={(value) => value[0] && set("autoSave", value[0] as AutoSave)}+ aria-label="Auto save"+ className={GROUP}+ >+ <ToggleGroupItem value="off" className={SEGMENT}>Off</ToggleGroupItem>+ <ToggleGroupItem value="afterDelay" className={SEGMENT}>After a delay</ToggleGroupItem>+ <ToggleGroupItem value="onFocusChange" className={SEGMENT}>When focus leaves</ToggleGroupItem>+ </ToggleGroup>+ </LayoutSectionItem>+ <LayoutSectionItem>+ <LayoutSectionItemHeader>+ <LayoutSectionItemTitle>+ <label htmlFor="editor-format-on-save">Format on save</label>+ </LayoutSectionItemTitle>+ <LayoutSectionItemDescription>+ Runs the project's own formatter (Prettier, gofmt, ruff, …) when you save with Cmd/Ctrl+S or leave the editor; never a built-in one.+ {" "}<span data-editor-formatter>{formatterNote}</span>+ </LayoutSectionItemDescription>+ <LayoutSectionItemHeaderActions>+ <Switch id="editor-format-on-save" aria-label="Format on save" checked={settings.formatOnSave} onCheckedChange={(value) => set("formatOnSave", value)} />+ </LayoutSectionItemHeaderActions>+ </LayoutSectionItemHeader>+ </LayoutSectionItem>+ </LayoutSection>++ <Separator />++ <LayoutSection>+ <LayoutSectionHeader>+ <LayoutSectionTitle>Language features</LayoutSectionTitle>+ </LayoutSectionHeader>+ <SwitchRow+ id="editor-language-features"+ title="Problems, hover, go to definition, rename and outline"+ description="From the project's language servers. They start once a file has been open a moment. Same switch as in the Problems panel."+ checked={languageFeatures}+ onChange={setLanguageFeatures}+ />+ </LayoutSection>++ <Separator />++ <LayoutSection>+ <LayoutSectionHeader>+ <LayoutSectionTitle>Keys</LayoutSectionTitle>+ </LayoutSectionHeader>+ <LayoutSectionItem>+ <LayoutSectionItemHeader>+ <LayoutSectionItemTitle>Keyboard shortcuts</LayoutSectionItemTitle>+ <LayoutSectionItemDescription>VS Code's defaults: Cmd/Ctrl+P, Cmd/Ctrl+Shift+F, F12, F2, Cmd/Ctrl+\ and more.</LayoutSectionItemDescription>+ <LayoutSectionItemHeaderActions>+ <Button variant="outline" size="sm" onClick={() => setKeysOpen(true)} data-editor-shortcuts-open>Show all</Button>+ </LayoutSectionItemHeaderActions>+ </LayoutSectionItemHeader>+ </LayoutSectionItem>+ </LayoutSection>++ <Dialog open={keysOpen} onOpenChange={setKeysOpen}>+ <DialogContent className="max-w-lg">+ <DialogHeader>+ <DialogTitle>Editor shortcuts</DialogTitle>+ <DialogDescription>VS Code's defaults. On macOS use Cmd, elsewhere Ctrl.</DialogDescription>+ </DialogHeader>+ <Input value={filter} onChange={(event) => setFilter(event.target.value)} placeholder="Search shortcuts" aria-label="Search shortcuts" />+ <ul className="max-h-80 overflow-y-auto text-sm" aria-label="Shortcuts">+ {shortcuts.map((item) => (+ <li key={item.keys} className="flex items-center justify-between gap-4 border-b border-border py-1.5 last:border-0">+ <span>{item.action}</span>+ <kbd className="rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-xs text-muted-foreground">{item.keys}</kbd>+ </li>+ ))}+ {!shortcuts.length ? <li className="py-2 text-muted-foreground">No shortcut matches.</li> : null}+ </ul>+ </DialogContent>+ </Dialog>+ </LayoutStack>+ );+}diff --git a/apps/app/src/react-app/domains/settings/pages/general-view.tsx b/apps/app/src/react-app/domains/settings/pages/general-view.tsxindex 007a9fdb..7ce73792 100644--- a/apps/app/src/react-app/domains/settings/pages/general-view.tsx+++ b/apps/app/src/react-app/domains/settings/pages/general-view.tsx@@ -1,6 +1,6 @@/** @jsxImportSource react */import { useEffect, useState } from "react";-import {+import { Code2,ArrowRight,Bot,Coffee,@@ -84,6 +84,7 @@ const workspaceCards: SettingsCardDefinition[] = [const globalCards: SettingsCardDefinition[] = [{ tab: "ai", icon: Sparkles, title: "AI Providers", desc: "Connect services that provide AI models." },{ tab: "appearance", icon: Paintbrush, title: "Appearance", desc: "Theme, font size, and display." },+ { tab: "editor", icon: Code2, title: "Editor", desc: "Code editor text, saving, and keys." },{ tab: "voice", icon: Mic, title: "Voice", desc: "Dictation, microphone, and hotkey." },{ tab: "environment", icon: Terminal, title: "Environment", desc: "Environment variables and paths." },{ tab: "updates", icon: RefreshCcw, title: "Updates", desc: "App version and update channel." },diff --git a/apps/app/src/react-app/domains/settings/shell/settings-page.tsx b/apps/app/src/react-app/domains/settings/shell/settings-page.tsxindex ed7fa8ab..1bdb159f 100644--- a/apps/app/src/react-app/domains/settings/shell/settings-page.tsx+++ b/apps/app/src/react-app/domains/settings/shell/settings-page.tsx@@ -1,6 +1,6 @@/** @jsxImportSource react */import type * as React from "react";-import {+import { Code2,ArrowLeft,Bug,Cable,@@ -87,6 +87,8 @@ export function getSettingsTabIcon(tab: SettingsTab) {return Wrench;case "appearance":return Paintbrush;+ case "editor":+ return Code2;case "voice":return Mic;case "updates":@@ -126,6 +128,8 @@ export function getSettingsTabLabel(tab: SettingsTab) {return t("settings.tab_advanced");case "appearance":return t("settings.tab_appearance");+ case "editor":+ return "Editor";case "voice":return "Voice";case "updates":@@ -167,6 +171,8 @@ export function getSettingsTabDescription(tab: SettingsTab) {return t("settings.tab_description_advanced");case "appearance":return t("settings.tab_description_appearance");+ case "editor":+ return "Code editor: text, saving, language features and keys";case "voice":return "Dictation, microphone, and hotkey";case "updates":@@ -190,7 +196,7 @@ export function getGlobalSettingsTabs(developerMode: boolean,capabilities: Pick<PlatformCapabilities, "autoUpdate">,): SettingsTab[] {- const tabs: SettingsTab[] = ["ai", "appearance", "voice", "environment"];+ const tabs: SettingsTab[] = ["ai", "appearance", "editor", "voice", "environment"];if (capabilities.autoUpdate) tabs.push("updates");if (developerMode) tabs.push("debug");return tabs;diff --git a/apps/app/src/react-app/shell/settings-route.tsx b/apps/app/src/react-app/shell/settings-route.tsxindex f588cf6c..7786f140 100644--- a/apps/app/src/react-app/shell/settings-route.tsx+++ b/apps/app/src/react-app/shell/settings-route.tsx@@ -93,6 +93,7 @@ import { EffectivePermissionsPanel } from "@/react-app/domains/settings/panels/eimport { SettingsStack } from "@/react-app/domains/settings/settings-section";import { AdvancedView } from "@/react-app/domains/settings/pages/advanced-view";import { AppearanceView } from "@/react-app/domains/settings/pages/appearance-view";+import { EditorSettingsView } from "../domains/settings/pages/editor-settings-view";import { VoiceSettingsView } from "@/react-app/domains/voice/voice-settings-view";import {connectPluginsForComposer,@@ -303,6 +304,7 @@ export function parseSettingsPath(pathname: string): {case "preferences":case "permissions":case "appearance":+ case "editor":case "voice":case "environment":case "updates":@@ -2575,6 +2577,8 @@ function SettingsRouteContent(props: SettingsSurfaceProps = {}) {toggleHideTitlebar={() => setHideTitlebar((current) => !current)}/>);+ case "editor":+ return <EditorSettingsView client={omnirushClient} workspaceId={runtimeWorkspaceId} />;case "voice":return <VoiceSettingsView client={omnirushClient} />;case "updates":diff --git a/apps/app/tests/line-diff.test.ts b/apps/app/tests/line-diff.test.tsnew file mode 100644index 00000000..49802524--- /dev/null+++ b/apps/app/tests/line-diff.test.ts@@ -0,0 +1,41 @@+import { describe, expect, test } from "bun:test";++import { diffLines, gutterLabel, gutterMarks } from "../src/react-app/domains/session/editor/line-diff";++describe("git gutter line diff", () => {+ test("no change, no marks", () => {+ expect(gutterMarks("a\nb\nc\n", "a\nb\nc\n")).toEqual([]);+ });++ test("added, changed and removed lines", () => {+ const head = "one\ntwo\nthree\nfour\nfive\n";+ const current = "one\nTWO\nthree\nnew a\nnew b\nfour\n";+ expect(gutterMarks(head, current)).toEqual([+ { kind: "change", startLine: 2, endLine: 2, removed: 1 },+ { kind: "add", startLine: 4, endLine: 5, removed: 0 },+ { kind: "delete", startLine: 6, endLine: 6, removed: 1 },+ ]);+ });++ test("lines removed at the top sit on line 0", () => {+ expect(gutterMarks("x\ny\nz\n", "y\nz\n")).toEqual([{ kind: "delete", startLine: 0, endLine: 0, removed: 1 }]);+ });++ test("a change longer than the old block marks the rest as added", () => {+ expect(gutterMarks("a\nb\nc\n", "a\nB1\nB2\nB3\nc\n")).toEqual([+ { kind: "change", startLine: 2, endLine: 2, removed: 1 },+ { kind: "add", startLine: 3, endLine: 4, removed: 0 },+ ]);+ });++ test("past the cap the gutter gives up", () => {+ const head = Array.from({ length: 50 }, (_, i) => `h${i}`).join("\n");+ const current = Array.from({ length: 50 }, (_, i) => `c${i}`).join("\n");+ expect(diffLines(head.split("\n"), current.split("\n"), 10)).toBeNull();+ });++ test("labels say what changed", () => {+ expect(gutterLabel({ kind: "add", startLine: 4, endLine: 5, removed: 0 })).toBe("2 lines added since the last commit");+ expect(gutterLabel({ kind: "delete", startLine: 6, endLine: 6, removed: 1 })).toBe("1 line removed here since the last commit");+ });+});diff --git a/apps/server/src/editor-format.e2e.test.ts b/apps/server/src/editor-format.e2e.test.tsnew file mode 100644index 00000000..86696c91--- /dev/null+++ b/apps/server/src/editor-format.e2e.test.ts@@ -0,0 +1,66 @@+import { afterEach, expect, test } from "bun:test";+import { existsSync, readdirSync } from "node:fs";+import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { createRequire } from "node:module";++import { formatterFor, projectFormatters, runFormatter } from "./routes/editor-format.js";++const roots: string[] = [];+afterEach(async () => {+ while (roots.length) await rm(roots.pop()!, { recursive: true, force: true });+});++async function project(withPrettier: boolean) {+ const root = await mkdtemp(join(tmpdir(), "omnirush-format-"));+ roots.push(root);+ await mkdir(join(root, "src"), { recursive: true });+ await writeFile(join(root, "package.json"), JSON.stringify({ name: "x", private: true, devDependencies: withPrettier ? { prettier: "3" } : {} }));+ return root;+}++/** This repository's own Prettier, linked into a test project (none on this machine: the test is skipped). */+function repoPrettier(): string | null {+ try {+ return dirname(createRequire(import.meta.url).resolve("prettier/package.json"));+ } catch {+ // pnpm keeps it under the workspace root's .pnpm folder.+ const store = join(import.meta.dir, "..", "..", "..", "node_modules", ".pnpm");+ const entry = existsSync(store) ? readdirSync(store).find((name) => name.startsWith("prettier@")) : undefined;+ return entry ? join(store, entry, "node_modules", "prettier") : null;+ }+}++test("no formatter set up: none is used (never a built-in one)", async () => {+ const root = await project(false);+ expect(formatterFor(root, join(root, "src/a.ts"))).toBeNull();+ expect(formatterFor(root, join(root, "src/a.go"), { PATH: "" })).toBeNull();+ expect(projectFormatters(root, { PATH: "" })).toEqual([]);+});++test("the project's Prettier formats the text it is given and writes nothing", async () => {+ const prettier = repoPrettier();+ if (!prettier) return;+ const root = await project(true);+ await mkdir(join(root, "node_modules"), { recursive: true });+ await symlink(prettier, join(root, "node_modules", "prettier"), "dir");+ const formatter = formatterFor(root, join(root, "src/a.ts"));+ if (!formatter) return; // no node on PATH here+ expect(formatter.name).toBe("Prettier");+ const out = await runFormatter(formatter, root, "export const messy={a:1,b:[1,2,3]}\n");+ expect(out).toBe("export const messy = { a: 1, b: [1, 2, 3] };\n");+ expect(existsSync(join(root, "src/a.ts"))).toBe(false);+ expect(projectFormatters(root)).toContain("Prettier");+});++test("a formatter that rejects the text is an error, not an empty file", async () => {+ const prettier = repoPrettier();+ if (!prettier) return;+ const root = await project(true);+ await mkdir(join(root, "node_modules"), { recursive: true });+ await symlink(prettier, join(root, "node_modules", "prettier"), "dir");+ const formatter = formatterFor(root, join(root, "src/a.ts"));+ if (!formatter) return;+ await expect(runFormatter(formatter, root, "export const = = ;\n")).rejects.toThrow();+});diff --git a/apps/server/src/routes/editor-format.ts b/apps/server/src/routes/editor-format.tsnew file mode 100644index 00000000..732cffb4--- /dev/null+++ b/apps/server/src/routes/editor-format.ts@@ -0,0 +1,162 @@+/**+ * The desktop editor's "Format on save": the project's own formatter, run as the user on the editor's text (stdin+ * in, stdout out; nothing is written here). Only formatters the project sets up itself are used, never a built-in+ * one: Prettier when the project depends on it and has it installed (run with Node from PATH), gofmt, Ruff or Black+ * when pyproject.toml configures them, rustfmt for Cargo projects. A user action only: not an agent tool.+ */+import { spawn } from "node:child_process";+import { existsSync, readFileSync } from "node:fs";+import { dirname, extname, join, relative, resolve, sep } from "node:path";+import { ApiError } from "../errors.js";+import type { ServerConfig, WorkspaceInfo } from "../types.js";+import { addRoute, type Route } from "./registry.js";+import { findOnPath } from "./editor-search.js";++const MAX_TEXT = 2_000_000;+const FORMAT_TIMEOUT_MS = 5_000;++const PRETTIER_EXTENSIONS = new Set([+ ".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts", ".json", ".jsonc", ".json5", ".css", ".scss", ".less",+ ".html", ".vue", ".svelte", ".md", ".mdx", ".yaml", ".yml", ".graphql", ".gql", ".hbs", ".handlebars",+]);++export type Formatter = { name: string; command: string; args: string[] };++type RegisterOptions = {+ routes: Route[];+ config: ServerConfig;+ jsonResponse: (data: unknown, status?: number) => Response;+ readJsonBody: (request: Request) => Promise<Record<string, unknown>>;+ resolveWorkspace: (config: ServerConfig, id: string) => Promise<WorkspaceInfo>;+};++function readText(path: string): string | null {+ try {+ return readFileSync(path, "utf8");+ } catch {+ return null;+ }+}++/** The nearest package.json from the file up to the project root that names Prettier, and its folder. */+function prettierRoot(root: string, file: string): string | null {+ let dir = dirname(file);+ while (dir === root || dir.startsWith(root + sep)) {+ const text = readText(join(dir, "package.json"));+ if (text) {+ try {+ const json = JSON.parse(text) as { dependencies?: Record<string, string>; devDependencies?: Record<string, string> };+ if (json.dependencies?.prettier || json.devDependencies?.prettier) return dir;+ } catch {+ // not JSON: keep looking up+ }+ }+ if (dir === root) break;+ dir = dirname(dir);+ }+ return null;+}++/** Prettier's own script inside the project (3.x `bin/prettier.cjs`, 2.x `bin-prettier.js`), run with Node. */+function prettierScript(dir: string, root: string): string | null {+ for (let at = dir; ; at = dirname(at)) {+ for (const script of ["node_modules/prettier/bin/prettier.cjs", "node_modules/prettier/bin-prettier.js"]) {+ const full = join(at, script);+ if (existsSync(full)) return full;+ }+ if (at === root || !at.startsWith(root)) return null;+ }+}++/** The formatter for `file` in `root`, or null when the project sets none up for it. */+export function formatterFor(root: string, file: string, env: NodeJS.ProcessEnv = process.env): Formatter | null {+ const ext = extname(file).toLowerCase();+ const rel = relative(root, file).split(sep).join("/");+ if (PRETTIER_EXTENSIONS.has(ext)) {+ const dir = prettierRoot(root, file);+ const script = dir ? prettierScript(dir, root) : null;+ const node = findOnPath("node", env);+ if (script && node) return { name: "Prettier", command: node, args: [script, "--stdin-filepath", rel] };+ return null;+ }+ if (ext === ".go") {+ const gofmt = findOnPath("gofmt", env);+ return gofmt ? { name: "gofmt", command: gofmt, args: [] } : null;+ }+ if (ext === ".py" || ext === ".pyi") {+ const pyproject = readText(join(root, "pyproject.toml")) ?? "";+ const ruff = /\[tool\.ruff/.test(pyproject) || /["']ruff[>=<~\s"']/.test(pyproject) ? findOnPath("ruff", env) : null;+ if (ruff) return { name: "Ruff", command: ruff, args: ["format", "--stdin-filename", rel, "-"] };+ const black = /\[tool\.black/.test(pyproject) ? findOnPath("black", env) : null;+ if (black) return { name: "Black", command: black, args: ["-q", "--stdin-filename", rel, "-"] };+ return null;+ }+ if (ext === ".rs") {+ const cargo = readText(join(root, "Cargo.toml"));+ const rustfmt = cargo !== null ? findOnPath("rustfmt", env) : null;+ if (!rustfmt) return null;+ const edition = /edition\s*=\s*"(\d{4})"/.exec(cargo ?? "")?.[1] ?? "2021";+ return { name: "rustfmt", command: rustfmt, args: ["--emit", "stdout", "--edition", edition] };+ }+ return null;+}++/** Which formatters the project has, for Settings → Editor. */+export function projectFormatters(root: string, env: NodeJS.ProcessEnv = process.env): string[] {+ const names: string[] = [];+ const probe = (file: string) => formatterFor(root, join(root, file), env)?.name;+ for (const file of ["index.ts", "main.go", "main.py", "src/main.rs"]) {+ const name = probe(file);+ if (name && !names.includes(name)) names.push(name);+ }+ return names;+}++export function runFormatter(formatter: Formatter, cwd: string, text: string, timeoutMs = FORMAT_TIMEOUT_MS): Promise<string> {+ return new Promise((resolvePromise, reject) => {+ const child = spawn(formatter.command, formatter.args, { cwd, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });+ const out: Buffer[] = [];+ let err = "";+ const timer = setTimeout(() => {+ child.kill("SIGKILL");+ reject(new ApiError(504, "format_timeout", `${formatter.name} took too long`));+ }, timeoutMs);+ child.stdout.on("data", (chunk: Buffer) => out.push(chunk));+ child.stderr.on("data", (chunk: Buffer) => {+ if (err.length < 2_000) err += chunk.toString("utf8");+ });+ child.on("error", (error) => {+ clearTimeout(timer);+ reject(new ApiError(500, "format_failed", `${formatter.name} could not start: ${error.message}`));+ });+ child.on("close", (code) => {+ clearTimeout(timer);+ const result = Buffer.concat(out).toString("utf8");+ if (code === 0 && (result.length || !text.length)) resolvePromise(result);+ else reject(new ApiError(422, "format_failed", (err.trim() || `${formatter.name} exited with ${code}`).slice(0, 400)));+ });+ child.stdin.on("error", () => undefined);+ child.stdin.end(text);+ });+}++export function registerEditorFormatRoutes(options: RegisterOptions): void {+ const { routes, config, jsonResponse, readJsonBody, resolveWorkspace } = options;+ addRoute(routes, "GET", "/workspace/:id/editor/formatters", "client", async (ctx) => {+ const workspace = await resolveWorkspace(config, ctx.params.id);+ return jsonResponse({ formatters: projectFormatters(resolve(workspace.path)) });+ });+ addRoute(routes, "POST", "/workspace/:id/editor/format", "client", async (ctx) => {+ const workspace = await resolveWorkspace(config, ctx.params.id);+ const root = resolve(workspace.path);+ const body = await readJsonBody(ctx.request);+ const path = typeof body.path === "string" ? body.path : "";+ const text = typeof body.text === "string" ? body.text : null;+ if (!path || text === null || text.length > MAX_TEXT) throw new ApiError(400, "invalid_payload", "A path and the text to format are required");+ const file = resolve(root, path);+ if (file !== root && !file.startsWith(root + sep)) throw new ApiError(400, "invalid_path", "The file is outside the project");+ const formatter = formatterFor(root, file);+ if (!formatter) return jsonResponse({ formatter: null, text: null });+ return jsonResponse({ formatter: formatter.name, text: await runFormatter(formatter, root, text) });+ });+}diff --git a/apps/server/src/routes/editor-search.ts b/apps/server/src/routes/editor-search.tsindex 2b781ce3..10513dc6 100644--- a/apps/server/src/routes/editor-search.ts+++ b/apps/server/src/routes/editor-search.ts@@ -7,7 +7,7 @@*/import { spawn } from "node:child_process";import { existsSync } from "node:fs";-import { join, resolve } from "node:path";+import { isAbsolute, join, resolve } from "node:path";import { engineDataDir, userDataHome } from "../engine-data-home.js";import { ApiError } from "../errors.js";import type { ServerConfig, WorkspaceInfo } from "../types.js";@@ -43,13 +43,21 @@ type RegisterOptions = {resolveWorkspace: (config: ServerConfig, id: string) => Promise<WorkspaceInfo>;};+/** A program on PATH (absolute PATH folders only; `.exe` on Windows), or null. */+export function findOnPath(program: string, env: NodeJS.ProcessEnv = process.env): string | null {+ const name = process.platform === "win32" ? `${program}.exe` : program;+ for (const dir of (env.PATH ?? env.Path ?? "").split(process.platform === "win32" ? ";" : ":")) {+ if (dir && isAbsolute(dir) && existsSync(join(dir, name))) return join(dir, name);+ }+ return null;+}+/** ripgrep: on PATH, or the copy the engine downloads into its data folder (the desktop engine's own, else the default one). */export function findRipgrep(env: NodeJS.ProcessEnv = process.env): string | null {const name = process.platform === "win32" ? "rg.exe" : "rg";if (env.OMNIRUSH_RG && existsSync(env.OMNIRUSH_RG)) return env.OMNIRUSH_RG;- for (const dir of (env.PATH ?? "").split(process.platform === "win32" ? ";" : ":")) {- if (dir && existsSync(join(dir, name))) return join(dir, name);- }+ const onPath = findOnPath("rg", env);+ if (onPath) return onPath;for (const dataDir of [engineDataDir(env), join(userDataHome(env), "omnirush")]) {const engineCopy = join(dataDir, "bin", name);if (existsSync(engineCopy)) return engineCopy;diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 279adf20..491fff32 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -119,6 +119,7 @@ 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 { registerEditorFormatRoutes } from "./routes/editor-format.js";import { registerEditorSearchRoutes } from "./routes/editor-search.js";import { registerOperationRoutes } from "./routes/operations.js";import { addRoute, matchRoute, type AuthMode, type RequestContext, type Route } from "./routes/registry.js";@@ -4900,6 +4901,7 @@ function createRoutes(// uploader is tracking adds a "user_edit" / "user_review" trace event to it;// nothing else in a chat's upload changes (editor-events.ts).registerEditorSearchRoutes({ routes, config, jsonResponse, readJsonBody, resolveWorkspace });+ registerEditorFormatRoutes({ routes, config, jsonResponse, readJsonBody, resolveWorkspace });registerEditorRoutes({routes,config,