Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: bounded language features and safer editor search

ogsamrat8bcaaf7dbd4e
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
index 4d272d8f..4c15ddf5 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
@@ -52,13 +52,18 @@ import { ProblemsView } from "./problems-view";
import { OutlineView } from "./outline-view";
import { codeChipText, lineLabel, sendToChat } from "./chat-context";
import {
+ activateLsp,
+ activateLspForModel,
+ clearLanguageFeatures,
documentSymbols,
installLanguageFeatures,
problemCounts,
refreshAllDiagnostics,
refreshFileDiagnostics,
setLanguageContext,
+ setLspSessionBusy,
symbolPath,
+ useIsLspActive,
useProblemsStore,
type LspDiagnostic,
} from "./lsp";
@@ -66,6 +71,9 @@ import type { AgentAction, SurfaceHandle } from "./editor-surface";
import { baselinesForTurns, turnFileChange, type TurnFileChange } from "./review";
import "./editor.css";
+/** How long a file stays the active one before its language features start. */
+const LSP_DWELL_MS = 2500;
+
export type EditorPanelProps = {
client: OmniRushServerClient;
workspaceId: string;
@@ -934,9 +942,38 @@ export default function EditorPanel(props: EditorPanelProps) {
requestAnimationFrame(() => surfaceHandle.current?.reveal(reveal.line, reveal.column, reveal.endColumn));
}, [activeTab, surface]);
- // The active file's problems: when it opens and after edits (its unsaved text is checked).
+ // Language features start for a file once it has been the active file for a moment, or when it is edited
+ // (a file only glanced at from search, quick open or Problems starts no language server).
+ const languageFeatures = useEditorStore((state) => state.languageFeatures);
+ const activeFilePath = surface?.kind === "file" ? surface.doc.path : null;
+ const lspActive = useIsLspActive(activeFilePath);
+ useEffect(() => {
+ setLspSessionBusy(sessionBusy);
+ }, [sessionBusy]);
+ useEffect(() => {
+ if (!languageFeatures) clearLanguageFeatures();
+ }, [languageFeatures]);
+ useEffect(() => {
+ if (!surface || surface.kind !== "file" || !languageFeatures || lspActive) return;
+ const path = surface.doc.path;
+ const timer = window.setTimeout(() => activateLsp(path), LSP_DWELL_MS);
+ // A typed edit starts them at once; the text loading or reloading from disk does not (the document is clean
+ // again right after a reload, so the check waits a microtask).
+ const doc = surface.doc;
+ const subscription = doc.model.onDidChangeContent(() => {
+ queueMicrotask(() => {
+ if (docs.isDirty(doc)) activateLsp(path);
+ });
+ });
+ return () => {
+ window.clearTimeout(timer);
+ subscription.dispose();
+ };
+ }, [docs, surface, languageFeatures, lspActive]);
+
+ // The active file's problems: when its language features start and after edits (its unsaved text is checked).
useEffect(() => {
- if (!surface || surface.kind !== "file") return;
+ if (!surface || surface.kind !== "file" || !lspActive) return;
const doc = surface.doc;
void refreshFileDiagnostics(doc.path);
let timer = 0;
@@ -948,7 +985,7 @@ export default function EditorPanel(props: EditorPanelProps) {
window.clearTimeout(timer);
subscription.dispose();
};
- }, [surface]);
+ }, [surface, lspActive, sessionBusy]);
// Breadcrumbs: the symbols around the cursor.
useEffect(() => {
@@ -959,14 +996,14 @@ export default function EditorPanel(props: EditorPanelProps) {
let cancelled = false;
const timer = window.setTimeout(() => {
void documentSymbols(surface.doc.model).then((symbols) => {
- if (!cancelled) setBreadcrumbSymbols(symbolPath(symbols, cursor.line, cursor.column).map((symbol) => symbol.name));
+ if (!cancelled) setBreadcrumbSymbols(symbolPath(symbols ?? [], cursor.line, cursor.column).map((symbol) => symbol.name));
});
}, 300);
return () => {
cancelled = true;
window.clearTimeout(timer);
};
- }, [cursor, surface]);
+ }, [cursor, surface, lspActive]);
// ── save ───────────────────────────────────────────────────────────────
const save = useCallback(async (options: { force?: boolean } = {}) => {
@@ -1029,6 +1066,8 @@ export default function EditorPanel(props: EditorPanelProps) {
useEditorStore.getState().setQuickOpen(true);
} else if (command === "symbol") {
const editor = surfaceHandle.current?.activeEditor();
+ const model = editor?.getModel();
+ if (model) activateLspForModel(model);
editor?.focus();
editor?.trigger("palette", "editor.action.quickOutline", null);
} else if (command === "outline") {
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
index 194c18c7..ed4207f2 100644
--- a/apps/app/src/react-app/domains/session/editor/editor-store.ts
+++ b/apps/app/src/react-app/domains/session/editor/editor-store.ts
@@ -46,6 +46,8 @@ type EditorStore = {
/** The bottom panel: Problems shown, and which tab is in front (the terminal opens through its own switch). */
problemsOpen: boolean;
bottomTab: "problems" | "terminal";
+ /** Language features in the editor (problems, hover, go to, rename, outline) from the project's language servers. */
+ languageFeatures: boolean;
openTab: (workspaceId: string, tab: EditorTab, options?: { preview?: boolean }) => void;
closeTab: (workspaceId: string, id: string) => void;
selectTab: (workspaceId: string, id: string) => void;
@@ -63,6 +65,7 @@ type EditorStore = {
requestChatToggle: () => void;
setProblemsOpen: (open: boolean) => void;
setBottomTab: (tab: "problems" | "terminal") => void;
+ setLanguageFeatures: (on: boolean) => void;
};
export const DEFAULT_IDE_CHAT_WIDTH = 420;
@@ -95,6 +98,7 @@ export const useEditorStore = create<EditorStore>()(
chatToggleRequest: 0,
problemsOpen: false,
bottomTab: "terminal",
+ languageFeatures: true,
openTab: (workspaceId, tab) =>
set((state) => {
const current = state.byWorkspace[workspaceId] ?? EMPTY;
@@ -150,6 +154,7 @@ export const useEditorStore = create<EditorStore>()(
requestChatToggle: () => set((state) => ({ chatToggleRequest: state.chatToggleRequest + 1 })),
setProblemsOpen: (problemsOpen) => set(problemsOpen ? { problemsOpen, bottomTab: "problems" } : { problemsOpen }),
setBottomTab: (bottomTab) => set({ bottomTab }),
+ setLanguageFeatures: (languageFeatures) => set({ languageFeatures }),
}),
{
name: "omnirush:editor:v1",
@@ -161,6 +166,7 @@ export const useEditorStore = create<EditorStore>()(
modeByWorkspace: state.modeByWorkspace,
ideChatCollapsed: state.ideChatCollapsed,
ideChatWidth: state.ideChatWidth,
+ languageFeatures: state.languageFeatures,
}),
},
),
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
index c6bf20d3..5104cc56 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
@@ -59,7 +59,8 @@ const BASE_OPTIONS: MonacoApi.editor.IStandaloneEditorConstructionOptions = {
renderLineHighlight: "line",
smoothScrolling: false,
padding: { top: 6, bottom: 6 },
- stickyScroll: { enabled: true, maxLineCount: 3 },
+ // 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" },
// Large files stay responsive: no tokenisation past 20k chars per line, no word-based suggestions on huge files.
maxTokenizationLineLength: 20_000,
wordBasedSuggestions: "currentDocument",
diff --git a/apps/app/src/react-app/domains/session/editor/lsp.ts b/apps/app/src/react-app/domains/session/editor/lsp.ts
index d933e259..4814e4b2 100644
--- a/apps/app/src/react-app/domains/session/editor/lsp.ts
+++ b/apps/app/src/react-app/domains/session/editor/lsp.ts
@@ -6,12 +6,20 @@
* diagnostics (squiggles and the Problems panel), and "Fix with agent" as a
* quick fix. An unsaved buffer's text goes with each request; the engine
* uses it for that request only and then goes back to the file on disk.
+ *
+ * Bounds: a file's language servers start only once it has been the active
+ * file for a moment, or on the first edit / go to / rename / go to symbol request
+ * (not when a file is just glanced at); one request per file at a time; no
+ * unsaved text while the chat's agent is working; and the "Language features
+ * in the editor" switch turns all of it off.
*/
import { create } from "zustand";
import type * as MonacoApi from "monaco-editor/editor/editor.api.js";
import type { OmniRushServerClient } from "@/app/lib/omnirush-server";
+import { toast } from "@/components/ui/sonner";
import type { EditorDocuments } from "./editor-models";
+import { useEditorStore } from "./editor-store";
import type { Monaco } from "./monaco";
export type LspPosition = { line: number; character: number };
@@ -34,6 +42,33 @@ type Context = {
let current: Context | null = null;
let installed = false;
let unavailable = false;
+let sessionBusy = false;
+
+/** Files whose language features have started (per workspace): the outline and diagnostics follow it. */
+export const useLspActivation = create<{ active: Record<string, true> }>(() => ({ active: {} }));
+const activationKey = (path: string) => `${current?.workspaceId ?? ""}\u0000${path}`;
+export function isLspActive(path: string): boolean {
+ return Boolean(useLspActivation.getState().active[activationKey(path)]);
+}
+export function useIsLspActive(path: string | null): boolean {
+ return useLspActivation((state) => (path ? Boolean(state.active[activationKey(path)]) : false));
+}
+/** Starts language features for the file of an editor model (go to symbol and other explicit actions). */
+export function activateLspForModel(model: MonacoApi.editor.ITextModel) {
+ const path = modelPath(model);
+ if (path) activateLsp(path);
+}
+/** Starts language features for a file (its language servers open it). */
+export function activateLsp(path: string) {
+ if (!current || !useEditorStore.getState().languageFeatures || isLspActive(path)) return;
+ const key = activationKey(path);
+ useLspActivation.setState((state) => ({ active: { ...state.active, [key]: true } }));
+}
+
+/** While the chat's agent works, no unsaved text goes to the language servers (its tools read their diagnostics). */
+export function setLspSessionBusy(busy: boolean) {
+ sessionBusy = busy;
+}
/** The Problems panel: diagnostics per project file, as the language servers last reported them. */
export const useProblemsStore = create<{
@@ -68,9 +103,14 @@ export function problemCounts(files: readonly ProblemFile[]) {
/** The workspace-relative path of an editor model, or null (baselines, other workspaces). */
function modelPath(model: MonacoApi.editor.ITextModel): string | null {
- if (!current || model.uri.scheme !== "omnirush-file") return null;
- if (model.uri.authority !== current.docs.uri("x").authority) return null;
- return model.uri.path.replace(/^\//, "");
+ return uriPath(model.uri);
+}
+
+/** The workspace-relative path of an editor URI of the current workspace, or null. */
+function uriPath(uri: MonacoApi.Uri): string | null {
+ if (!current || uri.scheme !== "omnirush-file") return null;
+ if (uri.authority !== current.docs.uri("x").authority) return null;
+ return uri.path.replace(/^\//, "");
}
/** A `file://` URI from a language server to a workspace path, or null when it is outside the project. */
@@ -94,9 +134,13 @@ function toMonacoRange(monaco: Monaco, range: LspRange): MonacoApi.IRange {
return new monaco.Range(range.start.line + 1, range.start.character + 1, range.end.line + 1, range.end.character + 1);
}
-function payloadFor(model: MonacoApi.editor.ITextModel, path: string, position?: MonacoApi.Position) {
+function isDirty(path: string): boolean {
const doc = current?.docs.get(path);
- const text = doc && current?.docs.isDirty(doc) ? model.getValue() : undefined;
+ return Boolean(doc && current?.docs.isDirty(doc));
+}
+
+function payloadFor(model: MonacoApi.editor.ITextModel, path: string, position?: MonacoApi.Position) {
+ const text = isDirty(path) && !sessionBusy ? model.getValue() : undefined;
return {
path,
...(position ? { line: position.lineNumber - 1, character: position.column - 1 } : {}),
@@ -104,10 +148,43 @@ function payloadFor(model: MonacoApi.editor.ITextModel, path: string, position?:
};
}
+/** One request per file at a time (the engine swaps a file's text in the language servers per request). */
+const lanes = new Map<string, Promise<unknown>>();
+function inLane<T>(path: string, run: () => Promise<T>): Promise<T> {
+ const key = activationKey(path);
+ const next = (lanes.get(key) ?? Promise.resolve()).then(run, run);
+ const settled = next.catch(() => undefined);
+ lanes.set(key, settled);
+ void settled.then(() => {
+ if (lanes.get(key) === settled) lanes.delete(key);
+ });
+ return next;
+}
+
+/**
+ * Whether this engine has the editor routes, checked once per workspace with an empty request before any file
+ * text is sent (an engine without them could hand an unknown request to something else).
+ */
+let support: Promise<boolean> | null = null;
+function supported(ctx: Context): Promise<boolean> {
+ support ??= ctx.client.editorLsp<unknown>(ctx.workspaceId, "diagnostics", {}).then((raw) => Array.isArray(raw), () => false);
+ return support;
+}
+
async function call<T>(op: Parameters<OmniRushServerClient["editorLsp"]>[1], payload: Parameters<OmniRushServerClient["editorLsp"]>[2]): Promise<T | null> {
- if (!current || unavailable) return null;
+ if (!current || unavailable || !useEditorStore.getState().languageFeatures) return null;
+ const ctx = current;
+ const path = typeof payload.path === "string" ? payload.path : null;
+ if (!(await supported(ctx))) {
+ if (current === ctx) {
+ unavailable = true;
+ useProblemsStore.getState().setAvailable(false);
+ }
+ return null;
+ }
try {
- return await current.client.editorLsp<T>(current.workspaceId, op, payload);
+ const run = () => ctx.client.editorLsp<T>(ctx.workspaceId, op, payload);
+ return await (path ? inLane(path, run) : run());
} catch (error) {
// An engine without the editor routes (older build): language features stay off quietly.
if ((error as { status?: number }).status === 404) {
@@ -174,12 +251,16 @@ function toDocumentSymbols(monaco: Monaco, raw: LspDocumentSymbol[]): MonacoApi.
/** Document symbols of a model (cached per version), for the outline and breadcrumbs. */
const symbolCache = new Map<string, { version: number; symbols: MonacoApi.languages.DocumentSymbol[] }>();
-export async function documentSymbols(model: MonacoApi.editor.ITextModel): Promise<MonacoApi.languages.DocumentSymbol[]> {
+export async function documentSymbols(model: MonacoApi.editor.ITextModel, options: { userAction?: boolean } = {}): Promise<MonacoApi.languages.DocumentSymbol[] | null> {
const path = modelPath(model);
if (!path || !current) return [];
+ if (options.userAction) activateLsp(path);
+ if (!isLspActive(path)) return null;
const key = model.uri.toString();
const cached = symbolCache.get(key);
if (cached && cached.version === model.getVersionId()) return cached.symbols;
+ // Unsaved text cannot be sent now: keep what the outline shows.
+ if (cached && isDirty(path) && sessionBusy) return cached.symbols;
const raw = await call<LspDocumentSymbol[]>("symbols", payloadFor(model, path));
const symbols = Array.isArray(raw) ? toDocumentSymbols(current.monaco, raw) : [];
symbolCache.set(key, { version: model.getVersionId(), symbols });
@@ -239,17 +320,38 @@ export function applyMarkers(path: string, diagnostics: readonly LspDiagnostic[]
})));
}
+/** Per file: a diagnostics request running, one more wanted after it (only the latest counts). */
+const diagnosticsRuns = new Map<string, { pending: boolean }>();
+
/** Diagnostics of one file (its unsaved text when dirty) into its squiggles and the Problems panel. */
export async function refreshFileDiagnostics(path: string): Promise<void> {
- if (!current) return;
+ if (!current || !isLspActive(path)) return;
const ctx = current;
- const doc = ctx.docs.get(path);
- if (!doc) return;
- const raw = await call<ProblemFile[]>("diagnostics", payloadFor(doc.model, path));
- if (!raw || current !== ctx) return;
- const file = raw.find((item) => item.path === path) ?? { path, diagnostics: [] };
- applyMarkers(path, file.diagnostics);
- useProblemsStore.getState().merge(ctx.workspaceId, file);
+ const key = activationKey(path);
+ const running = diagnosticsRuns.get(key);
+ if (running) {
+ running.pending = true;
+ return;
+ }
+ const run = { pending: true };
+ diagnosticsRuns.set(key, run);
+ try {
+ while (run.pending && current === ctx) {
+ run.pending = false;
+ const doc = ctx.docs.get(path);
+ // Unsaved text cannot be sent while the agent works, and the disk's diagnostics do not fit the buffer: keep the squiggles.
+ if (!doc || (isDirty(path) && sessionBusy)) return;
+ const version = doc.model.getVersionId();
+ const raw = await call<ProblemFile[]>("diagnostics", payloadFor(doc.model, path));
+ // An edit since the request: its result is already stale; the run after it applies.
+ if (!raw || current !== ctx || (doc.model.getVersionId() !== version && run.pending)) continue;
+ const file = raw.find((item) => item.path === path) ?? { path, diagnostics: [] };
+ applyMarkers(path, file.diagnostics);
+ useProblemsStore.getState().merge(ctx.workspaceId, file);
+ }
+ } finally {
+ diagnosticsRuns.delete(key);
+ }
}
/** Every diagnostic the language servers hold for the project (files they have seen). */
@@ -258,15 +360,32 @@ export async function refreshAllDiagnostics(): Promise<void> {
const ctx = current;
const raw = await call<ProblemFile[]>("diagnostics", {});
if (!raw || current !== ctx) return;
- useProblemsStore.getState().set(ctx.workspaceId, raw);
- for (const file of raw) applyMarkers(file.path, file.diagnostics);
+ // Files with unsaved changes keep what their own text gave (the servers hold the disk copy's).
+ const before = useProblemsStore.getState().byWorkspace[ctx.workspaceId] ?? [];
+ const dirty = new Set(raw.map((file) => file.path).concat(before.map((file) => file.path)).filter(isDirty));
+ const files = [...raw.filter((file) => !dirty.has(file.path)), ...before.filter((file) => dirty.has(file.path))];
+ useProblemsStore.getState().set(ctx.workspaceId, files.sort((a, b) => a.path.localeCompare(b.path)));
+ for (const file of raw) if (!dirty.has(file.path)) applyMarkers(file.path, file.diagnostics);
+}
+
+/** Language features turned off: squiggles and problems go, and files start again only after the dwell. */
+export function clearLanguageFeatures() {
+ if (current) {
+ const monaco = current.monaco;
+ for (const model of monaco.editor.getModels()) if (modelPath(model)) monaco.editor.setModelMarkers(model, "lsp", []);
+ useProblemsStore.getState().set(current.workspaceId, []);
+ }
+ useLspActivation.setState({ active: {} });
+ symbolCache.clear();
}
/** Where the editor's language features act now (the workspace shown). */
export function setLanguageContext(ctx: Context | null) {
current = ctx;
unavailable = false;
+ support = null;
symbolCache.clear();
+ diagnosticsRuns.clear();
useProblemsStore.getState().setAvailable(true);
}
@@ -277,8 +396,9 @@ export function installLanguageFeatures(monaco: Monaco) {
const selector = "*";
monaco.languages.registerHoverProvider(selector, {
provideHover: async (model, position) => {
+ // The mouse resting on a file just glanced at starts nothing: hover works once the file's features started.
const path = modelPath(model);
- if (!path) return null;
+ if (!path || !isLspActive(path)) return null;
const contents = hoverContents(await call("hover", payloadFor(model, path, position)));
return contents.length ? { contents } : null;
},
@@ -287,6 +407,7 @@ export function installLanguageFeatures(monaco: Monaco) {
provideDefinition: async (model, position) => {
const path = modelPath(model);
if (!path) return null;
+ activateLsp(path);
return toLocations(await call("definition", payloadFor(model, path, position)));
},
});
@@ -294,18 +415,27 @@ export function installLanguageFeatures(monaco: Monaco) {
provideReferences: async (model, position) => {
const path = modelPath(model);
if (!path) return null;
+ activateLsp(path);
return toLocations(await call("references", payloadFor(model, path, position)));
},
});
monaco.languages.registerDocumentSymbolProvider(selector, {
displayName: "Language server",
- provideDocumentSymbols: (model) => documentSymbols(model),
+ // Only go to symbol (Cmd/Ctrl+Shift+O) asks Monaco for symbols (sticky scroll uses indentation): an explicit request.
+ provideDocumentSymbols: async (model) => (await documentSymbols(model, { userAction: true })) ?? [],
});
+ // Monaco's standalone build only logs a rename's reject reason: say it as a toast too.
+ const reject = (reason: string) => {
+ toast.info(reason);
+ return { edits: [], rejectReason: reason };
+ };
monaco.languages.registerRenameProvider(selector, {
provideRenameEdits: async (model, position, newName) => {
const path = modelPath(model);
if (!path || !current) return null;
const ctx = current;
+ activateLsp(path);
+ if (isDirty(path) && sessionBusy) return reject("Save this file or wait for the agent to finish before renaming.");
const raw = await call<unknown[]>("rename", { ...payloadFor(model, path, position), newName });
const edits: MonacoApi.languages.IWorkspaceTextEdit[] = [];
type TextEdit = { range: LspRange; newText: string };
@@ -325,7 +455,13 @@ export function installLanguageFeatures(monaco: Monaco) {
if (change.textDocument?.uri && change.edits) await addEdits(change.textDocument.uri, change.edits);
}
}
- if (!edits.length) return { edits: [], rejectReason: "Nothing to rename here (or the language server cannot rename this)." };
+ if (!edits.length) return reject("Nothing to rename here (or the language server cannot rename this).");
+ // Other files' edits were computed on their saved text: refuse rather than misplace them in unsaved buffers.
+ const otherDirty = edits.some((edit) => {
+ const target = uriPath(edit.resource);
+ return target !== null && target !== path && isDirty(target);
+ });
+ if (otherDirty) return reject("Save your other changes before renaming.");
return { edits };
},
});
@@ -360,8 +496,8 @@ export function installLanguageFeatures(monaco: Monaco) {
// Go to definition / references into another file: open it as a tab.
monaco.editor.registerEditorOpener({
openCodeEditor: (_source, resource, selectionOrPosition) => {
- if (!current || resource.scheme !== "omnirush-file") return false;
- const path = resource.path.replace(/^\//, "");
+ const path = uriPath(resource);
+ if (!current || !path) return false;
const at = selectionOrPosition && "startLineNumber" in selectionOrPosition
? { line: selectionOrPosition.startLineNumber, column: selectionOrPosition.startColumn }
: selectionOrPosition && "lineNumber" in selectionOrPosition
diff --git a/apps/app/src/react-app/domains/session/editor/outline-view.tsx b/apps/app/src/react-app/domains/session/editor/outline-view.tsx
index d953365f..8045a507 100644
--- a/apps/app/src/react-app/domains/session/editor/outline-view.tsx
+++ b/apps/app/src/react-app/domains/session/editor/outline-view.tsx
@@ -5,7 +5,8 @@ import { ChevronDown, ChevronRight } from "lucide-react";
import type * as MonacoApi from "monaco-editor/editor/editor.api.js";
import { cn } from "@/lib/utils";
-import { documentSymbols } from "./lsp";
+import { useEditorStore } from "./editor-store";
+import { documentSymbols, useIsLspActive } from "./lsp";
// Monaco SymbolKind (0-based): a short mark per kind.
const KIND_MARK: Record<number, { mark: string; className: string }> = {
@@ -54,6 +55,8 @@ export function OutlineView(props: { model: MonacoApi.editor.ITextModel | null;
const [open, setOpen] = useState(true);
const [symbols, setSymbols] = useState<MonacoApi.languages.DocumentSymbol[] | null>(null);
const [tick, setTick] = useState(0);
+ const active = useIsLspActive(props.path);
+ const languageFeatures = useEditorStore((state) => state.languageFeatures);
useEffect(() => {
const model = props.model;
@@ -78,7 +81,7 @@ export function OutlineView(props: { model: MonacoApi.editor.ITextModel | null;
cancelled = true;
window.clearTimeout(timer);
};
- }, [open, props.model, tick]);
+ }, [open, props.model, tick, active]);
return (
<div className={cn("flex min-h-0 flex-col border-t border-border text-xs", open ? "max-h-[45%]" : "")} data-editor-outline>
@@ -90,7 +93,8 @@ export function OutlineView(props: { model: MonacoApi.editor.ITextModel | null;
{open ? (
<div className="min-h-0 overflow-y-auto px-1 pb-2">
{!props.model ? <p className="px-2 text-muted-foreground">Open a file to see its symbols.</p>
- : symbols === null ? <p className="px-2 text-muted-foreground">Loading symbols…</p>
+ : !languageFeatures ? <p className="px-2 text-muted-foreground">Language features in the editor are off.</p>
+ : symbols === null ? <p className="px-2 text-muted-foreground">{active ? "Loading symbols…" : "Symbols show once the file has been open a moment."}</p>
: symbols.length === 0 ? <p className="px-2 text-muted-foreground">No symbols (no language server for this file, or none found).</p>
: symbols.map((symbol, index) => <SymbolRow key={`${symbol.name}:${index}`} symbol={symbol} depth={0} onReveal={props.onReveal} />)}
</div>
diff --git a/apps/app/src/react-app/domains/session/editor/problems-view.tsx b/apps/app/src/react-app/domains/session/editor/problems-view.tsx
index 859c5617..fec8fa10 100644
--- a/apps/app/src/react-app/domains/session/editor/problems-view.tsx
+++ b/apps/app/src/react-app/domains/session/editor/problems-view.tsx
@@ -10,6 +10,7 @@ import { AlertTriangle, ChevronDown, ChevronRight, CircleX, Info, RefreshCw, Spa
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
+import { useEditorStore } from "./editor-store";
import { diagnosticCode, problemCounts, useProblemsStore, type LspDiagnostic } from "./lsp";
const EMPTY: never[] = [];
@@ -23,6 +24,8 @@ export function ProblemsView(props: {
}) {
const files = useProblemsStore((state) => state.byWorkspace[props.workspaceId] ?? EMPTY);
const available = useProblemsStore((state) => state.available);
+ const languageFeatures = useEditorStore((state) => state.languageFeatures);
+ const setLanguageFeatures = useEditorStore((state) => state.setLanguageFeatures);
const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});
const [errorsOnly, setErrorsOnly] = useState(false);
const counts = problemCounts(files);
@@ -39,6 +42,10 @@ export function ProblemsView(props: {
<span>{counts.errors} error{counts.errors === 1 ? "" : "s"}, {counts.warnings} warning{counts.warnings === 1 ? "" : "s"}</span>
<span className="text-[11px]">· files the language servers have open</span>
<span className="flex-1" />
+ <label className="flex items-center gap-1" title="Problems, hover, go to definition, rename and outline from the project's language servers">
+ <input type="checkbox" checked={languageFeatures} onChange={(event) => setLanguageFeatures(event.target.checked)} data-editor-language-features />
+ Language features
+ </label>
<label className="flex items-center gap-1">
<input type="checkbox" checked={errorsOnly} onChange={(event) => setErrorsOnly(event.target.checked)} />
Errors only
@@ -48,7 +55,12 @@ export function ProblemsView(props: {
</Button>
</div>
<div className="min-h-0 flex-1 overflow-y-auto py-1">
- {!available ? (
+ {!languageFeatures ? (
+ <p className="px-3 py-2 text-muted-foreground">
+ Language features in the editor are off, so no language server starts for the files you open.{" "}
+ <button type="button" className="text-foreground underline underline-offset-2" onClick={() => setLanguageFeatures(true)}>Turn on</button>
+ </p>
+ ) : !available ? (
<p className="px-3 py-2 text-muted-foreground">This engine build has no editor language features yet; problems show once it updates.</p>
) : shown.length === 0 ? (
<p className="px-3 py-2 text-muted-foreground">No problems in the files the language servers have open. Open a file to check it.</p>
diff --git a/apps/app/src/react-app/domains/session/editor/search-view.tsx b/apps/app/src/react-app/domains/session/editor/search-view.tsx
index 0491a31e..6556e223 100644
--- a/apps/app/src/react-app/domains/session/editor/search-view.tsx
+++ b/apps/app/src/react-app/domains/session/editor/search-view.tsx
@@ -27,13 +27,25 @@ function matcher(query: string, flags: Flags): RegExp | null {
}
}
-/** The replacement for one matched text ($1… groups in regex mode). */
-export function replacementFor(matched: string, query: string, replace: string, flags: Flags): string {
- if (!flags.regex) return replace;
- const re = matcher(query, { ...flags });
- if (!re) return replace;
- re.lastIndex = 0;
- return matched.replace(new RegExp(re.source, re.flags.replace("g", "")), replace);
+/** A sticky copy of the search: it matches exactly at `lastIndex`, with the whole line as context (\b, lookarounds). */
+function stickyMatcher(query: string, flags: Flags): RegExp | null {
+ const re = matcher(query, flags);
+ return re ? new RegExp(re.source, `${re.flags.replace("g", "")}y`) : null;
+}
+
+/**
+ * The text that replaces the match at [start, end) of `line` ($1… groups in regex mode), or null when the
+ * search no longer matches exactly there.
+ */
+export function replacementAt(line: string, start: number, end: number, replace: string, sticky: RegExp | null, regex: boolean): string | null {
+ if (!sticky) return null;
+ sticky.lastIndex = start;
+ const found = sticky.exec(line);
+ if (!found || found[0].length !== end - start) return null;
+ if (!regex) return replace;
+ sticky.lastIndex = start;
+ const replaced = line.replace(sticky, replace);
+ return replaced.slice(start, replaced.length - (line.length - end));
}
type Target = { path: string; line: number; start: number; end: number };
@@ -118,6 +130,7 @@ export function SearchView(props: {
matches: file.matches.filter((match, index) => !dismissed[`${file.path}:${index}`]).map((match) => ({ ...match, key: `${file.path}:${file.matches.indexOf(match)}` })),
})).filter((file) => file.matches.length && !dismissed[file.path]), [dismissed, result]);
const total = visible.reduce((sum, file) => sum + file.matches.length, 0);
+ const previewMatcher = useMemo(() => stickyMatcher(query, flags), [flags, query]);
/** Replaces the given matches: in each file's document (open or loaded now), one undo step per file, then saved. */
const apply = async (targets: Target[]) => {
@@ -125,6 +138,8 @@ export function SearchView(props: {
for (const target of targets) byFile.set(target.path, [...(byFile.get(target.path) ?? []), target]);
let changed = 0;
let failed = 0;
+ let leftUnsaved = 0;
+ const sticky = stickyMatcher(query, flags);
for (const [path, list] of byFile) {
const opened = await props.docs.open(path);
if (!opened.ok) {
@@ -132,27 +147,29 @@ export function SearchView(props: {
continue;
}
const model = opened.doc.model;
+ // A file with unsaved changes of yours is edited but not saved (saving would also save your changes).
+ const wasDirty = props.docs.isDirty(opened.doc);
const edits: { range: { startLineNumber: number; startColumn: number; endLineNumber: number; endColumn: number }; text: string }[] = [];
for (const target of list) {
if (target.line > model.getLineCount()) continue;
- const lineText = model.getLineContent(target.line);
- const matched = lineText.slice(target.start, target.end);
// The file may have changed since the search: only a match that is still there is replaced.
- const re = matcher(query, flags);
- if (!re) continue;
- re.lastIndex = 0;
- const still = new RegExp(re.source, re.flags.replace("g", "")).exec(matched);
- if (!still || still.index !== 0 || still[0].length !== matched.length) {
+ const text = replacementAt(model.getLineContent(target.line), target.start, target.end, replace, sticky, flags.regex);
+ if (text === null) {
failed += 1;
continue;
}
edits.push({
range: { startLineNumber: target.line, startColumn: target.start + 1, endLineNumber: target.line, endColumn: target.end + 1 },
- text: replacementFor(matched, query, replace, flags),
+ text,
});
}
if (!edits.length) continue;
model.pushEditOperations([], edits, () => null);
+ if (wasDirty) {
+ changed += edits.length;
+ leftUnsaved += 1;
+ continue;
+ }
const saved = await props.docs.save(path, { sessionId: props.sessionId, source: "editor" });
if (saved.ok) changed += edits.length;
else {
@@ -160,7 +177,10 @@ export function SearchView(props: {
toast.error(`${path}: ${saved.message}`);
}
}
- if (changed) toast.success(`Replaced ${changed} match${changed === 1 ? "" : "es"}${failed ? `; ${failed} skipped` : ""}.`);
+ if (changed) {
+ const unsaved = leftUnsaved ? ` ${leftUnsaved} file${leftUnsaved === 1 ? "" : "s"} with your unsaved changes ${leftUnsaved === 1 ? "was" : "were"} left unsaved.` : "";
+ toast.success(`Replaced ${changed} match${changed === 1 ? "" : "es"}${failed ? `; ${failed} skipped` : ""}.${unsaved}`);
+ }
else if (failed) toast.error("Nothing replaced: the files changed since the search. Search again.");
props.onSaved();
setRerun((value) => value + 1);
@@ -308,7 +328,7 @@ export function SearchView(props: {
{showReplace && replace !== undefined ? (
<>
<span className="bg-red-3 text-red-11 line-through dark:bg-red-5/40">{hit}</span>
- <span className="bg-green-3 text-green-11 dark:bg-green-5/40">{replacementFor(hit, query, replace, flags)}</span>
+ <span className="bg-green-3 text-green-11 dark:bg-green-5/40">{replacementAt(match.text, match.start, match.end, replace, previewMatcher, flags.regex) ?? replace}</span>
</>
) : (
<span className="rounded-sm bg-amber-4 text-foreground dark:bg-amber-6/60">{hit}</span>
diff --git a/apps/app/src/react-app/shell/session-route.tsx b/apps/app/src/react-app/shell/session-route.tsx
index 1876aa01..b348f873 100644
--- a/apps/app/src/react-app/shell/session-route.tsx
+++ b/apps/app/src/react-app/shell/session-route.tsx
@@ -2926,6 +2926,7 @@ export function SessionRoute() {
};
}, [selectedSessionId]);
+ const editorLanguageFeatures = useEditorStore((state) => state.languageFeatures);
const layoutModeName = useEditorStore((state) => (selectedWorkspaceId ? state.modeByWorkspace[selectedWorkspaceId] : undefined) ?? "chat");
const layoutAvailable = isElectronRuntime() && Boolean(selectedWorkspace) && selectedWorkspace?.workspaceType !== "remote";
const layoutPaletteItems = useMemo<PaletteItem[]>(() => layoutAvailable ? [
@@ -2958,6 +2959,16 @@ export function SessionRoute() {
},
})) : []),
...(layoutModeName === "ide" ? [{
+ id: "editor.language-features",
+ title: editorLanguageFeatures ? "Turn off language features in the editor" : "Turn on language features in the editor",
+ detail: "Problems, hover, go to definition, rename and outline from the project's language servers",
+ meta: "",
+ searchText: "editor ide language features lsp problems hover rename outline server off on",
+ action: () => {
+ setCommandPaletteOpen(false);
+ useEditorStore.getState().setLanguageFeatures(!editorLanguageFeatures);
+ },
+ }, {
id: "layout.chat-panel",
title: "Show or hide the chat",
detail: "Fold the chat panel of the IDE layout away, or bring it back",
diff --git a/apps/server/src/editor-search.e2e.test.ts b/apps/server/src/editor-search.e2e.test.ts
index 3d06c6b5..6801cd5d 100644
--- a/apps/server/src/editor-search.e2e.test.ts
+++ b/apps/server/src/editor-search.e2e.test.ts
@@ -63,3 +63,21 @@ test("bad input is refused", () => {
expect(() => parseSearchOptions({ query: "(", regex: true })).toThrow();
expect(parseSearchOptions({ query: "x", include: ["../etc/*", "/abs", "src/**"] }).include).toEqual(["src/**"]);
});
+
+test("git grep: a file name holding `:1:` is read whole, and a failing git is an error", async () => {
+ const root = await project();
+ await writeFile(join(root, "src", "we:1:ird.ts"), "limit\n");
+ const result = await searchWorkspace(root, options({ include: ["src/we*"] }), null);
+ expect(result.files.map((file) => file.path)).toEqual(["src/we:1:ird.ts"]);
+ // A pattern git refuses (no closing bracket in either regex syntax) comes back as an error, not "0 results".
+ await expect(searchWorkspace(root, { ...options({ regex: true }), query: "lim[it" }, null)).rejects.toThrow();
+});
+
+test("ripgrep from the desktop engine's data folder", async () => {
+ const userData = await mkdtemp(join(tmpdir(), "omnirush-userdata-"));
+ roots.push(userData);
+ const name = process.platform === "win32" ? "rg.exe" : "rg";
+ await mkdir(join(userData, "engine-data", "omnirush", "bin"), { recursive: true });
+ await writeFile(join(userData, "engine-data", "omnirush", "bin", name), "");
+ expect(findRipgrep({ PATH: "", OMNIRUSH_DESKTOP_USER_DATA_DIR: userData, HOME: userData })).toBe(join(userData, "engine-data", "omnirush", "bin", name));
+});
diff --git a/apps/server/src/routes/editor-search.ts b/apps/server/src/routes/editor-search.ts
index 1245818d..81b4b691 100644
--- a/apps/server/src/routes/editor-search.ts
+++ b/apps/server/src/routes/editor-search.ts
@@ -7,8 +7,8 @@
*/
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
-import { homedir } from "node:os";
import { 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";
import { addRoute, type Route } from "./registry.js";
@@ -43,16 +43,18 @@ type RegisterOptions = {
resolveWorkspace: (config: ServerConfig, id: string) => Promise<WorkspaceInfo>;
};
-/** ripgrep: on PATH, or where the engine puts its own copy. */
+/** 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 dataHome = env.XDG_DATA_HOME || join(homedir(), ".local", "share");
- const engineCopy = join(dataHome, "omnirush", "bin", name);
- return existsSync(engineCopy) ? engineCopy : null;
+ for (const dataDir of [engineDataDir(env), join(userDataHome(env), "omnirush")]) {
+ const engineCopy = join(dataDir, "bin", name);
+ if (existsSync(engineCopy)) return engineCopy;
+ }
+ return null;
}
function globList(value: unknown): string[] {
@@ -165,7 +167,8 @@ export async function searchWorkspace(root: string, options: SearchOptions, rg =
};
if (rg) {
- const args = ["--json", "--no-config", "--max-columns", "2000", "--max-filesize", "5M", "--no-follow"];
+ // `--path-separator /`: Windows paths come back as `src/a.ts`, like everywhere else.
+ const args = ["--json", "--no-config", "--max-columns", "2000", "--max-filesize", "5M", "--no-follow", "--path-separator", "/"];
if (!options.regex) args.push("--fixed-strings");
if (options.caseSensitive) args.push("--case-sensitive");
else args.push("--ignore-case");
@@ -197,32 +200,44 @@ export async function searchWorkspace(root: string, options: SearchOptions, rg =
}
// No ripgrep: git grep in a repository (tracked and untracked, ignored files left out), matched again here for columns.
+ // Plain text is a fixed string (-F). A regex tries Perl syntax (-P, closest to the editor's) and, where git has no
+ // PCRE (Apple's git), extended syntax (-E). A failing git is an error, never an empty result.
if (!existsSync(resolve(root, ".git"))) return { engine: "none", files: [], matchCount: 0, truncated: false, timedOut: false };
const source = options.regex ? options.query : options.query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const pattern = new RegExp(options.wholeWord ? `\\b(?:${source})\\b` : source, options.caseSensitive ? "g" : "gi");
- const args = ["-c", "core.quotePath=false", "grep", "-n", "-I", "--untracked", "--exclude-standard", "--full-name", "-P"];
- if (!options.caseSensitive) args.push("-i");
- if (options.wholeWord) args.push("-w");
- // Pathspecs are OR-ed: with include globs, those alone (not "."), then the excludes.
- args.push("-e", options.regex ? options.query : source, "--");
- if (options.include.length) for (const glob of options.include) args.push(`:(glob)${glob}`);
- else args.push(".");
- for (const glob of options.exclude) args.push(`:(exclude,glob)${glob}`);
- const outcome = await run("git", args, root, (line) => {
- const hit = /^(.*?):(\d+):(.*)$/.exec(line);
- if (!hit) return true;
- const [, path, lineNumber, text] = hit;
- pattern.lastIndex = 0;
- let found: RegExpExecArray | null;
- while ((found = pattern.exec(text!)) !== null) {
- if (found[0].length === 0) {
- pattern.lastIndex += 1;
- continue;
+ const gitGrep = async (syntax: "-F" | "-P" | "-E") => {
+ const args = ["-c", "core.quotePath=false", "grep", "-n", "-z", "-I", "--untracked", "--exclude-standard", "--full-name", syntax];
+ if (!options.caseSensitive) args.push("-i");
+ if (options.wholeWord) args.push("-w");
+ // Pathspecs are OR-ed: with include globs, those alone (not "."), then the excludes.
+ args.push("-e", options.query, "--");
+ if (options.include.length) for (const glob of options.include) args.push(`:(glob)${glob}`);
+ else args.push(".");
+ for (const glob of options.exclude) args.push(`:(exclude,glob)${glob}`);
+ // -z: `path\0line\0text`, so a file name with `:12:` in it cannot be mis-split.
+ return run("git", args, root, (line) => {
+ const [path, lineNumber, ...rest] = line.split("\0");
+ if (!path || !lineNumber || !rest.length) return true;
+ const text = rest.join("\0");
+ pattern.lastIndex = 0;
+ let found: RegExpExecArray | null;
+ while ((found = pattern.exec(text)) !== null) {
+ if (found[0].length === 0) {
+ pattern.lastIndex += 1;
+ continue;
+ }
+ if (!add(path, { line: Number(lineNumber), ...cutLine(text, found.index, found.index + found[0].length) })) return false;
}
- if (!add(path!, { line: Number(lineNumber), ...cutLine(text!, found.index, found.index + found[0].length) })) return false;
- }
- return true;
- });
+ return true;
+ });
+ };
+ let outcome = await gitGrep(options.regex ? "-P" : "-F");
+ if (options.regex && outcome.code === 128 && !matchCount && /perl|pcre/i.test(outcome.stderr)) outcome = await gitGrep("-E");
+ // 0 = matches, 1 = none; anything else (128: bad pattern, no PCRE …) is an error unless matching was cut short on purpose.
+ if (outcome.code !== null && outcome.code > 1 && !truncated && !outcome.timedOut) {
+ const message = outcome.stderr.replace(/^fatal:\s*/i, "").trim().slice(0, 300) || "git grep failed";
+ throw new ApiError(400, options.regex ? "invalid_regex" : "search_failed", message);
+ }
return { engine: "git", files: [...files].map(([path, matches]) => ({ path, matches })), matchCount, truncated, timedOut: outcome.timedOut };
}