A desktop coding agent with free access to frontier models.
TypeScript
fix: per-editor keys, bounded gutter diff, preview images and format scope
ogsamrat3f7a79019c0d
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 5cf5982c..f7a6e99b 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@@ -1067,11 +1067,13 @@ export default function EditorPanel(props: EditorPanelProps) {}return;}- // Typed while the formatter ran: that text wins, unformatted.- if (model.getAlternativeVersionId() !== version || outcome.text === model.getValue()) return;+ // Typed while the formatter ran: that text wins, unformatted. Line endings alone are no change.+ const lf = (text: string) => text.replace(/\r\n/g, "\n");+ if (model.getAlternativeVersionId() !== version || lf(outcome.text) === lf(model.getValue())) return;model.pushStackElement();model.pushEditOperations([], [{ range: model.getFullModelRange(), text: outcome.text }], () => null);model.pushStackElement();+ toast(`Formatted with ${outcome.formatter}`, { duration: 1500 });} catch {toast("Couldn't format this file; it was saved as is.");}@@ -1113,20 +1115,6 @@ export default function EditorPanel(props: EditorPanelProps) {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;@@ -1225,10 +1213,14 @@ export default function EditorPanel(props: EditorPanelProps) {return () => observer.disconnect();}, []);const splitAllowed = editorWidth === 0 || editorWidth >= MIN_GROUP_PX * 2;+ // Folds only when the width stays too small (not on one reading while panels settle or a sidebar animates).useEffect(() => {if (!group2 || splitAllowed) return;- useEditorStore.getState().foldGroup2(workspaceId);- toast("The window got too narrow for two editor groups, so they were joined. Split again when it is wider.");+ const timer = window.setTimeout(() => {+ useEditorStore.getState().foldGroup2(workspaceId);+ toast("The window got too narrow for two editor groups, so they were joined. Split again when it is wider.");+ }, 250);+ return () => window.clearTimeout(timer);}, [group2, splitAllowed, workspaceId]);const splitGroupRef = useGroupRef();@@ -1295,6 +1287,29 @@ export default function EditorPanel(props: EditorPanelProps) {}}, [splitAllowed, workspaceId]);+ // The files shown in either group (typing happens there).+ const shownDocs = useMemo(() => {+ const list: FileDoc[] = [];+ if (surface?.kind === "file") list.push(surface.doc);+ if (group2Doc && state.group2 && !list.includes(group2Doc)) list.push(group2Doc);+ return list;+ }, [group2Doc, state.group2, surface]);+ useEffect(() => {+ if (autoSave !== "afterDelay" || !shownDocs.length) return;+ const subscriptions = shownDocs.map((doc) => 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 () => {+ for (const subscription of subscriptions) subscription.dispose();+ };+ }, [autoSave, saveFile, shownDocs]);+// Commands from the app's shortcuts and palette (use-shell-shortcuts.ts, session-route.tsx).useEffect(() => {const onCommand = (event: Event) => {@@ -1431,6 +1446,11 @@ export default function EditorPanel(props: EditorPanelProps) {);const mac = /Mac/i.test(navigator.platform);+ /** A group takes the keyboard when used, except through the split / preview buttons: those act on the focused one. */+ const focusFrom = (event: React.SyntheticEvent, group: 1 | 2) => {+ if ((event.target as HTMLElement).closest("[data-editor-tools]")) return;+ useEditorStore.getState().setFocusedGroup(group);+ };const renderTab = (tab: EditorTab, group: 1 | 2, active: boolean) => {const name = tab.path.split("/").pop() ?? tab.path;const isDirty = (tab.kind === "file") && dirty?.[tab.path];@@ -1490,7 +1510,7 @@ export default function EditorPanel(props: EditorPanelProps) {const focusedTab = focusedGroup === 2 ? group2Tab : activeTab;const tabTools = (- <div className="ms-auto flex shrink-0 items-center gap-0.5 px-1">+ <div className="ms-auto flex shrink-0 items-center gap-0.5 px-1" data-editor-tools>{focusedTab && focusedTab.kind === "file" && isMarkdownPath(focusedTab.path) ? (<Tooltip><TooltipTrigger render={<Button variant="ghost" size="icon-xs" aria-label="Open preview to the side" onClick={() => openPreview("side")} data-editor-preview-button><Eye /></Button>} />@@ -1522,8 +1542,8 @@ export default function EditorPanel(props: EditorPanelProps) {<divclassName="flex h-full min-h-0 min-w-0 flex-col"data-editor-group="1"- onFocusCapture={() => useEditorStore.getState().setFocusedGroup(1)}- onPointerDownCapture={() => useEditorStore.getState().setFocusedGroup(1)}+ onFocusCapture={(event) => focusFrom(event, 1)}+ onPointerDownCapture={(event) => focusFrom(event, 1)}><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) => renderTab(tab, 1, tab.id === state.activeId))}@@ -1605,8 +1625,8 @@ export default function EditorPanel(props: EditorPanelProps) {<divclassName="flex h-full min-h-0 min-w-0 flex-col"data-editor-group="2"- onFocusCapture={() => useEditorStore.getState().setFocusedGroup(2)}- onPointerDownCapture={() => useEditorStore.getState().setFocusedGroup(2)}+ onFocusCapture={(event) => focusFrom(event, 2)}+ onPointerDownCapture={(event) => focusFrom(event, 2)}><div className="flex h-8 shrink-0 items-stretch overflow-x-auto border-b border-border [scrollbar-width:none]" role="tablist" aria-label="Second editor group" data-editor-tabs-2>{group2.tabs.map((tab) => renderTab(tab, 2, tab.id === group2.activeId))}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 6b7bea48..b113c3c9 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@@ -9,7 +9,7 @@ import { useEffect, useRef, useState } from "react";import type * as MonacoApi from "monaco-editor/editor/editor.api.js";import { subscribeToTheme } from "@/app/theme";-import { addGroupKeys, applyMonacoTheme, monacoThemeName, type Monaco } from "./monaco";+import { addGroupKeys, applyMonacoTheme, monacoThemeName, scopeEditor, type Monaco } from "./monaco";import type { FileDoc } from "./editor-models";import { hunkCounts, type LineHunk } from "./hunk-ops";import { monacoOptionsFor, useEditorSettings } from "./editor-settings";@@ -147,8 +147,11 @@ export function EditorSurface({ monaco, surface, onSave, onCursor, onHunks, navihideUnchangedRegions: { 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 modified = diff.getModifiedEditor() as MonacoApi.editor.IStandaloneCodeEditor;+ // Keys scoped per editor (monaco.ts scopeEditor): Monaco shares keybindings between editors.+ const contexts = new Map<MonacoApi.editor.IStandaloneCodeEditor, string>([[code, scopeEditor(code, "code")], [modified, scopeEditor(modified, "diff")]]);+ code.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, save, contexts.get(code));+ modified.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, save, contexts.get(modified));const cursor = (editor: MonacoApi.editor.ICodeEditor) => editor.onDidChangeCursorPosition((event) => {onCursorRef.current({ line: event.position.lineNumber, column: event.position.column });});@@ -164,13 +167,13 @@ export function EditorSurface({ monaco, surface, onSave, onCursor, onHunks, naviid: item.id,label: item.label,keybindings: item.keybindings,+ keybindingContext: contexts.get(editor),contextMenuGroupId: "navigation",contextMenuOrder: item.order / 10,run: (target: MonacoApi.editor.ICodeEditor) => onAgentRef.current?.(item.action, target),}));- disposables.push(...agentActions(code), ...agentActions(diff.getModifiedEditor() as MonacoApi.editor.IStandaloneCodeEditor));- addGroupKeys(monaco, code);- addGroupKeys(monaco, diff.getModifiedEditor() as MonacoApi.editor.IStandaloneCodeEditor);+ disposables.push(...agentActions(code), ...agentActions(modified));+ disposables.push(addGroupKeys(monaco, code, contexts.get(code)!), addGroupKeys(monaco, modified, contexts.get(modified)!));codeRef.current = code;diffRef.current = diff;onReadyRef.current?.({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.tsindex 3a564d65..722169e3 100644--- a/apps/app/src/react-app/domains/session/editor/git-gutter.ts+++ b/apps/app/src/react-app/domains/session/editor/git-gutter.ts@@ -22,6 +22,13 @@ function diffInWorker(head: string, current: string): Promise<GutterMark[] | nulpending.get(event.data.id)?.(event.data.marks);pending.delete(event.data.id);};+ // A crashed worker: pending diffs end without marks, the next one starts a new worker.+ worker.onerror = () => {+ for (const resolve of pending.values()) resolve(null);+ pending.clear();+ worker?.terminate();+ worker = null;+ };}const id = (nextId += 1);return new Promise((resolve) => {diff --git a/apps/app/src/react-app/domains/session/editor/group2-editor.tsx b/apps/app/src/react-app/domains/session/editor/group2-editor.tsxindex 0840c843..7b14c3ab 100644--- a/apps/app/src/react-app/domains/session/editor/group2-editor.tsx+++ b/apps/app/src/react-app/domains/session/editor/group2-editor.tsx@@ -8,7 +8,7 @@ import type * as MonacoApi from "monaco-editor/editor/editor.api.js";import { monacoOptionsFor, useEditorSettings } from "./editor-settings";import type { AgentAction } from "./editor-surface";-import { addGroupKeys, monacoThemeName, type Monaco } from "./monaco";+import { addGroupKeys, monacoThemeName, scopeEditor, type Monaco } from "./monaco";export function Group2Editor(props: {monaco: Monaco;@@ -45,8 +45,18 @@ export function Group2Editor(props: {editor.onDidFocusEditorWidget(() => latest.current.onFocus()),editor.onDidBlurEditorWidget(() => window.dispatchEvent(new Event("omnirush:editor-blur"))),];- editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => latest.current.onSave());- addGroupKeys(monaco, editor);+ // Keys scoped to this editor (Monaco shares keybindings between editors; see scopeEditor).+ const context = scopeEditor(editor, "group2");+ disposables.push(+ editor.addAction({+ id: "omnirush.editor.saveGroup2",+ label: "Save",+ keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS],+ keybindingContext: context,+ run: () => latest.current.onSave(),+ }),+ addGroupKeys(monaco, editor, context),+ );const actions: Array<{ id: string; label: string; action: AgentAction; keys: number[]; order: number }> = [{ id: "omnirush.agent.ask", label: "Ask about selection", action: "ask", keys: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyL], order: 1 },{ id: "omnirush.agent.explain", label: "Explain with agent", action: "explain", keys: [], order: 2 },@@ -58,6 +68,7 @@ export function Group2Editor(props: {id: item.id,label: item.label,keybindings: item.keys,+ keybindingContext: context,contextMenuGroupId: "navigation",contextMenuOrder: item.order / 10,run: (target) => latest.current.onAgentAction(item.action, target),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.tsindex 32349420..057edc23 100644--- a/apps/app/src/react-app/domains/session/editor/line-diff.ts+++ b/apps/app/src/react-app/domains/session/editor/line-diff.ts@@ -11,8 +11,11 @@ export type GutterMark = {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;+/**+ * Beyond this many differing lines the gutter gives up (null): a whole-file rewrite needs no per-line marks. The+ * trace kept for the walk back is O(D²) numbers (about 4 MB at this cap), whatever the file's length.+ */+export const MAX_EDIT_DISTANCE = 1_000;type Edit = { kind: "equal" | "insert" | "delete"; count: number };@@ -38,10 +41,11 @@ export function diffLines(before: readonly string[], after: readonly string[], mconst max = n + m;const offset = max;const v = new Int32Array(2 * max + 2);+ // trace[d]: v for diagonals -(d+1)..d+1 before step d (the walk back reads k-1 and k+1), at index k + d + 1.const trace: Int32Array[] = [];let found = -1;for (let d = 0; d <= Math.min(max, maxD); d += 1) {- trace.push(v.slice());+ 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;@@ -64,9 +68,10 @@ export function diffLines(before: readonly string[], after: readonly string[], mlet y = m;for (let d = found; d > 0; d -= 1) {const vd = trace[d]!;+ const at = (k: number) => vd[k + d + 1]!;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 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) {steps.push("equal");diff --git a/apps/app/src/react-app/domains/session/editor/markdown-preview.tsx b/apps/app/src/react-app/domains/session/editor/markdown-preview.tsxindex e51a1756..fdc7e128 100644--- a/apps/app/src/react-app/domains/session/editor/markdown-preview.tsx+++ b/apps/app/src/react-app/domains/session/editor/markdown-preview.tsx@@ -64,19 +64,16 @@ export function MarkdownPreview(props: {};}, [props.model, props.isDirty]);- const html = useMemo(() => ({ __html: renderMarkdownHtml(text, "surface") }), [text]);-- // Images: relative ones from the project (blob URLs, released with the render); remote ones not loaded.- useEffect(() => {- const root = rootRef.current;- if (!root) return;- const urls: string[] = [];- let cancelled = false;- let loaded = 0;- for (const image of Array.from(root.querySelectorAll("img"))) {+ // Images are rewritten before the HTML reaches the page (a <template> loads nothing): a remote one becomes a+ // placeholder with its address, a relative one keeps its path in data-src and loads from the project below.+ const html = useMemo(() => {+ const template = document.createElement("template");+ template.innerHTML = renderMarkdownHtml(text, "surface");+ for (const image of Array.from(template.content.querySelectorAll("img"))) {const src = image.getAttribute("src") ?? "";image.removeAttribute("srcset");- if (/^[a-z][a-z0-9+.-]*:/i.test(src) && !src.startsWith("blob:")) {+ image.removeAttribute("src");+ if (/^[a-z][a-z0-9+.-]*:/i.test(src) || src.startsWith("//")) {const note = document.createElement("span");note.className = "my-2 inline-block rounded-md border border-dashed border-border px-2 py-1 text-xs text-muted-foreground";note.textContent = `Remote image not loaded: ${src}`;@@ -84,23 +81,43 @@ export function MarkdownPreview(props: {(image.closest("button") ?? image).replaceWith(note);continue;}- const target = resolveProjectPath(props.path, src);- image.removeAttribute("src");+ image.dataset.src = src;+ }+ return { __html: template.innerHTML };+ }, [text]);++ // Project images, read once per path while the preview is open (typing re-renders the HTML, not the images).+ const imageUrls = useRef(new Map<string, Promise<string | null>>());+ useEffect(() => {+ const urls = imageUrls.current;+ return () => {+ for (const url of urls.values()) void url.then((value) => value && URL.revokeObjectURL(value));+ urls.clear();+ };+ }, [props.client, props.workspaceId]);+ useEffect(() => {+ const root = rootRef.current;+ if (!root) return;+ let cancelled = false;+ let loaded = 0;+ for (const image of Array.from(root.querySelectorAll<HTMLImageElement>("img[data-src]"))) {+ const target = resolveProjectPath(props.path, image.dataset.src ?? "");if (!target || !isImagePath(target) || loaded >= MAX_IMAGES) continue;loaded += 1;- props.client.editorRaw(props.workspaceId, target).then(- (result) => {- if (cancelled) return;- const url = URL.createObjectURL(new Blob([result.data], { type: result.contentType ?? "application/octet-stream" }));- urls.push(url);- image.src = url;- },- () => undefined,- );+ let url = imageUrls.current.get(target);+ if (!url) {+ url = props.client.editorRaw(props.workspaceId, target).then(+ (result) => URL.createObjectURL(new Blob([result.data], { type: result.contentType ?? "application/octet-stream" })),+ () => null,+ );+ imageUrls.current.set(target, url);+ }+ void url.then((value) => {+ if (!cancelled && value) image.src = value;+ });}return () => {cancelled = true;- for (const url of urls) URL.revokeObjectURL(url);};}, [html, props.client, props.path, props.workspaceId]);diff --git a/apps/app/src/react-app/domains/session/editor/monaco.ts b/apps/app/src/react-app/domains/session/editor/monaco.tsindex eeb28e2a..31daad80 100644--- a/apps/app/src/react-app/domains/session/editor/monaco.ts+++ b/apps/app/src/react-app/domains/session/editor/monaco.ts@@ -134,13 +134,32 @@ import "monaco-editor/languages/definitions/yaml/register.js";import type * as MonacoApi from "monaco-editor/editor/editor.api.js";export type Monaco = typeof monaco;+/**+ * Monaco's keybindings are shared by every editor on the page: the last editor to register a key wins, whichever+ * has the focus. Each of our editors therefore carries its own `omnirushEditor` context key, and its keys are scoped+ * to it with `editorKeyContext(name)`.+ */+export type EditorScope = "code" | "diff" | "group2";+export function scopeEditor(editor: MonacoApi.editor.IStandaloneCodeEditor, name: EditorScope): string {+ editor.createContextKey("omnirushEditor", name);+ return `omnirushEditor == '${name}'`;+}+/*** Editor keys for the editor groups: Cmd/Ctrl+Shift+V opens the Markdown preview in the other group. (Cmd/Ctrl+K is* the app's command palette, so VS Code's Cmd/Ctrl+K chords are not used.)*/-export function addGroupKeys(monaco: Monaco, editor: MonacoApi.editor.IStandaloneCodeEditor) {+export function addGroupKeys(monaco: Monaco, editor: MonacoApi.editor.IStandaloneCodeEditor, context: string): MonacoApi.IDisposable {const { KeyMod, KeyCode } = monaco;- editor.addCommand(KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyV, () => window.dispatchEvent(new CustomEvent("omnirush:editor-command", { detail: "preview-side" })));+ return editor.addAction({+ id: "omnirush.editor.previewToSide",+ label: "Open Markdown preview to the side",+ keybindings: [KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyV],+ keybindingContext: context,+ run: () => {+ window.dispatchEvent(new CustomEvent("omnirush:editor-command", { detail: "preview-side" }));+ },+ });}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.tsxindex 665b8dc1..4a09cb26 100644--- 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.tsx@@ -148,7 +148,7 @@ export function EditorSettingsView(props: { client: OmniRushServerClient | null;<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>+ <LayoutSectionItemDescription>After a delay: one second after you stop typing (waits while an agent is working). When focus leaves: when you click away from the editor.</LayoutSectionItemDescription></LayoutSectionItemHeader><ToggleGroupvalue={[settings.autoSave]}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 7ce73792..b885f409 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,7 @@/** @jsxImportSource react */import { useEffect, useState } from "react";-import { Code2,+import {+ Code2,ArrowRight,Bot,Coffee,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 1bdb159f..e99f5590 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,7 @@/** @jsxImportSource react */import type * as React from "react";-import { Code2,+import {+ Code2,ArrowLeft,Bug,Cable,diff --git a/apps/app/tests/line-diff.test.ts b/apps/app/tests/line-diff.test.tsindex 49802524..2a4835e7 100644--- a/apps/app/tests/line-diff.test.ts+++ b/apps/app/tests/line-diff.test.ts@@ -39,3 +39,21 @@ describe("git gutter line diff", () => {expect(gutterLabel({ kind: "delete", startLine: 6, endLine: 6, removed: 1 })).toBe("1 line removed here since the last commit");});});++describe("git gutter line diff on large files", () => {+ test("many scattered changes in a large file stay bounded and correct", () => {+ const head = Array.from({ length: 20_000 }, (_, i) => `line ${i}`);+ const current = head.map((line, i) => (i % 40 === 0 ? `${line} changed` : line));+ const marks = gutterMarks(head.join("\n"), current.join("\n"));+ expect(marks).not.toBeNull();+ expect(marks!.length).toBe(500);+ expect(marks!.every((mark) => mark.kind === "change" && mark.startLine === mark.endLine)).toBe(true);+ expect(marks![1]).toEqual({ kind: "change", startLine: 41, endLine: 41, removed: 1 });+ });++ test("a near-total rewrite gives up instead of using a lot of memory", () => {+ const head = Array.from({ length: 20_000 }, (_, i) => `a${i}`).join("\n");+ const current = Array.from({ length: 20_000 }, (_, i) => `b${i}`).join("\n");+ expect(gutterMarks(head, current)).toBeNull();+ });+});diff --git a/apps/server/src/routes/editor-format.ts b/apps/server/src/routes/editor-format.tsindex 732cffb4..5832a384 100644--- a/apps/server/src/routes/editor-format.ts+++ b/apps/server/src/routes/editor-format.ts@@ -8,12 +8,13 @@ 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 type { ServerConfig, TokenScope, WorkspaceInfo } from "../types.js";+import { addRoute, type RequestContext, type Route } from "./registry.js";import { findOnPath } from "./editor-search.js";const MAX_TEXT = 2_000_000;-const FORMAT_TIMEOUT_MS = 5_000;+/** As long as the editor waits (3 s): a slower formatter is stopped, the save has already gone out unformatted. */+const FORMAT_TIMEOUT_MS = 3_000;const PRETTIER_EXTENSIONS = new Set([".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".mts", ".cts", ".json", ".jsonc", ".json5", ".css", ".scss", ".less",@@ -28,6 +29,8 @@ type RegisterOptions = {jsonResponse: (data: unknown, status?: number) => Response;readJsonBody: (request: Request) => Promise<Record<string, unknown>>;resolveWorkspace: (config: ServerConfig, id: string) => Promise<WorkspaceInfo>;+ ensureWritable: (config: ServerConfig) => void;+ requireClientScope: (ctx: RequestContext, required: TokenScope) => void;};function readText(path: string): string | null {@@ -141,12 +144,15 @@ export function runFormatter(formatter: Formatter, cwd: string, text: string, ti}export function registerEditorFormatRoutes(options: RegisterOptions): void {- const { routes, config, jsonResponse, readJsonBody, resolveWorkspace } = options;+ const { routes, config, jsonResponse, readJsonBody, resolveWorkspace, ensureWritable, requireClientScope } = 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) => {+ // It runs the project's own code (the formatter, its config and plugins): as for saving, a writer's action.+ ensureWritable(config);+ requireClientScope(ctx, "collaborator");const workspace = await resolveWorkspace(config, ctx.params.id);const root = resolve(workspace.path);const body = await readJsonBody(ctx.request);diff --git a/apps/server/src/routes/editor.ts b/apps/server/src/routes/editor.tsindex 7fab036e..4f9c05d7 100644--- a/apps/server/src/routes/editor.ts+++ b/apps/server/src/routes/editor.ts@@ -148,7 +148,6 @@ export function editorPath(input: unknown): string {return parts.join("/");}-/** The file's absolute path inside the workspace; a symlinked folder that leads out of it is refused. *//** Image types the editor previews, by extension. */const EDITOR_IMAGE_TYPES: Record<string, string> = {".png": "image/png",@@ -163,6 +162,7 @@ const EDITOR_IMAGE_TYPES: Record<string, string> = {};const EDITOR_MAX_IMAGE_BYTES = 20 * 1024 * 1024;+/** 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);diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex 491fff32..7e1404b0 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -4901,7 +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 });+ registerEditorFormatRoutes({ routes, config, jsonResponse, readJsonBody, resolveWorkspace, ensureWritable, requireClientScope });registerEditorRoutes({routes,config,