A desktop coding agent with free access to frontier models.
TypeScript
feat: search, problems, outline and agent actions in the editor
ogsamratdde932b3e345
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.tsindex f5a194fa..1d22ab02 100644--- a/apps/app/src/app/lib/omnirush-server.ts+++ b/apps/app/src/app/lib/omnirush-server.ts@@ -1664,6 +1664,14 @@ async function fetchWithTimeout(}}+export type OmniRushEditorSearchMatch = { line: number; text: string; start: number; end: number; textOffset: number };+export type OmniRushEditorSearchResult = {+ engine: "ripgrep" | "git" | "none";+ files: Array<{ path: string; matches: OmniRushEditorSearchMatch[] }>;+ matchCount: number;+ truncated: boolean;+ timedOut: boolean;+};export type OmniRushEditorTree = { git: boolean; files: string[]; truncated: boolean; generatedAt: number };export type OmniRushEditorFile = {path: string;@@ -2808,6 +2816,36 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: s) =>requestJson<{ ok: true }>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/editor/review`, { token, hostToken, method: "POST", body: payload }),+ editorSearch: (+ workspaceId: string,+ payload: { query: string; regex?: boolean; caseSensitive?: boolean; wholeWord?: boolean; include?: string[]; exclude?: string[]; maxMatches?: number },+ signal?: AbortSignal,+ ) =>+ requestJson<OmniRushEditorSearchResult>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/editor/search`, {+ token,+ hostToken,+ method: "POST",+ body: payload,+ timeoutMs: 30_000,+ signal,+ }),++ /** The engine's language features for the editor (the project's own language servers); see the engine's /editor routes. */+ editorLsp: <T = unknown>(+ workspaceId: string,+ op: "diagnostics" | "hover" | "definition" | "references" | "symbols" | "rename",+ payload: { path?: string; line?: number; character?: number; newName?: string; text?: string },+ signal?: AbortSignal,+ ) =>+ requestJson<T>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/opencode/editor/lsp/${op}`, {+ token,+ hostToken,+ method: "POST",+ body: payload,+ timeoutMs: op === "diagnostics" ? 45_000 : 20_000,+ signal,+ }),+editorGitStatus: (workspaceId: string) =>requestJson<OmniRushEditorGitStatus>(baseUrl, `/workspace/${encodeURIComponent(workspaceId)}/editor/git/status`, { token, hostToken, timeoutMs: 30_000 }),diff --git a/apps/app/src/react-app/domains/session/editor/chat-context.ts b/apps/app/src/react-app/domains/session/editor/chat-context.tsnew file mode 100644index 00000000..d145727d--- /dev/null+++ b/apps/app/src/react-app/domains/session/editor/chat-context.ts@@ -0,0 +1,52 @@+/**+ * The editor's hand-off to the chat ("Ask about selection", "Explain",+ * "Refactor", "Write tests", "Fix with agent"): the code or the problem goes+ * into the chat's composer as a removable chip with its file and lines, and+ * an instruction is prefilled. Nothing is sent: the user reads, edits and+ * sends it (a busy chat queues it as usual).+ */+import { useComposerStateStore } from "../surface/composer-state-store";+import { useEditorStore } from "./editor-store";++export type ChatContextChip = {+ /** What the chip shows: `src/orders.ts L5–6 · selection` (no square brackets). */+ label: string;+ /** What the agent receives in place of the chip. */+ text: string;+};++export type ChatHandoffResult = { ok: true } | { ok: false; reason: string };++export function sendToChat(sessionId: string | null, instruction: string, chips: ChatContextChip[]): ChatHandoffResult {+ if (!sessionId) return { ok: false, reason: "Open or start a chat first." };+ const store = useComposerStateStore.getState();+ const state = store.sessions[sessionId];+ const draft = state?.draft ?? "";+ const parts = state?.pasteParts ?? [];+ const made = chips.map((chip) => ({+ id: `editor-${Math.random().toString(36).slice(2)}`,+ label: chip.label.replace(/[[\]]/g, "").slice(0, 120),+ text: chip.text,+ lines: chip.text.split(/\r?\n/).length,+ }));+ const placeholders = made.map((part) => `[pasted text ${part.label}]`).join(" ");+ const lead = draft.trim() ? `${draft.replace(/\s+$/, "")}\n` : "";+ store.setPasteParts(sessionId, [...parts, ...made]);+ store.replaceDraft(sessionId, `${lead}${instruction}${instruction && placeholders ? "\n" : ""}${placeholders}`);+ // The chat panel opens if it was folded away, and the composer takes the focus.+ useEditorStore.getState().setIdeChatCollapsed(false);+ window.setTimeout(() => window.dispatchEvent(new Event("omnirush:focusPrompt")), 50);+ return { ok: true };+}++/** A fenced code block for the agent: the file, its lines, and the code. */+export function codeChipText(path: string, startLine: number, endLine: number, language: string, code: string): string {+ const fence = code.includes("```") ? "````" : "```";+ return `${path} lines ${startLine}-${endLine}:\n${fence}${language}\n${code.replace(/\s+$/, "")}\n${fence}`;+}++export function lineLabel(path: string, startLine: number, endLine: number, column?: number): string {+ const name = path.split("/").pop() ?? path;+ if (column !== undefined && startLine === endLine) return `${name} L${startLine}:C${column}`;+ return startLine === endLine ? `${name} L${startLine}` : `${name} L${startLine}–${endLine}`;+}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 687ec7ab..4d272d8f 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@@ -24,6 +24,8 @@ import {Plus,RefreshCw,Search,+ CircleX,+ AlertTriangle,SquareTerminal,Undo2,X,@@ -45,6 +47,22 @@ import { EditorSurface, type SurfaceDoc } from "./editor-surface";import { acceptHunk, hunkCounts, rejectHunk, type LineHunk } from "./hunk-ops";import { languageForPath, setupMonaco, type Monaco } from "./monaco";import { QuickOpen } from "./quick-open";+import { SearchView } from "./search-view";+import { ProblemsView } from "./problems-view";+import { OutlineView } from "./outline-view";+import { codeChipText, lineLabel, sendToChat } from "./chat-context";+import {+ documentSymbols,+ installLanguageFeatures,+ problemCounts,+ refreshAllDiagnostics,+ refreshFileDiagnostics,+ setLanguageContext,+ symbolPath,+ useProblemsStore,+ type LspDiagnostic,+} from "./lsp";+import type { AgentAction, SurfaceHandle } from "./editor-surface";import { baselinesForTurns, turnFileChange, type TurnFileChange } from "./review";import "./editor.css";@@ -513,6 +531,15 @@ export default function EditorPanel(props: EditorPanelProps) {const sideOpen = useEditorStore((store) => store.sideOpen);const activeTab = state.tabs.find((tab) => tab.id === state.activeId) ?? null;const [surface, setSurface] = useState<SurfaceDoc | null>(null);+ const surfaceHandle = useRef<SurfaceHandle | null>(null);+ const pendingReveal = useRef<{ path: string; line: number; column: number; endColumn?: number } | null>(null);+ const [searchFocus, setSearchFocus] = useState(0);+ const [problemsLoading, setProblemsLoading] = useState(false);+ const [breadcrumbSymbols, setBreadcrumbSymbols] = useState<string[]>([]);+ const problemsOpen = useEditorStore((store) => store.problemsOpen);+ const bottomTab = useEditorStore((store) => store.bottomTab);+ const problemFiles = useProblemsStore((store) => store.byWorkspace[workspaceId]);+ const problemTotals = problemCounts(problemFiles ?? []);const [tabError, setTabError] = useState<string | null>(null);const [cursor, setCursor] = useState<{ line: number; column: number } | null>(null);const [hunks, setHunks] = useState<LineHunk[]>([]);@@ -553,6 +580,7 @@ export default function EditorPanel(props: EditorPanelProps) {useEffect(() => {if (wasBusy.current && !sessionBusy) {void docs.refresh().then(() => setDocsTick((value) => value + 1));+ void refreshAllDiagnostics();void queryClient.invalidateQueries({ queryKey: ["editor-tree", workspaceId] });void queryClient.invalidateQueries({ queryKey: ["editor-git", workspaceId] });void queryClient.invalidateQueries({ queryKey: ["editor-changes", workspaceId] });@@ -747,6 +775,69 @@ export default function EditorPanel(props: EditorPanelProps) {useEditorStore.getState().openTab(workspaceId, { id: tabId({ kind: "file", path }), kind: "file", path });recentRef.current = [path, ...recentRef.current.filter((item) => item !== path)].slice(0, 30);}, [workspaceId]);+ /** Opens a file and puts the cursor at a 1-based position (search results, problems, go to definition). */+ const openAt = useCallback((path: string, line: number, column: number, endColumn?: number) => {+ pendingReveal.current = { path, line, column, endColumn };+ openFile(path);+ const current = useEditorStore.getState().byWorkspace[workspaceId];+ const active = current?.tabs.find((tab) => tab.id === current.activeId);+ if (active?.path === path && surfaceHandle.current) {+ surfaceHandle.current.reveal(line, column, endColumn);+ pendingReveal.current = null;+ }+ }, [openFile, workspaceId]);++ const handoff = useCallback((instruction: string, chips: { label: string; text: string }[]) => {+ const result = sendToChat(sessionId, instruction, chips);+ if (!result.ok) toast(result.reason);+ }, [sessionId]);++ const fixWithAgent = useCallback((path: string, diagnostic: LspDiagnostic) => {+ const doc = docs.get(path);+ const line = diagnostic.range.start.line + 1;+ const from = Math.max(1, line - 3);+ const to = doc ? Math.min(doc.model.getLineCount(), diagnostic.range.end.line + 4) : line;+ const code = doc ? doc.model.getValueInRange({ startLineNumber: from, startColumn: 1, endLineNumber: to, endColumn: doc.model.getLineMaxColumn(to) }) : "";+ const where = `L${line}:C${diagnostic.range.start.character + 1}`;+ const source = diagnostic.source ? `${diagnostic.source}${diagnostic.code !== undefined ? ` ${typeof diagnostic.code === "object" ? diagnostic.code.value : diagnostic.code}` : ""}: ` : "";+ handoff("Fix this problem:", [{+ label: `${path.split("/").pop()} ${where} · ${diagnostic.message.split("\n")[0]!.slice(0, 50)}`,+ text: `${path} ${where}: ${source}${diagnostic.message}${code ? `\n${codeChipText(path, from, to, doc ? languageForPath(path) : "", code)}` : ""}`,+ }]);+ }, [docs, handoff]);++ const agentAction = useCallback((action: AgentAction, editor: import("monaco-editor/editor/editor.api.js").editor.ICodeEditor) => {+ const model = editor.getModel();+ const selection = editor.getSelection();+ if (!model || !selection || model.uri.scheme !== "omnirush-file") return;+ const path = model.uri.path.replace(/^\//, "");+ let range = selection;+ if (selection.isEmpty()) {+ // No selection: the line under the cursor.+ const line = selection.startLineNumber;+ range = new monaco.Selection(line, 1, line, model.getLineMaxColumn(line));+ }+ const code = model.getValueInRange(range);+ const chip = {+ label: `${lineLabel(path, range.startLineNumber, range.endLineNumber)} · selection`,+ text: codeChipText(path, range.startLineNumber, range.endLineNumber, model.getLanguageId(), code),+ };+ const instruction = action === "explain" ? "Explain what this code does and why."+ : action === "refactor" ? "Refactor this code: "+ : action === "tests" ? "Write tests for this code with the project's test setup, and run them."+ : "";+ handoff(instruction, [chip]);+ }, [handoff, monaco]);++ // The language features act on this workspace while the editor shows it.+ useEffect(() => {+ installLanguageFeatures(monaco);+ setLanguageContext({ monaco, client, workspaceId, workspaceRoot, docs, openAt: (path, line, column) => openAt(path, line, column), fixWithAgent });+ setProblemsLoading(true);+ void refreshAllDiagnostics().finally(() => setProblemsLoading(false));+ return () => setLanguageContext(null);+ }, [client, docs, fixWithAgent, monaco, openAt, workspaceId, workspaceRoot]);+const openReview = useCallback((file: ReviewFile) => {if (file.baseline === undefined) {openFile(file.path);@@ -836,6 +927,47 @@ export default function EditorPanel(props: EditorPanelProps) {// reviewFiles changes identity per fetch; the key carries what matters.}, [activeTab, docs, client, workspaceId, reviewKey, changesQuery.isFetching, docsTick]);+ useEffect(() => {+ const reveal = pendingReveal.current;+ if (!reveal || !surface || !activeTab || activeTab.path !== reveal.path) return;+ pendingReveal.current = null;+ 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).+ useEffect(() => {+ if (!surface || surface.kind !== "file") return;+ const doc = surface.doc;+ void refreshFileDiagnostics(doc.path);+ let timer = 0;+ const subscription = doc.model.onDidChangeContent(() => {+ window.clearTimeout(timer);+ timer = window.setTimeout(() => void refreshFileDiagnostics(doc.path), 1200);+ });+ return () => {+ window.clearTimeout(timer);+ subscription.dispose();+ };+ }, [surface]);++ // Breadcrumbs: the symbols around the cursor.+ useEffect(() => {+ if (!surface || surface.kind !== "file" || !cursor) {+ setBreadcrumbSymbols([]);+ return;+ }+ 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));+ });+ }, 300);+ return () => {+ cancelled = true;+ window.clearTimeout(timer);+ };+ }, [cursor, surface]);+// ── save ───────────────────────────────────────────────────────────────const save = useCallback(async (options: { force?: boolean } = {}) => {if (!activeTab) return;@@ -844,6 +976,7 @@ export default function EditorPanel(props: EditorPanelProps) {if (!doc) return;const result = await docs.save(path, { sessionId, source: "editor", force: options.force });if (result.ok) {+ void refreshFileDiagnostics(path);void queryClient.invalidateQueries({ queryKey: ["editor-git", workspaceId] });if (!files.includes(path)) void queryClient.invalidateQueries({ queryKey: ["editor-tree", workspaceId] });return;@@ -882,6 +1015,30 @@ export default function EditorPanel(props: EditorPanelProps) {}}, [client, queryClient, workspaceId]);+ // Commands from the app's shortcuts and palette (use-shell-shortcuts.ts, session-route.tsx).+ useEffect(() => {+ const onCommand = (event: Event) => {+ const command = (event as CustomEvent<string>).detail;+ if (command === "search") {+ useEditorStore.getState().setView(workspaceId, "search");+ setSearchFocus((value) => value + 1);+ } else if (command === "problems") {+ useEditorStore.getState().setProblemsOpen(true);+ void refreshAllDiagnostics();+ } else if (command === "quick-open") {+ useEditorStore.getState().setQuickOpen(true);+ } else if (command === "symbol") {+ const editor = surfaceHandle.current?.activeEditor();+ editor?.focus();+ editor?.trigger("palette", "editor.action.quickOutline", null);+ } else if (command === "outline") {+ useEditorStore.getState().setView(workspaceId, "files");+ }+ };+ window.addEventListener("omnirush:editor-command", onCommand);+ return () => window.removeEventListener("omnirush:editor-command", onCommand);+ }, [workspaceId]);+// ── keys ───────────────────────────────────────────────────────────────const panelRef = useRef<HTMLDivElement | null>(null);useEffect(() => {@@ -917,7 +1074,19 @@ export default function EditorPanel(props: EditorPanelProps) {const side = (<div className="flex h-full min-h-0 flex-col border-e border-border bg-muted/20">- {state.view === "files" ? (+ {state.view === "search" ? (+ <SearchView+ client={client}+ workspaceId={workspaceId}+ docs={docs}+ sessionId={sessionId}+ focusNonce={searchFocus}+ onOpen={openAt}+ onSaved={() => void queryClient.invalidateQueries({ queryKey: ["editor-git", workspaceId] })}+ />+ ) : state.view === "files" ? (+ <div className="flex h-full min-h-0 flex-col">+ <div className="min-h-0 flex-1"><FilesViewfiles={files}truncated={Boolean(treeQuery.data?.truncated)}@@ -928,6 +1097,13 @@ export default function EditorPanel(props: EditorPanelProps) {onOpen={openFile}onRefresh={() => void treeQuery.refetch()}/>+ </div>+ <OutlineView+ model={surface?.kind === "file" ? surface.doc.model : null}+ path={surface?.kind === "file" ? surface.doc.path : null}+ onReveal={(line, column) => surfaceHandle.current?.reveal(line, column)}+ />+ </div>) : state.view === "changes" ? (<ChangesViewdata={review}@@ -1013,10 +1189,15 @@ export default function EditorPanel(props: EditorPanelProps) {) : activePath ? (<div className="flex h-6 shrink-0 items-center gap-1 border-b border-border px-3 text-[11px] text-muted-foreground" data-editor-breadcrumb>{activePath.split("/").map((part, index, parts) => (- <span key={`${index}:${part}`} className={cn(index === parts.length - 1 && "text-foreground")}>+ <span key={`${index}:${part}`} className={cn("shrink-0", index === parts.length - 1 && !breadcrumbSymbols.length && "text-foreground")}>{part}{index < parts.length - 1 ? <span className="mx-1 opacity-60">›</span> : null}</span>))}+ {breadcrumbSymbols.map((name, index) => (+ <span key={`symbol:${index}:${name}`} className={cn("min-w-0 truncate", index === breadcrumbSymbols.length - 1 && "text-foreground")} data-editor-breadcrumb-symbol>+ <span className="mx-1 opacity-60">›</span>{name}+ </span>+ ))}{activeDoc?.conflict ? (<button type="button" className="ms-auto flex items-center gap-1 text-amber-600 hover:underline dark:text-amber-400" onClick={() => void docs.revert(activePath)}><Undo2 className="size-3" /> Changed on disk: reload@@ -1045,12 +1226,27 @@ export default function EditorPanel(props: EditorPanelProps) {onCursor={setCursor}onHunks={setHunks}navigate={navigate}+ onAgentAction={agentAction}+ onReady={(handle) => {+ surfaceHandle.current = handle;+ }}/></div></div><div className="flex h-6 shrink-0 items-center gap-3 overflow-hidden whitespace-nowrap border-t border-border px-3 text-[11px] text-muted-foreground" data-editor-status>{branch ? <span className="flex min-w-0 items-center gap-1 truncate"><GitBranch className="size-3 shrink-0" />{branch}</span> : null}{gitQuery.data?.repo ? <span className="shrink-0">{gitQuery.data.files.length} changed</span> : null}+ <button+ type="button"+ className="flex shrink-0 items-center gap-1 rounded px-1 hover:bg-muted hover:text-foreground"+ onClick={() => useEditorStore.getState().setProblemsOpen(!(problemsOpen && bottomTab === "problems"))}+ aria-label={`Problems: ${problemTotals.errors} errors, ${problemTotals.warnings} warnings`}+ title="Problems"+ data-editor-problem-counts+ >+ <CircleX className="size-3" />{problemTotals.errors}+ <AlertTriangle className="size-3" />{problemTotals.warnings}+ </button><span className="flex-1" />{cursor && activeTab ? <span className="shrink-0 max-[1100px]:hidden">Ln {cursor.line}, Col {cursor.column}</span> : null}{activePath ? <span className="shrink-0 max-[1250px]:hidden">{languageForPath(activePath)}</span> : null}@@ -1098,21 +1294,7 @@ export default function EditorPanel(props: EditorPanelProps) {{railItem("files", "Files", <Files />, mac ? "⌘⇧E" : "Ctrl+Shift+E")}{railItem("changes", "Agent changes", <FileDiff />, null, pendingCount)}{railItem("git", "Git", <GitBranch />, null, gitQuery.data?.repo ? gitQuery.data.files.length : undefined)}- <Tooltip>- <TooltipTrigger- render={(- <button- type="button"- aria-label="Go to file"- onClick={() => useEditorStore.getState().setQuickOpen(true)}- className="flex size-9 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-muted hover:text-foreground [&_svg]:size-[18px]"- >- <Search />- </button>- )}- />- <TooltipContent side="right">Go to file ({mac ? "⌘P" : "Ctrl+P"})</TooltipContent>- </Tooltip>+ {railItem("search", "Search in files", <Search />, mac ? "⌘⇧F" : "Ctrl+Shift+F")}<span className="flex-1" />{props.railFoot}</nav>@@ -1120,6 +1302,16 @@ export default function EditorPanel(props: EditorPanelProps) {<div className="flex h-9 shrink-0 items-center gap-1.5 border-b border-border px-2 max-lg:h-12 mac:titlebar-drag mac:ps-6 [&_button]:mac:titlebar-no-drag" data-editor-header>{props.headerStart}<span className="flex-1" />+ <Tooltip>+ <TooltipTrigger+ render={(+ <Button variant="ghost" size="icon-sm" aria-label="Go to file" onClick={() => useEditorStore.getState().setQuickOpen(true)}>+ <FileCode2 />+ </Button>+ )}+ />+ <TooltipContent>Go to file ({mac ? "⌘P" : "Ctrl+P"})</TooltipContent>+ </Tooltip><Tooltip><TooltipTriggerrender={(@@ -1165,11 +1357,66 @@ export default function EditorPanel(props: EditorPanelProps) {</ResizablePanel></ResizablePanelGroup></ResizablePanel>- {props.terminalOpen && props.terminal ? (+ {(props.terminalOpen && props.terminal) || problemsOpen ? (+ // The bottom panel: Problems and the terminal, as tabs.<><ResizableHandle />- <ResizablePanel defaultSize="220px" minSize="120px" maxSize="70%" className="min-h-0" data-editor-terminal>- {props.terminal}+ <ResizablePanel defaultSize="220px" minSize="120px" maxSize="70%" className="min-h-0" data-editor-bottom-panel>+ <div className="flex h-full min-h-0 flex-col">+ <div className="flex h-7 shrink-0 items-center gap-1 border-b border-border px-2 text-xs" role="tablist">+ {[+ { id: "problems" as const, label: `Problems${problemTotals.errors + problemTotals.warnings ? ` ${problemTotals.errors + problemTotals.warnings}` : ""}` },+ { id: "terminal" as const, label: "Terminal" },+ ].map((item) => {+ const front = item.id === "problems" ? problemsOpen && (bottomTab === "problems" || !props.terminalOpen) : props.terminalOpen && (bottomTab === "terminal" || !problemsOpen);+ return (+ <button+ key={item.id}+ type="button"+ role="tab"+ aria-selected={front}+ data-editor-bottom-tab={item.id}+ onClick={() => {+ if (item.id === "problems") useEditorStore.getState().setProblemsOpen(true);+ else {+ if (!props.terminalOpen) props.onToggleTerminal();+ useEditorStore.getState().setBottomTab("terminal");+ }+ }}+ className={cn("rounded-md px-2 py-0.5", front ? "bg-muted text-foreground" : "text-muted-foreground hover:text-foreground")}+ >+ {item.label}+ </button>+ );+ })}+ <span className="flex-1" />+ <Button+ variant="ghost"+ size="icon-xs"+ aria-label="Close panel"+ onClick={() => {+ useEditorStore.getState().setProblemsOpen(false);+ if (props.terminalOpen) props.onToggleTerminal();+ }}+ >+ <X />+ </Button>+ </div>+ <div className="min-h-0 flex-1">+ {problemsOpen && (bottomTab === "problems" || !props.terminalOpen) ? (+ <ProblemsView+ workspaceId={workspaceId}+ loading={problemsLoading}+ onOpen={(path, line, column) => openAt(path, line, column)}+ onFix={fixWithAgent}+ onRefresh={() => {+ setProblemsLoading(true);+ void refreshAllDiagnostics().finally(() => setProblemsLoading(false));+ }}+ />+ ) : props.terminal}+ </div>+ </div></ResizablePanel></>) : null}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.tsindex 6b468230..194c18c7 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@@ -13,7 +13,7 @@ export type EditorTab =/** A file against git (HEAD or the index), from the git panel. */| { id: string; kind: "git"; path: string; ref: "HEAD" | "index" };-export type EditorSideView = "files" | "changes" | "git";+export type EditorSideView = "files" | "changes" | "git" | "search";/** The window layout: Chat (sessions sidebar + chat) or IDE (files, editor and terminal, chat docked right). */export type LayoutMode = "chat" | "ide";export type ReviewScope = "turn" | "chat";@@ -43,6 +43,9 @@ type EditorStore = {/** One-shot requests from shortcuts: switch Chat/IDE (Cmd/Ctrl+Shift+Y), fold the chat (Cmd/Ctrl+Shift+H). */modeToggleRequest: number;chatToggleRequest: number;+ /** The bottom panel: Problems shown, and which tab is in front (the terminal opens through its own switch). */+ problemsOpen: boolean;+ bottomTab: "problems" | "terminal";openTab: (workspaceId: string, tab: EditorTab, options?: { preview?: boolean }) => void;closeTab: (workspaceId: string, id: string) => void;selectTab: (workspaceId: string, id: string) => void;@@ -58,6 +61,8 @@ type EditorStore = {setIdeChatWidth: (width: number) => void;requestModeToggle: () => void;requestChatToggle: () => void;+ setProblemsOpen: (open: boolean) => void;+ setBottomTab: (tab: "problems" | "terminal") => void;};export const DEFAULT_IDE_CHAT_WIDTH = 420;@@ -88,6 +93,8 @@ export const useEditorStore = create<EditorStore>()(ideChatWidth: DEFAULT_IDE_CHAT_WIDTH,modeToggleRequest: 0,chatToggleRequest: 0,+ problemsOpen: false,+ bottomTab: "terminal",openTab: (workspaceId, tab) =>set((state) => {const current = state.byWorkspace[workspaceId] ?? EMPTY;@@ -141,6 +148,8 @@ export const useEditorStore = create<EditorStore>()(setIdeChatWidth: (width) => set({ ideChatWidth: Math.round(Math.min(Math.max(width, 320), 1200)) }),requestModeToggle: () => set((state) => ({ modeToggleRequest: state.modeToggleRequest + 1 })),requestChatToggle: () => set((state) => ({ chatToggleRequest: state.chatToggleRequest + 1 })),+ setProblemsOpen: (problemsOpen) => set(problemsOpen ? { problemsOpen, bottomTab: "problems" } : { problemsOpen }),+ setBottomTab: (bottomTab) => set({ bottomTab }),}),{name: "omnirush:editor:v1",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 c0ce6aba..34111827 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@@ -37,6 +37,16 @@ type EditorSurfaceProps = {onHunks: (hunks: LineHunk[]) => void;/** Bumped to jump to the next / previous hunk. */navigate: { direction: 1 | -1; nonce: number } | null;+ /** The editor's agent actions (right-click menu, Cmd/Ctrl+L): the editor they ran in. */+ onAgentAction?: (action: AgentAction, editor: MonacoApi.editor.ICodeEditor) => void;+ /** A handle to reveal a position in the visible editor and to read it. */+ onReady?: (handle: SurfaceHandle | null) => void;+};++export type AgentAction = "ask" | "explain" | "refactor" | "tests";+export type SurfaceHandle = {+ reveal: (line: number, column: number, endColumn?: number) => void;+ activeEditor: () => MonacoApi.editor.ICodeEditor | null;};const BASE_OPTIONS: MonacoApi.editor.IStandaloneEditorConstructionOptions = {@@ -92,7 +102,11 @@ function hunkBar(const VIEW_STATES = new Map<string, MonacoApi.editor.ICodeEditorViewState | MonacoApi.editor.IDiffEditorViewState | null>();-export function EditorSurface({ monaco, surface, onSave, onCursor, onHunks, navigate }: EditorSurfaceProps) {+export function EditorSurface({ monaco, surface, onSave, onCursor, onHunks, navigate, onAgentAction, onReady }: EditorSurfaceProps) {+ const onAgentRef = useRef(onAgentAction);+ onAgentRef.current = onAgentAction;+ const onReadyRef = useRef(onReady);+ onReadyRef.current = onReady;const codeHostRef = useRef<HTMLDivElement | null>(null);const diffHostRef = useRef<HTMLDivElement | null>(null);const codeRef = useRef<MonacoApi.editor.IStandaloneCodeEditor | null>(null);@@ -136,8 +150,33 @@ export function EditorSurface({ monaco, surface, onSave, onCursor, onHunks, navionCursorRef.current({ line: event.position.lineNumber, column: event.position.column });});const disposables = [cursor(code), cursor(diff.getModifiedEditor())];+ // The agent in the editor: the right-click menu's first group, and Cmd/Ctrl+L to ask.+ const agentActions = (editor: MonacoApi.editor.IStandaloneCodeEditor) => ([+ { id: "omnirush.agent.ask", label: "Ask about selection", action: "ask" as const, keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyL], order: 1 },+ { id: "omnirush.agent.explain", label: "Explain with agent", action: "explain" as const, keybindings: [], order: 2 },+ { id: "omnirush.agent.refactor", label: "Refactor with agent…", action: "refactor" as const, keybindings: [], order: 3 },+ { id: "omnirush.agent.tests", label: "Write tests with agent", action: "tests" as const, keybindings: [], order: 4 },+ ]).map((item) => editor.addAction({+ id: item.id,+ label: item.label,+ keybindings: item.keybindings,+ contextMenuGroupId: "0_agent",+ contextMenuOrder: item.order,+ run: (target: MonacoApi.editor.ICodeEditor) => onAgentRef.current?.(item.action, target),+ }));+ disposables.push(...agentActions(code), ...agentActions(diff.getModifiedEditor() as MonacoApi.editor.IStandaloneCodeEditor));codeRef.current = code;diffRef.current = diff;+ onReadyRef.current?.({+ reveal: (line, column, endColumn) => {+ const editor = modeRef.current === "diff" ? diff.getModifiedEditor() : code;+ const selection = { startLineNumber: line, startColumn: column, endLineNumber: line, endColumn: endColumn ?? column };+ editor.setSelection(selection);+ editor.revealRangeInCenterIfOutsideViewport(selection);+ editor.focus();+ },+ activeEditor: () => (modeRef.current === "diff" ? diff.getModifiedEditor() : modeRef.current === "file" ? code : null),+ });// Follows the app theme: light/dark, presets and custom themes (app/theme.ts).const unsubscribeTheme = subscribeToTheme(() => {applyMonacoTheme();@@ -149,6 +188,7 @@ export function EditorSurface({ monaco, surface, onSave, onCursor, onHunks, navireturn () => {const key = currentKey.current;if (key) VIEW_STATES.set(key, modeRef.current === "diff" ? diff.saveViewState() : code.saveViewState());+ onReadyRef.current?.(null);unsubscribeTheme();for (const disposable of disposables) disposable.dispose();code.dispose();diff --git a/apps/app/src/react-app/domains/session/editor/lsp.ts b/apps/app/src/react-app/domains/session/editor/lsp.tsnew file mode 100644index 00000000..d933e259--- /dev/null+++ b/apps/app/src/react-app/domains/session/editor/lsp.ts@@ -0,0 +1,374 @@+/**+ * Language features in the editor from the project's own language servers,+ * the ones the agent already runs (the engine's /editor/lsp routes): hover,+ * go to definition (F12, Cmd/Ctrl+click), references (Shift+F12), rename+ * (F2), document symbols (outline, breadcrumbs, Cmd/Ctrl+Shift+O),+ * 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.+ */+import { create } from "zustand";+import type * as MonacoApi from "monaco-editor/editor/editor.api.js";++import type { OmniRushServerClient } from "@/app/lib/omnirush-server";+import type { EditorDocuments } from "./editor-models";+import type { Monaco } from "./monaco";++export type LspPosition = { line: number; character: number };+export type LspRange = { start: LspPosition; end: LspPosition };+export type LspDiagnostic = { range: LspRange; severity?: number; message: string; source?: string; code?: string | number | { value: string | number } };+export type ProblemFile = { path: string; diagnostics: LspDiagnostic[] };++type Context = {+ monaco: Monaco;+ client: OmniRushServerClient;+ workspaceId: string;+ workspaceRoot: string;+ docs: EditorDocuments;+ /** Opens a project file in the editor at a 1-based position. */+ openAt: (path: string, line: number, column: number) => void;+ /** "Fix with agent" for a diagnostic. */+ fixWithAgent: (path: string, diagnostic: LspDiagnostic) => void;+};++let current: Context | null = null;+let installed = false;+let unavailable = false;++/** The Problems panel: diagnostics per project file, as the language servers last reported them. */+export const useProblemsStore = create<{+ byWorkspace: Record<string, ProblemFile[]>;+ available: boolean;+ set: (workspaceId: string, files: ProblemFile[]) => void;+ merge: (workspaceId: string, file: ProblemFile) => void;+ setAvailable: (available: boolean) => void;+}>((set) => ({+ byWorkspace: {},+ available: true,+ set: (workspaceId, files) => set((state) => ({ byWorkspace: { ...state.byWorkspace, [workspaceId]: files.filter((file) => file.diagnostics.length) } })),+ merge: (workspaceId, file) =>+ set((state) => {+ const rest = (state.byWorkspace[workspaceId] ?? []).filter((item) => item.path !== file.path);+ return { byWorkspace: { ...state.byWorkspace, [workspaceId]: file.diagnostics.length ? [...rest, file].sort((a, b) => a.path.localeCompare(b.path)) : rest } };+ }),+ setAvailable: (available) => set({ available }),+}));++export function problemCounts(files: readonly ProblemFile[]) {+ let errors = 0;+ let warnings = 0;+ for (const file of files) {+ for (const diagnostic of file.diagnostics) {+ if ((diagnostic.severity ?? 1) === 1) errors += 1;+ else if (diagnostic.severity === 2) warnings += 1;+ }+ }+ return { errors, warnings };+}++/** 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(/^\//, "");+}++/** A `file://` URI from a language server to a workspace path, or null when it is outside the project. */+export function uriToPath(uri: string, workspaceRoot: string): string | null {+ if (!uri.startsWith("file://")) return null;+ let path: string;+ try {+ path = decodeURIComponent(new URL(uri).pathname);+ } catch {+ return null;+ }+ if (/^\/[A-Za-z]:\//.test(path)) path = path.slice(1);+ const root = workspaceRoot.replace(/\\/g, "/").replace(/\/+$/, "");+ const normalized = path.replace(/\\/g, "/");+ const caseless = /^[A-Za-z]:\//.test(root);+ const inside = caseless ? normalized.toLowerCase().startsWith(`${root.toLowerCase()}/`) : normalized.startsWith(`${root}/`);+ return inside ? normalized.slice(root.length + 1) : null;+}++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) {+ const doc = current?.docs.get(path);+ const text = doc && current?.docs.isDirty(doc) ? model.getValue() : undefined;+ return {+ path,+ ...(position ? { line: position.lineNumber - 1, character: position.column - 1 } : {}),+ ...(text !== undefined ? { text } : {}),+ };+}++async function call<T>(op: Parameters<OmniRushServerClient["editorLsp"]>[1], payload: Parameters<OmniRushServerClient["editorLsp"]>[2]): Promise<T | null> {+ if (!current || unavailable) return null;+ try {+ return await current.client.editorLsp<T>(current.workspaceId, op, payload);+ } catch (error) {+ // An engine without the editor routes (older build): language features stay off quietly.+ if ((error as { status?: number }).status === 404) {+ unavailable = true;+ useProblemsStore.getState().setAvailable(false);+ }+ return null;+ }+}++type LspLocation = { uri?: string; range?: LspRange; targetUri?: string; targetRange?: LspRange; targetSelectionRange?: LspRange };++/** Locations inside the project, with an editor model ready for each (peek and go-to need one). */+async function toLocations(raw: unknown): Promise<MonacoApi.languages.Location[]> {+ if (!current) return [];+ const ctx = current;+ const list = (Array.isArray(raw) ? raw : raw ? [raw] : []) as LspLocation[];+ const out: MonacoApi.languages.Location[] = [];+ const opened = new Set<string>();+ for (const item of list.slice(0, 200)) {+ const uri = item.targetUri ?? item.uri;+ const range = item.targetSelectionRange ?? item.targetRange ?? item.range;+ if (!uri || !range) continue;+ const path = uriToPath(uri, ctx.workspaceRoot);+ if (!path) continue;+ if (!opened.has(path)) {+ if (opened.size >= 30) continue;+ const result = await ctx.docs.open(path);+ if (!result.ok) continue;+ opened.add(path);+ }+ out.push({ uri: ctx.docs.uri(path), range: toMonacoRange(ctx.monaco, range) });+ }+ return out;+}++const SYMBOL_KIND_MAP = (monaco: Monaco, kind: number) => {+ // LSP SymbolKind is 1-based; Monaco's is the same list 0-based.+ const value = Math.max(0, kind - 1);+ return value as MonacoApi.languages.SymbolKind;+};++type LspDocumentSymbol = { name: string; detail?: string; kind: number; range?: LspRange; selectionRange?: LspRange; children?: LspDocumentSymbol[]; location?: { uri: string; range: LspRange } };++function toDocumentSymbols(monaco: Monaco, raw: LspDocumentSymbol[]): MonacoApi.languages.DocumentSymbol[] {+ return raw+ .filter((symbol) => symbol && typeof symbol.name === "string")+ .map((symbol): MonacoApi.languages.DocumentSymbol | null => {+ const range = symbol.range ?? symbol.location?.range;+ const selection = symbol.selectionRange ?? range;+ if (!range || !selection) return null;+ return {+ name: symbol.name,+ detail: symbol.detail ?? "",+ kind: SYMBOL_KIND_MAP(monaco, symbol.kind),+ tags: [],+ range: toMonacoRange(monaco, range),+ selectionRange: toMonacoRange(monaco, selection),+ children: symbol.children ? toDocumentSymbols(monaco, symbol.children) : undefined,+ };+ })+ .filter((item): item is MonacoApi.languages.DocumentSymbol => item !== null);+}++/** 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[]> {+ const path = modelPath(model);+ if (!path || !current) return [];+ const key = model.uri.toString();+ const cached = symbolCache.get(key);+ if (cached && cached.version === model.getVersionId()) 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 });+ return symbols;+}++/** The symbols around a position, outermost first (breadcrumbs). */+export function symbolPath(symbols: readonly MonacoApi.languages.DocumentSymbol[], line: number, column: number): MonacoApi.languages.DocumentSymbol[] {+ const inside = (range: MonacoApi.IRange) =>+ (line > range.startLineNumber || (line === range.startLineNumber && column >= range.startColumn))+ && (line < range.endLineNumber || (line === range.endLineNumber && column <= range.endColumn));+ for (const symbol of symbols) {+ if (inside(symbol.range)) return [symbol, ...symbolPath(symbol.children ?? [], line, column)];+ }+ return [];+}++function hoverContents(raw: unknown): MonacoApi.IMarkdownString[] {+ const out: MonacoApi.IMarkdownString[] = [];+ const add = (value: unknown) => {+ if (!value) return;+ if (typeof value === "string") out.push({ value });+ else if (typeof value === "object" && "value" in (value as Record<string, unknown>)) {+ const item = value as { value: string; language?: string; kind?: string };+ out.push({ value: item.language ? `\`\`\`${item.language}\n${item.value}\n\`\`\`` : item.value });+ }+ };+ for (const hover of Array.isArray(raw) ? raw : [raw]) {+ const contents = (hover as { contents?: unknown } | null)?.contents;+ if (Array.isArray(contents)) contents.forEach(add);+ else add(contents);+ }+ return out;+}++const SEVERITY = (monaco: Monaco, severity?: number) =>+ severity === 2 ? monaco.MarkerSeverity.Warning : severity === 3 ? monaco.MarkerSeverity.Info : severity === 4 ? monaco.MarkerSeverity.Hint : monaco.MarkerSeverity.Error;++export function diagnosticCode(diagnostic: LspDiagnostic): string | undefined {+ const code = diagnostic.code;+ if (code === undefined || code === null) return undefined;+ return typeof code === "object" ? String(code.value) : String(code);+}++/** Squiggles for one open file, from diagnostics. */+export function applyMarkers(path: string, diagnostics: readonly LspDiagnostic[]) {+ if (!current) return;+ const doc = current.docs.get(path);+ if (!doc) return;+ const monaco = current.monaco;+ monaco.editor.setModelMarkers(doc.model, "lsp", diagnostics.map((diagnostic) => ({+ ...toMonacoRange(monaco, diagnostic.range),+ severity: SEVERITY(monaco, diagnostic.severity),+ message: diagnostic.message,+ source: diagnostic.source,+ code: diagnosticCode(diagnostic),+ })));+}++/** 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;+ 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);+}++/** Every diagnostic the language servers hold for the project (files they have seen). */+export async function refreshAllDiagnostics(): Promise<void> {+ if (!current) return;+ 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);+}++/** Where the editor's language features act now (the workspace shown). */+export function setLanguageContext(ctx: Context | null) {+ current = ctx;+ unavailable = false;+ symbolCache.clear();+ useProblemsStore.getState().setAvailable(true);+}++/** The providers, once per Monaco instance; they act on the current context. */+export function installLanguageFeatures(monaco: Monaco) {+ if (installed) return;+ installed = true;+ const selector = "*";+ monaco.languages.registerHoverProvider(selector, {+ provideHover: async (model, position) => {+ const path = modelPath(model);+ if (!path) return null;+ const contents = hoverContents(await call("hover", payloadFor(model, path, position)));+ return contents.length ? { contents } : null;+ },+ });+ monaco.languages.registerDefinitionProvider(selector, {+ provideDefinition: async (model, position) => {+ const path = modelPath(model);+ if (!path) return null;+ return toLocations(await call("definition", payloadFor(model, path, position)));+ },+ });+ monaco.languages.registerReferenceProvider(selector, {+ provideReferences: async (model, position) => {+ const path = modelPath(model);+ if (!path) return null;+ return toLocations(await call("references", payloadFor(model, path, position)));+ },+ });+ monaco.languages.registerDocumentSymbolProvider(selector, {+ displayName: "Language server",+ provideDocumentSymbols: (model) => documentSymbols(model),+ });+ monaco.languages.registerRenameProvider(selector, {+ provideRenameEdits: async (model, position, newName) => {+ const path = modelPath(model);+ if (!path || !current) return null;+ const ctx = current;+ const raw = await call<unknown[]>("rename", { ...payloadFor(model, path, position), newName });+ const edits: MonacoApi.languages.IWorkspaceTextEdit[] = [];+ type TextEdit = { range: LspRange; newText: string };+ const addEdits = async (uri: string, list: TextEdit[]) => {+ const target = uriToPath(uri, ctx.workspaceRoot);+ if (!target) return;+ const opened = await ctx.docs.open(target);+ if (!opened.ok) return;+ for (const edit of list) {+ edits.push({ resource: ctx.docs.uri(target), versionId: undefined, textEdit: { range: toMonacoRange(ctx.monaco, edit.range), text: edit.newText } });+ }+ };+ for (const result of raw ?? []) {+ const workspaceEdit = result as { changes?: Record<string, TextEdit[]>; documentChanges?: Array<{ textDocument?: { uri: string }; edits?: TextEdit[] }> };+ for (const [uri, list] of Object.entries(workspaceEdit.changes ?? {})) await addEdits(uri, list);+ for (const change of workspaceEdit.documentChanges ?? []) {+ 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)." };+ return { edits };+ },+ });+ const fixCommand = "omnirush.editor.fixWithAgent";+ monaco.editor.registerCommand(fixCommand, (_accessor, path: string, diagnostic: LspDiagnostic) => {+ current?.fixWithAgent(path, diagnostic);+ });+ monaco.languages.registerCodeActionProvider(selector, {+ provideCodeActions: (model, _range, context) => {+ const path = modelPath(model);+ if (!path || !context.markers.length) return { actions: [], dispose: () => undefined };+ const actions = context.markers.slice(0, 3).map((marker) => ({+ title: `Fix with agent: ${marker.message.split("\n")[0]!.slice(0, 60)}`,+ kind: "quickfix",+ diagnostics: [marker],+ isPreferred: false,+ command: {+ id: fixCommand,+ title: "Fix with agent",+ arguments: [path, {+ range: { start: { line: marker.startLineNumber - 1, character: marker.startColumn - 1 }, end: { line: marker.endLineNumber - 1, character: marker.endColumn - 1 } },+ severity: marker.severity === monaco.MarkerSeverity.Warning ? 2 : marker.severity === monaco.MarkerSeverity.Error ? 1 : 3,+ message: marker.message,+ source: marker.source,+ code: typeof marker.code === "object" ? marker.code?.value : marker.code,+ } satisfies LspDiagnostic],+ },+ }));+ return { actions, dispose: () => undefined };+ },+ });+ // 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 at = selectionOrPosition && "startLineNumber" in selectionOrPosition+ ? { line: selectionOrPosition.startLineNumber, column: selectionOrPosition.startColumn }+ : selectionOrPosition && "lineNumber" in selectionOrPosition+ ? { line: selectionOrPosition.lineNumber, column: selectionOrPosition.column }+ : { line: 1, column: 1 };+ current.openAt(path, at.line, at.column);+ return true;+ },+ });+}diff --git a/apps/app/src/react-app/domains/session/editor/monaco.ts b/apps/app/src/react-app/domains/session/editor/monaco.tsindex d46c2ac0..3cd01f0d 100644--- a/apps/app/src/react-app/domains/session/editor/monaco.ts+++ b/apps/app/src/react-app/domains/session/editor/monaco.ts@@ -39,6 +39,14 @@ import "monaco-editor/features/unicodeHighlighter/register.js";import "monaco-editor/features/wordHighlighter/register.js";import "monaco-editor/features/wordOperations/register.js";import "monaco-editor/features/readOnlyMessage/register.js";+// Language features (providers in lsp.ts): go to definition and Cmd/Ctrl+click, peek references,+// rename, the symbol picker (Cmd/Ctrl+Shift+O), quick fixes (the lightbulb), next problem (F8).+import "monaco-editor/features/gotoSymbol/register.js";+import "monaco-editor/features/referenceSearch/register.js";+import "monaco-editor/features/rename/register.js";+import "monaco-editor/features/quickOutline/register.js";+import "monaco-editor/features/codeAction/register.js";+import "monaco-editor/features/gotoError/register.js";// Syntax colouring only (Monarch grammars, each loaded on first use); not languages/register.all.js,// which also starts the CSS/HTML/JSON/TypeScript language-service workers.import "monaco-editor/languages/definitions/abap/register.js";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.tsxnew file mode 100644index 00000000..d953365f--- /dev/null+++ b/apps/app/src/react-app/domains/session/editor/outline-view.tsx@@ -0,0 +1,100 @@+/** @jsxImportSource react */+/** The Outline section under the Files view: the active file's symbols from its language server. */+import { useEffect, useState } from "react";+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";++// Monaco SymbolKind (0-based): a short mark per kind.+const KIND_MARK: Record<number, { mark: string; className: string }> = {+ 4: { mark: "C", className: "text-amber-11" },+ 5: { mark: "m", className: "text-violet-11" },+ 6: { mark: "p", className: "text-blue-11" },+ 8: { mark: "c", className: "text-violet-11" },+ 9: { mark: "E", className: "text-amber-11" },+ 10: { mark: "I", className: "text-cyan-11" },+ 11: { mark: "ƒ", className: "text-violet-11" },+ 12: { mark: "v", className: "text-blue-11" },+ 13: { mark: "k", className: "text-blue-11" },+ 22: { mark: "s", className: "text-amber-11" },+ 25: { mark: "T", className: "text-cyan-11" },+};++function SymbolRow(props: { symbol: MonacoApi.languages.DocumentSymbol; depth: number; onReveal: (line: number, column: number) => void }) {+ const [open, setOpen] = useState(props.depth < 1);+ const children = props.symbol.children ?? [];+ const mark = KIND_MARK[props.symbol.kind] ?? { mark: "•", className: "text-muted-foreground" };+ return (+ <>+ <div className="flex items-center gap-1 rounded-md py-0.5 pe-1 hover:bg-muted" style={{ paddingInlineStart: 6 + props.depth * 12 }}>+ {children.length ? (+ <button type="button" aria-label={open ? "Collapse" : "Expand"} onClick={() => setOpen((value) => !value)} className="text-muted-foreground">+ {open ? <ChevronDown className="size-3" /> : <ChevronRight className="size-3" />}+ </button>+ ) : <span className="w-3" />}+ <button+ type="button"+ className="flex min-w-0 flex-1 items-center gap-1.5 text-start"+ onClick={() => props.onReveal(props.symbol.selectionRange.startLineNumber, props.symbol.selectionRange.startColumn)}+ data-editor-outline-symbol={props.symbol.name}+ >+ <span className={cn("w-3 shrink-0 text-center font-mono text-[10.5px]", mark.className)}>{mark.mark}</span>+ <span className="truncate">{props.symbol.name}</span>+ {props.symbol.detail ? <span className="truncate text-[10.5px] text-muted-foreground">{props.symbol.detail}</span> : null}+ </button>+ </div>+ {open ? children.map((child, index) => <SymbolRow key={`${child.name}:${index}`} symbol={child} depth={props.depth + 1} onReveal={props.onReveal} />) : null}+ </>+ );+}++export function OutlineView(props: { model: MonacoApi.editor.ITextModel | null; path: string | null; onReveal: (line: number, column: number) => void }) {+ const [open, setOpen] = useState(true);+ const [symbols, setSymbols] = useState<MonacoApi.languages.DocumentSymbol[] | null>(null);+ const [tick, setTick] = useState(0);++ useEffect(() => {+ const model = props.model;+ if (!model) return;+ const subscription = model.onDidChangeContent(() => setTick((value) => value + 1));+ return () => subscription.dispose();+ }, [props.model]);++ useEffect(() => {+ let cancelled = false;+ const model = props.model;+ if (!model || !open) {+ setSymbols(null);+ return;+ }+ const timer = window.setTimeout(() => {+ void documentSymbols(model).then((next) => {+ if (!cancelled) setSymbols(next);+ });+ }, tick ? 800 : 0);+ return () => {+ cancelled = true;+ window.clearTimeout(timer);+ };+ }, [open, props.model, tick]);++ return (+ <div className={cn("flex min-h-0 flex-col border-t border-border text-xs", open ? "max-h-[45%]" : "")} data-editor-outline>+ <button type="button" className="flex h-7 shrink-0 items-center gap-1 px-2 text-[10.5px] font-medium uppercase tracking-wide text-muted-foreground hover:text-foreground" onClick={() => setOpen((value) => !value)} aria-expanded={open}>+ {open ? <ChevronDown className="size-3" /> : <ChevronRight className="size-3" />}+ Outline+ {props.path ? <span className="truncate normal-case tracking-normal">· {props.path.split("/").pop()}</span> : null}+ </button>+ {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>+ : 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>+ ) : null}+ </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.tsxnew file mode 100644index 00000000..859c5617--- /dev/null+++ b/apps/app/src/react-app/domains/session/editor/problems-view.tsx@@ -0,0 +1,103 @@+/** @jsxImportSource react */+/**+ * The Problems panel (bottom panel): what the project's language servers+ * report, by file. Scope: the files the servers have opened (yours and the+ * agent's), not a full build. Each problem opens its line; "Fix with agent"+ * hands it to the chat.+ */+import { useMemo, useState } from "react";+import { AlertTriangle, ChevronDown, ChevronRight, CircleX, Info, RefreshCw, Sparkles } from "lucide-react";++import { Button } from "@/components/ui/button";+import { cn } from "@/lib/utils";+import { diagnosticCode, problemCounts, useProblemsStore, type LspDiagnostic } from "./lsp";++const EMPTY: never[] = [];++export function ProblemsView(props: {+ workspaceId: string;+ loading: boolean;+ onOpen: (path: string, line: number, column: number) => void;+ onFix: (path: string, diagnostic: LspDiagnostic) => void;+ onRefresh: () => void;+}) {+ const files = useProblemsStore((state) => state.byWorkspace[props.workspaceId] ?? EMPTY);+ const available = useProblemsStore((state) => state.available);+ const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});+ const [errorsOnly, setErrorsOnly] = useState(false);+ const counts = problemCounts(files);+ const shown = useMemo(() => files.map((file) => ({+ ...file,+ diagnostics: [...file.diagnostics]+ .filter((diagnostic) => !errorsOnly || (diagnostic.severity ?? 1) === 1)+ .sort((a, b) => (a.severity ?? 1) - (b.severity ?? 1) || a.range.start.line - b.range.start.line),+ })).filter((file) => file.diagnostics.length), [errorsOnly, files]);++ return (+ <div className="flex h-full min-h-0 flex-col text-xs" data-editor-problems={counts.errors + counts.warnings}>+ <div className="flex h-8 shrink-0 items-center gap-2 border-b border-border px-3 text-muted-foreground">+ <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">+ <input type="checkbox" checked={errorsOnly} onChange={(event) => setErrorsOnly(event.target.checked)} />+ Errors only+ </label>+ <Button variant="ghost" size="icon-xs" aria-label="Refresh problems" onClick={props.onRefresh}>+ <RefreshCw className={cn(props.loading && "animate-spin")} />+ </Button>+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto py-1">+ {!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>+ ) : shown.map((file) => (+ <div key={file.path}>+ <button+ type="button"+ className="flex w-full items-center gap-1 px-2 py-0.5 text-start hover:bg-muted"+ onClick={() => setCollapsed((value) => ({ ...value, [file.path]: !value[file.path] }))}+ >+ {collapsed[file.path] ? <ChevronRight className="size-3" /> : <ChevronDown className="size-3" />}+ <span className="font-medium">{file.path.split("/").pop()}</span>+ <span className="truncate text-[10.5px] text-muted-foreground">{file.path}</span>+ <span className="ms-auto rounded-full bg-muted px-1.5 text-[10px] text-muted-foreground">{file.diagnostics.length}</span>+ </button>+ {collapsed[file.path] ? null : file.diagnostics.map((diagnostic, index) => {+ const severity = diagnostic.severity ?? 1;+ const code = diagnosticCode(diagnostic);+ return (+ <div key={`${index}:${diagnostic.range.start.line}`} className="group flex items-center gap-2 py-0.5 ps-6 pe-2 hover:bg-muted" data-editor-problem>+ <button+ type="button"+ className="flex min-w-0 flex-1 items-center gap-2 text-start"+ onClick={() => props.onOpen(file.path, diagnostic.range.start.line + 1, diagnostic.range.start.character + 1)}+ >+ {severity === 1 ? <CircleX className="size-3.5 shrink-0 text-red-11" aria-label="Error" />+ : severity === 2 ? <AlertTriangle className="size-3.5 shrink-0 text-amber-11" aria-label="Warning" />+ : <Info className="size-3.5 shrink-0 text-blue-11" aria-label="Info" />}+ <span className="min-w-0 truncate">{diagnostic.message.split("\n")[0]}</span>+ <span className="shrink-0 text-[10.5px] text-muted-foreground">+ {diagnostic.source ? `${diagnostic.source}${code ? `(${code})` : ""} · ` : ""}+ L{diagnostic.range.start.line + 1}:C{diagnostic.range.start.character + 1}+ </span>+ </button>+ <Button+ variant="outline"+ size="xs"+ className="h-5 shrink-0 gap-1 px-1.5 text-[10.5px] opacity-70 group-hover:opacity-100"+ onClick={() => props.onFix(file.path, diagnostic)}+ data-editor-problem-fix+ >+ <Sparkles className="size-3" /> Fix with agent+ </Button>+ </div>+ );+ })}+ </div>+ ))}+ </div>+ </div>+ );+}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.tsxnew file mode 100644index 00000000..f5d43783--- /dev/null+++ b/apps/app/src/react-app/domains/session/editor/search-view.tsx@@ -0,0 +1,317 @@+/** @jsxImportSource react */+/**+ * Search in files (Cmd/Ctrl+Shift+F in the IDE layout): text or regex, case,+ * whole word, files to include/exclude, results by file. Replace previews the+ * change on each match; replacing a match, a file or everything edits the open+ * documents (one undo step per file) and saves them like a user's own save.+ */+import { useEffect, useMemo, useRef, useState } from "react";+import { CaseSensitive, ChevronDown, ChevronRight, Regex, Replace, ReplaceAll, WholeWord, X } from "lucide-react";++import type { OmniRushEditorSearchResult, OmniRushServerClient } from "@/app/lib/omnirush-server";+import { Button } from "@/components/ui/button";+import { toast } from "@/components/ui/sonner";+import { cn } from "@/lib/utils";+import type { EditorDocuments } from "./editor-models";++type Flags = { regex: boolean; caseSensitive: boolean; wholeWord: boolean };++function matcher(query: string, flags: Flags): RegExp | null {+ if (!query) return null;+ const source = flags.regex ? query : query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ try {+ return new RegExp(flags.wholeWord ? `\\b(?:${source})\\b` : source, flags.caseSensitive ? "g" : "gi");+ } catch {+ return 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);+}++type Target = { path: string; line: number; start: number; end: number };++export function SearchView(props: {+ client: OmniRushServerClient;+ workspaceId: string;+ docs: EditorDocuments;+ sessionId: string | null;+ focusNonce: number;+ onOpen: (path: string, line: number, column: number, endColumn: number) => void;+ onSaved: () => void;+}) {+ const [query, setQuery] = useState("");+ const [replace, setReplace] = useState("");+ const [showReplace, setShowReplace] = useState(false);+ const [showFilters, setShowFilters] = useState(false);+ const [include, setInclude] = useState("");+ const [exclude, setExclude] = useState("");+ const [flags, setFlags] = useState<Flags>({ regex: false, caseSensitive: false, wholeWord: false });+ const [result, setResult] = useState<OmniRushEditorSearchResult | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);+ const [rerun, setRerun] = useState(0);+ const [collapsed, setCollapsed] = useState<Record<string, true>>({});+ const [dismissed, setDismissed] = useState<Record<string, true>>({});+ const inputRef = useRef<HTMLInputElement | null>(null);+ const abortRef = useRef<AbortController | null>(null);++ useEffect(() => {+ inputRef.current?.focus();+ inputRef.current?.select();+ }, [props.focusNonce]);++ // Search as you type (debounced); a new search cancels the one running.+ useEffect(() => {+ abortRef.current?.abort();+ setError(null);+ if (!query.trim()) {+ setResult(null);+ return;+ }+ if (flags.regex && !matcher(query, flags)) {+ setError("Not a valid regular expression.");+ return;+ }+ const controller = new AbortController();+ abortRef.current = controller;+ const timer = window.setTimeout(() => {+ setBusy(true);+ props.client.editorSearch(props.workspaceId, {+ query,+ ...flags,+ include: include.split(",").map((item) => item.trim()).filter(Boolean),+ exclude: exclude.split(",").map((item) => item.trim()).filter(Boolean),+ }, controller.signal)+ .then((next) => {+ if (controller.signal.aborted) return;+ setResult(next);+ setDismissed({});+ })+ .catch((cause) => {+ if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : "Search failed.");+ })+ .finally(() => {+ if (!controller.signal.aborted) setBusy(false);+ });+ }, 250);+ return () => {+ window.clearTimeout(timer);+ controller.abort();+ };+ }, [exclude, flags, include, props.client, props.workspaceId, query, rerun]);++ const visible = useMemo(() => (result?.files ?? []).map((file) => ({+ path: file.path,+ 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);++ /** 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[]) => {+ const byFile = new Map<string, Target[]>();+ for (const target of targets) byFile.set(target.path, [...(byFile.get(target.path) ?? []), target]);+ let changed = 0;+ let failed = 0;+ for (const [path, list] of byFile) {+ const opened = await props.docs.open(path);+ if (!opened.ok) {+ failed += list.length;+ continue;+ }+ const model = opened.doc.model;+ 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) {+ 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),+ });+ }+ if (!edits.length) continue;+ model.pushEditOperations([], edits, () => null);+ const saved = await props.docs.save(path, { sessionId: props.sessionId, source: "editor" });+ if (saved.ok) changed += edits.length;+ else {+ failed += edits.length;+ toast.error(`${path}: ${saved.message}`);+ }+ }+ if (changed) toast.success(`Replaced ${changed} match${changed === 1 ? "" : "es"}${failed ? `; ${failed} skipped` : ""}.`);+ else if (failed) toast.error("Nothing replaced: the files changed since the search. Search again.");+ props.onSaved();+ setRerun((value) => value + 1);+ };++ const absoluteTarget = (path: string, match: { line: number; start: number; end: number; textOffset: number }): Target => ({+ path,+ line: match.line,+ start: match.start + match.textOffset,+ end: match.end + match.textOffset,+ });++ const replaceAll = () => {+ if (!total) return;+ const files = visible.length;+ if (!window.confirm(`Replace ${total} match${total === 1 ? "" : "es"} in ${files} file${files === 1 ? "" : "s"} with "${replace}"? Each file can be undone in the editor.`)) return;+ void apply(visible.flatMap((file) => file.matches.map((match) => absoluteTarget(file.path, match))));+ };++ const toggle = (key: keyof Flags, label: string, icon: React.ReactNode, shortcut: string) => (+ <button+ type="button"+ title={`${label} (${shortcut})`}+ aria-label={label}+ aria-pressed={flags[key]}+ onClick={() => setFlags((value) => ({ ...value, [key]: !value[key] }))}+ className={cn("flex size-5 items-center justify-center rounded [&_svg]:size-3.5", flags[key] ? "bg-primary/15 text-primary" : "text-muted-foreground hover:text-foreground")}+ >+ {icon}+ </button>+ );+ const mac = /Mac/i.test(navigator.platform);++ return (+ <div className="flex h-full min-h-0 flex-col text-xs" data-editor-search>+ <div className="flex shrink-0 flex-col gap-1 p-2">+ <div className="flex items-start gap-1">+ <button+ type="button"+ aria-label={showReplace ? "Hide replace" : "Show replace"}+ onClick={() => setShowReplace((value) => !value)}+ className="mt-1 text-muted-foreground hover:text-foreground"+ >+ {showReplace ? <ChevronDown className="size-3.5" /> : <ChevronRight className="size-3.5" />}+ </button>+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <div className="flex h-7 items-center gap-0.5 rounded-md border border-border bg-background pe-1 focus-within:ring-1 focus-within:ring-ring">+ <input+ ref={inputRef}+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ placeholder="Search"+ aria-label="Search in files"+ className="min-w-0 flex-1 bg-transparent px-2 outline-none placeholder:text-muted-foreground"+ onKeyDown={(event) => {+ if (event.altKey && event.key.toLowerCase() === "c") setFlags((value) => ({ ...value, caseSensitive: !value.caseSensitive }));+ if (event.altKey && event.key.toLowerCase() === "w") setFlags((value) => ({ ...value, wholeWord: !value.wholeWord }));+ if (event.altKey && event.key.toLowerCase() === "r") setFlags((value) => ({ ...value, regex: !value.regex }));+ }}+ />+ {toggle("caseSensitive", "Match case", <CaseSensitive />, mac ? "⌥C" : "Alt+C")}+ {toggle("wholeWord", "Whole word", <WholeWord />, mac ? "⌥W" : "Alt+W")}+ {toggle("regex", "Regular expression", <Regex />, mac ? "⌥R" : "Alt+R")}+ </div>+ {showReplace ? (+ <div className="flex items-center gap-1">+ <input+ value={replace}+ onChange={(event) => setReplace(event.target.value)}+ placeholder="Replace"+ aria-label="Replace with"+ className="h-7 min-w-0 flex-1 rounded-md border border-border bg-background px-2 outline-none focus-visible:ring-1 focus-visible:ring-ring"+ />+ <Button variant="ghost" size="icon-xs" aria-label="Replace all" title="Replace all" disabled={!total} onClick={replaceAll}>+ <ReplaceAll />+ </Button>+ </div>+ ) : null}+ </div>+ </div>+ <button type="button" className="self-end text-[11px] text-muted-foreground hover:text-foreground" onClick={() => setShowFilters((value) => !value)}>+ {showFilters ? "Hide file filters" : "Files to include / exclude"}+ </button>+ {showFilters ? (+ <>+ <input value={include} onChange={(event) => setInclude(event.target.value)} placeholder="Files to include, e.g. src/**, *.ts" aria-label="Files to include" className="h-7 rounded-md border border-border bg-background px-2 outline-none" />+ <input value={exclude} onChange={(event) => setExclude(event.target.value)} placeholder="Files to exclude, e.g. **/*.test.ts" aria-label="Files to exclude" className="h-7 rounded-md border border-border bg-background px-2 outline-none" />+ </>+ ) : null}+ <p className="px-1 text-[11px] text-muted-foreground" data-editor-search-summary>+ {error ? <span className="text-destructive">{error}</span>+ : busy ? "Searching…"+ : result ? `${total} result${total === 1 ? "" : "s"} in ${visible.length} file${visible.length === 1 ? "" : "s"}${result.truncated ? " (first results only: narrow the search)" : ""}${result.timedOut ? " (stopped after 20 s)" : ""}${result.engine === "none" ? " (search needs ripgrep or a git repository)" : ""}`+ : ""}+ </p>+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto px-1 pb-2" role="tree" aria-label="Search results">+ {visible.map((file) => (+ <div key={file.path} role="treeitem" aria-expanded={!collapsed[file.path]} data-editor-search-file={file.path}>+ <div className="group flex items-center gap-1 rounded-md px-1 py-0.5 hover:bg-muted">+ <button type="button" className="flex min-w-0 flex-1 items-center gap-1 text-start" onClick={() => setCollapsed((value) => {+ const next = { ...value };+ if (next[file.path]) delete next[file.path];+ else next[file.path] = true;+ return next;+ })}>+ {collapsed[file.path] ? <ChevronRight className="size-3 shrink-0" /> : <ChevronDown className="size-3 shrink-0" />}+ <span className="truncate font-medium">{file.path.split("/").pop()}</span>+ <span className="truncate text-[10.5px] text-muted-foreground">{file.path.includes("/") ? file.path.slice(0, file.path.lastIndexOf("/")) : ""}</span>+ </button>+ <span className="rounded-full bg-muted px-1.5 text-[10px] text-muted-foreground group-hover:hidden">{file.matches.length}</span>+ {showReplace ? (+ <button type="button" title="Replace in this file" aria-label={`Replace in ${file.path}`} className="hidden text-muted-foreground hover:text-foreground group-hover:block" onClick={() => void apply(file.matches.map((match) => absoluteTarget(file.path, match)))}>+ <ReplaceAll className="size-3.5" />+ </button>+ ) : null}+ <button type="button" title="Dismiss" aria-label={`Dismiss ${file.path}`} className="hidden text-muted-foreground hover:text-foreground group-hover:block" onClick={() => setDismissed((value) => ({ ...value, [file.path]: true }))}>+ <X className="size-3.5" />+ </button>+ </div>+ {collapsed[file.path] ? null : file.matches.map((match) => {+ const before = match.text.slice(0, match.start);+ const hit = match.text.slice(match.start, match.end);+ const after = match.text.slice(match.end);+ return (+ <div key={match.key} className="group flex items-center gap-1 rounded-md py-0.5 ps-5 pe-1 hover:bg-muted" data-editor-search-match>+ <button+ type="button"+ className="min-w-0 flex-1 truncate text-start font-mono text-[11.5px]"+ title={`Line ${match.line}`}+ onClick={() => props.onOpen(file.path, match.line, match.start + match.textOffset + 1, match.end + match.textOffset + 1)}+ >+ <span className="text-muted-foreground">{before.trimStart().slice(-40)}</span>+ {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="rounded-sm bg-amber-4 text-foreground dark:bg-amber-6/60">{hit}</span>+ )}+ <span className="text-muted-foreground">{after.slice(0, 80)}</span>+ </button>+ {showReplace ? (+ <button type="button" title="Replace" aria-label="Replace this match" className="hidden text-muted-foreground hover:text-foreground group-hover:block" onClick={() => void apply([absoluteTarget(file.path, match)])}>+ <Replace className="size-3.5" />+ </button>+ ) : null}+ <button type="button" title="Dismiss" aria-label="Dismiss this match" className="hidden text-muted-foreground hover:text-foreground group-hover:block" onClick={() => setDismissed((value) => ({ ...value, [match.key]: true }))}>+ <X className="size-3.5" />+ </button>+ </div>+ );+ })}+ </div>+ ))}+ </div>+ </div>+ );+}diff --git a/apps/app/src/react-app/shell/session-route.tsx b/apps/app/src/react-app/shell/session-route.tsxindex eeb5f2ea..1876aa01 100644--- a/apps/app/src/react-app/shell/session-route.tsx+++ b/apps/app/src/react-app/shell/session-route.tsx@@ -2940,6 +2940,23 @@ export function SessionRoute() {useEditorStore.getState().requestModeToggle();},},+ ...(layoutModeName === "ide" ? ([+ ["editor.search", "Search in files", "Find and replace across the project", "Cmd/Ctrl+Shift+F", "search"],+ ["editor.problems", "Show problems", "Errors and warnings from the language servers", "Cmd+Shift+M (macOS)", "problems"],+ ["editor.quick-open", "Go to file", "Open a project file by name", "Cmd/Ctrl+P", "quick-open"],+ ["editor.symbol", "Go to symbol in file", "Jump to a function, class or variable", "Cmd/Ctrl+Shift+O", "symbol"],+ ["editor.outline", "Show outline", "The active file's symbols, under Files", "", "outline"],+ ] as const).map(([id, title, detail, meta, command]) => ({+ id,+ title,+ detail,+ meta,+ searchText: `editor ide ${title} ${detail}`.toLowerCase(),+ action: () => {+ setCommandPaletteOpen(false);+ window.dispatchEvent(new CustomEvent("omnirush:editor-command", { detail: command }));+ },+ })) : []),...(layoutModeName === "ide" ? [{id: "layout.chat-panel",title: "Show or hide the chat",diff --git a/apps/app/src/react-app/shell/use-shell-shortcuts.ts b/apps/app/src/react-app/shell/use-shell-shortcuts.tsindex a99f4aa0..16ee4893 100644--- a/apps/app/src/react-app/shell/use-shell-shortcuts.ts+++ b/apps/app/src/react-app/shell/use-shell-shortcuts.ts@@ -123,7 +123,9 @@ export function useShellShortcuts(input: UseShellShortcutsInput) {// Cmd/Ctrl+Shift+H -> IDE layout: show / hide the chat// Ctrl+Shift+` -> new terminal tab (matches VS Code; Ctrl on macOS too)// Cmd/Ctrl+F -> find in current conversation (handled by session surface)- // Cmd/Ctrl+Shift+F -> search every session (titles + messages)+ // Cmd/Ctrl+Shift+F -> search every session (titles + messages); in the IDE layout: search in files+ // Cmd/Ctrl+Shift+P -> command palette (as Cmd/Ctrl+K)+ // Cmd+Shift+M -> IDE layout, macOS: Problems// Cmd/Ctrl+T -> next session tab// Cmd/Ctrl+Shift+T -> previous session tab// Ctrl+T / Ctrl+Shift+T (macOS) -> next / previous thinking mode@@ -152,9 +154,24 @@ export function useShellShortcuts(input: UseShellShortcutsInput) {const isMac = typeof navigator !== "undefined" && /Mac/i.test(navigator.platform);const mod = isMac ? event.metaKey : event.ctrlKey;if (!mod) return;+ // In the IDE layout these keys work as in VS Code: Cmd/Ctrl+Shift+F searches the files, Cmd/Ctrl+Shift+P opens the palette,+ // Cmd+Shift+M (macOS) opens Problems. In the Chat layout Cmd/Ctrl+Shift+F stays the session search.+ const ideLayout = typeof document !== "undefined" && Boolean(document.querySelector("[data-editor-layout='ide']"));+ const editorCommand = (command: string) => window.dispatchEvent(new CustomEvent("omnirush:editor-command", { detail: command }));if (event.shiftKey && !event.altKey && event.key?.toLowerCase() === "f") {event.preventDefault();- setSessionSearchOpen((value) => !value);+ if (ideLayout) editorCommand("search");+ else setSessionSearchOpen((value) => !value);+ return;+ }+ if (event.shiftKey && !event.altKey && event.key?.toLowerCase() === "p") {+ event.preventDefault();+ setCommandPaletteOpen(true);+ return;+ }+ if (ideLayout && isMac && event.shiftKey && !event.altKey && event.key?.toLowerCase() === "m") {+ event.preventDefault();+ editorCommand("problems");return;}if (event.shiftKey && !event.altKey && event.key?.toLowerCase() === "e") {diff --git a/apps/server/src/editor-search.e2e.test.ts b/apps/server/src/editor-search.e2e.test.tsnew file mode 100644index 00000000..3d06c6b5--- /dev/null+++ b/apps/server/src/editor-search.e2e.test.ts@@ -0,0 +1,65 @@+import { afterEach, describe, expect, test } from "bun:test";+import { execFileSync } from "node:child_process";+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { findRipgrep, parseSearchOptions, searchWorkspace } from "./routes/editor-search.js";++const roots: string[] = [];+afterEach(async () => {+ while (roots.length) await rm(roots.pop()!, { recursive: true, force: true });+});++async function project() {+ const root = await mkdtemp(join(tmpdir(), "omnirush-search-"));+ roots.push(root);+ await mkdir(join(root, "src"), { recursive: true });+ await mkdir(join(root, "dist"), { recursive: true });+ await writeFile(join(root, ".gitignore"), "dist/\n");+ await writeFile(join(root, "src", "a.ts"), "const limit = 50;\nconst unlimited = limit * 2;\nconst é = 'limit';\n");+ await writeFile(join(root, "src", "b.test.ts"), "expect(limit).toBe(50);\n");+ await writeFile(join(root, "dist", "out.js"), "var limit=1;\n");+ await writeFile(join(root, "logo.bin"), new Uint8Array([0, 1, 108, 105, 109, 105, 116]));+ execFileSync("git", ["init", "-q"], { cwd: root });+ return root;+}++const options = (over: Record<string, unknown>) => parseSearchOptions({ query: "limit", ...over });++describe.each([["ripgrep", findRipgrep()], ["git", null]] as const)("search in files (%s)", (_name, rg) => {+ test("plain, gitignore respected, binary skipped", async () => {+ if (_name === "ripgrep" && !rg) return;+ const root = await project();+ const result = await searchWorkspace(root, options({}), rg);+ expect(result.files.map((file) => file.path).sort()).toEqual(["src/a.ts", "src/b.test.ts"]);+ expect(result.matchCount).toBe(5);+ const third = result.files.find((file) => file.path === "src/a.ts")!.matches.at(-1)!;+ expect(third.text.slice(third.start, third.end)).toBe("limit");+ });++ test("whole word, case, include and exclude", async () => {+ if (_name === "ripgrep" && !rg) return;+ const root = await project();+ const word = await searchWorkspace(root, options({ wholeWord: true, exclude: ["**/*.test.ts"] }), rg);+ expect(word.files.map((file) => file.path)).toEqual(["src/a.ts"]);+ expect(word.matchCount).toBe(3);+ const cased = await searchWorkspace(root, options({ query: "LIMIT", caseSensitive: true }), rg);+ expect(cased.matchCount).toBe(0);+ const included = await searchWorkspace(root, options({ include: ["**/*.test.ts"] }), rg);+ expect(included.files.map((file) => file.path)).toEqual(["src/b.test.ts"]);+ });++ test("regex", async () => {+ if (_name === "ripgrep" && !rg) return;+ const root = await project();+ const result = await searchWorkspace(root, options({ query: "lim[a-z]t \\*", regex: true }), rg);+ expect(result.matchCount).toBe(1);+ });+});++test("bad input is refused", () => {+ expect(() => parseSearchOptions({ query: "" })).toThrow();+ expect(() => parseSearchOptions({ query: "(", regex: true })).toThrow();+ expect(parseSearchOptions({ query: "x", include: ["../etc/*", "/abs", "src/**"] }).include).toEqual(["src/**"]);+});diff --git a/apps/server/src/routes/editor-search.ts b/apps/server/src/routes/editor-search.tsnew file mode 100644index 00000000..1245818d--- /dev/null+++ b/apps/server/src/routes/editor-search.ts@@ -0,0 +1,236 @@+/**+ * The desktop editor's search in files: ripgrep (on PATH, or the copy the+ * engine downloads to its data folder), else `git grep`. It runs as the user,+ * reads only inside the workspace, honours .gitignore, skips binary files,+ * and caps matches and time. Replacing is done by the editor itself (it+ * edits the open documents and saves them through the editor's file route).+ */+import { spawn } from "node:child_process";+import { existsSync } from "node:fs";+import { homedir } from "node:os";+import { join, resolve } from "node:path";+import { ApiError } from "../errors.js";+import type { ServerConfig, WorkspaceInfo } from "../types.js";+import { addRoute, type Route } from "./registry.js";++export const SEARCH_MAX_MATCHES = 5_000;+export const SEARCH_MAX_FILES = 1_000;+const SEARCH_TIMEOUT_MS = 20_000;+const MAX_LINE_CHARS = 400;+const MAX_QUERY = 1_000;+const MAX_GLOBS = 50;++export type SearchOptions = {+ query: string;+ regex: boolean;+ caseSensitive: boolean;+ wholeWord: boolean;+ include: string[];+ exclude: string[];+ maxMatches: number;+};++/** One match: 1-based line, 0-based UTF-16 columns into `text` (the line, cut to 400 chars around the match). */+export type SearchMatch = { line: number; text: string; start: number; end: number; textOffset: number };+export type SearchFileResult = { path: string; matches: SearchMatch[] };+export type SearchResult = { engine: "ripgrep" | "git" | "none"; files: SearchFileResult[]; matchCount: number; truncated: boolean; timedOut: boolean };++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>;+};++/** ripgrep: on PATH, or where the engine puts its own copy. */+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;+}++function globList(value: unknown): string[] {+ const raw = typeof value === "string" ? value.split(",") : Array.isArray(value) ? value : [];+ return raw+ .filter((item): item is string => typeof item === "string")+ .map((item) => item.trim())+ .filter((item) => item && !item.includes("\0") && !item.startsWith("/") && !/^[A-Za-z]:/.test(item) && !item.split(/[\\/]/).includes(".."))+ .slice(0, MAX_GLOBS);+}++export function parseSearchOptions(body: Record<string, unknown>): SearchOptions {+ const query = typeof body.query === "string" ? body.query : "";+ if (!query || query.length > MAX_QUERY) throw new ApiError(400, "invalid_payload", "A search text is required");+ if (body.regex === true) {+ try {+ new RegExp(query);+ } catch {+ throw new ApiError(400, "invalid_regex", "This is not a valid regular expression");+ }+ }+ const max = typeof body.maxMatches === "number" && Number.isFinite(body.maxMatches) ? Math.floor(body.maxMatches) : SEARCH_MAX_MATCHES;+ return {+ query,+ regex: body.regex === true,+ caseSensitive: body.caseSensitive === true,+ wholeWord: body.wholeWord === true,+ include: globList(body.include),+ exclude: globList(body.exclude),+ maxMatches: Math.min(Math.max(max, 1), SEARCH_MAX_MATCHES),+ };+}++function cutLine(text: string, start: number, end: number): { text: string; start: number; end: number; textOffset: number } {+ const clean = text.replace(/\r?\n$/, "");+ if (clean.length <= MAX_LINE_CHARS) return { text: clean, start, end, textOffset: 0 };+ const from = Math.max(0, Math.min(start - 80, clean.length - MAX_LINE_CHARS));+ return { text: clean.slice(from, from + MAX_LINE_CHARS), start: start - from, end: Math.min(end - from, MAX_LINE_CHARS), textOffset: from };+}++/** UTF-8 byte offset in `line` to a UTF-16 index. */+function byteToIndex(line: string, byteOffset: number): number {+ const buffer = Buffer.from(line, "utf8");+ return buffer.subarray(0, Math.max(0, Math.min(byteOffset, buffer.length))).toString("utf8").length;+}++function run(cmd: string, args: string[], cwd: string, onLine: (line: string) => boolean): Promise<{ timedOut: boolean; code: number | null; stderr: string }> {+ return new Promise((resolvePromise) => {+ const child = spawn(cmd, args, { cwd, stdio: ["ignore", "pipe", "pipe"], windowsHide: true, env: { ...process.env, LC_ALL: "C.UTF-8" } });+ let buffered = "";+ let stderr = "";+ let stopped = false;+ let timedOut = false;+ const timer = setTimeout(() => {+ timedOut = true;+ child.kill("SIGKILL");+ }, SEARCH_TIMEOUT_MS);+ child.stdout.setEncoding("utf8");+ child.stdout.on("data", (chunk: string) => {+ if (stopped) return;+ buffered += chunk;+ let index;+ while ((index = buffered.indexOf("\n")) >= 0) {+ const line = buffered.slice(0, index);+ buffered = buffered.slice(index + 1);+ if (!onLine(line)) {+ stopped = true;+ child.kill("SIGKILL");+ return;+ }+ }+ });+ child.stderr.on("data", (chunk: Buffer) => {+ if (stderr.length < 4_000) stderr += chunk.toString("utf8");+ });+ child.on("error", (error) => {+ clearTimeout(timer);+ resolvePromise({ timedOut, code: null, stderr: error.message });+ });+ child.on("close", (code) => {+ clearTimeout(timer);+ if (!stopped && buffered) onLine(buffered);+ resolvePromise({ timedOut, code, stderr });+ });+ });+}++export async function searchWorkspace(root: string, options: SearchOptions, rg = findRipgrep()): Promise<SearchResult> {+ const files = new Map<string, SearchMatch[]>();+ let matchCount = 0;+ let truncated = false;+ const add = (path: string, match: SearchMatch) => {+ if (path.split("/").some((part) => part.toLowerCase() === ".git")) return true;+ let list = files.get(path);+ if (!list) {+ if (files.size >= SEARCH_MAX_FILES) {+ truncated = true;+ return false;+ }+ list = [];+ files.set(path, list);+ }+ list.push(match);+ matchCount += 1;+ if (matchCount >= options.maxMatches) {+ truncated = true;+ return false;+ }+ return true;+ };++ if (rg) {+ const args = ["--json", "--no-config", "--max-columns", "2000", "--max-filesize", "5M", "--no-follow"];+ if (!options.regex) args.push("--fixed-strings");+ if (options.caseSensitive) args.push("--case-sensitive");+ else args.push("--ignore-case");+ if (options.wholeWord) args.push("--word-regexp");+ for (const glob of options.include) args.push("--glob", glob);+ for (const glob of options.exclude) args.push("--glob", `!${glob}`);+ args.push("--glob", "!.git", "--", options.query, ".");+ const outcome = await run(rg, args, root, (line) => {+ let event: { type?: string; data?: { path?: { text?: string }; lines?: { text?: string }; line_number?: number; submatches?: Array<{ start: number; end: number }> } };+ try {+ event = JSON.parse(line);+ } catch {+ return true;+ }+ if (event.type !== "match" || !event.data?.path?.text || typeof event.data.lines?.text !== "string") return true;+ const path = event.data.path.text.replace(/^\.\//, "").replace(/\\/g, "/");+ const text = event.data.lines.text;+ for (const sub of event.data.submatches ?? []) {+ const start = byteToIndex(text, sub.start);+ const end = byteToIndex(text, sub.end);+ if (!add(path, { line: event.data.line_number ?? 0, ...cutLine(text, start, end) })) return false;+ }+ return true;+ });+ if (outcome.code === 2 && !matchCount && /regex|parse/i.test(outcome.stderr)) {+ throw new ApiError(400, "invalid_regex", outcome.stderr.trim().slice(0, 300));+ }+ return { engine: "ripgrep", files: [...files].map(([path, matches]) => ({ path, matches })), matchCount, truncated, timedOut: outcome.timedOut };+ }++ // No ripgrep: git grep in a repository (tracked and untracked, ignored files left out), matched again here for columns.+ 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;+ }+ if (!add(path!, { line: Number(lineNumber), ...cutLine(text!, found.index, found.index + found[0].length) })) return false;+ }+ return true;+ });+ return { engine: "git", files: [...files].map(([path, matches]) => ({ path, matches })), matchCount, truncated, timedOut: outcome.timedOut };+}++export function registerEditorSearchRoutes(options: RegisterOptions): void {+ const { routes, config, jsonResponse, readJsonBody, resolveWorkspace } = options;+ addRoute(routes, "POST", "/workspace/:id/editor/search", "client", async (ctx) => {+ const workspace = await resolveWorkspace(config, ctx.params.id);+ const search = parseSearchOptions(await readJsonBody(ctx.request));+ return jsonResponse(await searchWorkspace(resolve(workspace.path), search));+ });+}diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex bd5f4b5a..43f4751d 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 { 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";import { registerSessionGroupRoutes } from "./routes/session-groups.js";@@ -4840,6 +4841,7 @@ function createRoutes(// The desktop editor. A save or a hunk review that names a chat the session// uploader is tracking adds a "user_edit" / "user_review" trace event to it;// nothing else in a chat's upload changes (editor-events.ts).+ registerEditorSearchRoutes({ routes, config, jsonResponse, readJsonBody, resolveWorkspace });registerEditorRoutes({routes,config,