A desktop coding agent with free access to frontier models.
TypeScript
fix: no unsaved text while any chat works, and a retried route check
ogsamratb6fabe824f86
diff --git a/apps/app/src/react-app/domains/session/chat/session-page.tsx b/apps/app/src/react-app/domains/session/chat/session-page.tsxindex 472059ef..45cefa8e 100644--- a/apps/app/src/react-app/domains/session/chat/session-page.tsx+++ b/apps/app/src/react-app/domains/session/chat/session-page.tsx@@ -2217,6 +2217,7 @@ export function SessionPage(props: SessionPageProps) {workspaceRoot={props.selectedWorkspaceRoot}sessionId={props.selectedSessionId}sessionBusy={sessionTurnRunning(props.selectedSessionId)}+ agentBusy={runningTurns !== ""}opencodeClient={props.opencodeClient ?? null}terminalOpen={Boolean(props.terminalOpen)}onToggleTerminal={() => props.onTerminalOpenChange?.(!props.terminalOpen)}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 4c15ddf5..171b6508 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@@ -80,6 +80,8 @@ export type EditorPanelProps = {workspaceRoot: string;sessionId: string | null;sessionBusy: boolean;+ /** Some chat's agent is working (the language servers are shared by every chat): no unsaved text goes to them. */+ agentBusy: boolean;opencodeClient: Client | null;terminal: ReactNode | null;terminalOpen: boolean;@@ -528,7 +530,7 @@ function showConflict(path: string, input: { reload: () => void; overwrite: () =}export default function EditorPanel(props: EditorPanelProps) {- const { client, workspaceId, workspaceRoot, sessionId, sessionBusy, opencodeClient } = props;+ const { client, workspaceId, workspaceRoot, sessionId, sessionBusy, agentBusy, opencodeClient } = props;const monaco = useMemo<Monaco>(() => setupMonaco(), []);const docs = useMemo(() => editorDocuments(monaco, client, workspaceId), [monaco, client, workspaceId]);const queryClient = useQueryClient();@@ -948,8 +950,8 @@ export default function EditorPanel(props: EditorPanelProps) {const activeFilePath = surface?.kind === "file" ? surface.doc.path : null;const lspActive = useIsLspActive(activeFilePath);useEffect(() => {- setLspSessionBusy(sessionBusy);- }, [sessionBusy]);+ setLspSessionBusy(agentBusy);+ }, [agentBusy]);useEffect(() => {if (!languageFeatures) clearLanguageFeatures();}, [languageFeatures]);@@ -985,7 +987,7 @@ export default function EditorPanel(props: EditorPanelProps) {window.clearTimeout(timer);subscription.dispose();};- }, [surface, lspActive, sessionBusy]);+ }, [surface, lspActive, agentBusy]);// Breadcrumbs: the symbols around the cursor.useEffect(() => {diff --git a/apps/app/src/react-app/domains/session/editor/lsp.ts b/apps/app/src/react-app/domains/session/editor/lsp.tsindex 4814e4b2..8a6b1866 100644--- a/apps/app/src/react-app/domains/session/editor/lsp.ts+++ b/apps/app/src/react-app/domains/session/editor/lsp.ts@@ -165,26 +165,47 @@ function inLane<T>(path: string, run: () => Promise<T>): Promise<T> {* 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;+// Only a definite answer is kept: a JSON array = the routes exist; 404/405 or anything else that is not an+// array = they do not. A network error, timeout or 5xx (the engine still starting) is asked again next time.+let support: { workspaceId: string; answer: Promise<boolean | null> } | null = null;+async function supported(ctx: Context): Promise<boolean | null> {+ if (!support || support.workspaceId !== ctx.workspaceId) {+ support = {+ workspaceId: ctx.workspaceId,+ answer: ctx.client.editorLsp<unknown>(ctx.workspaceId, "diagnostics", {}).then(+ (raw) => Array.isArray(raw),+ (error: { status?: number }) => (error.status === 404 || error.status === 405 ? false : null),+ ),+ };+ }+ const asked = support;+ const answer = await asked.answer;+ if (answer === null && support === asked) support = null;+ return answer;}-async function call<T>(op: Parameters<OmniRushServerClient["editorLsp"]>[1], payload: Parameters<OmniRushServerClient["editorLsp"]>[2]): Promise<T | null> {+type Payload = Parameters<OmniRushServerClient["editorLsp"]>[2];++/**+ * One language request. `build` makes the payload when the request is sent (its turn in the file's lane), so+ * whether unsaved text goes with it is decided then, not when it was queued.+ */+async function call<T>(op: Parameters<OmniRushServerClient["editorLsp"]>[1], path: string | null, build: () => Payload): Promise<T | 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) {+ const support = await supported(ctx);+ if (support !== true) {+ if (support === false && current === ctx) {unavailable = true;useProblemsStore.getState().setAvailable(false);}return null;}try {- const run = () => ctx.client.editorLsp<T>(ctx.workspaceId, op, payload);- return await (path ? inLane(path, run) : run());+ const run = () => (useEditorStore.getState().languageFeatures ? ctx.client.editorLsp<T>(ctx.workspaceId, op, build()) : Promise.resolve(null));+ const result = await (path ? inLane(path, run) : run());+ // Turned off or another workspace since: the answer is not shown.+ return current === ctx && useEditorStore.getState().languageFeatures ? result : null;} catch (error) {// An engine without the editor routes (older build): language features stay off quietly.if ((error as { status?: number }).status === 404) {@@ -261,7 +282,8 @@ export async function documentSymbols(model: MonacoApi.editor.ITextModel, optionif (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 raw = await call<LspDocumentSymbol[]>("symbols", path, () => payloadFor(model, path));+ if (isDirty(path) && sessionBusy) return cached?.symbols ?? null;const symbols = Array.isArray(raw) ? toDocumentSymbols(current.monaco, raw) : [];symbolCache.set(key, { version: model.getVersionId(), symbols });return symbols;@@ -342,15 +364,17 @@ export async function refreshFileDiagnostics(path: string): Promise<void> {// 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));+ const raw = await call<ProblemFile[]>("diagnostics", path, () => 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;+ // Sent without its unsaved text (an agent started meanwhile): the disk's diagnostics do not fit the buffer.+ if (isDirty(path) && sessionBusy) return;const file = raw.find((item) => item.path === path) ?? { path, diagnostics: [] };applyMarkers(path, file.diagnostics);useProblemsStore.getState().merge(ctx.workspaceId, file);}} finally {- diagnosticsRuns.delete(key);+ if (diagnosticsRuns.get(key) === run) diagnosticsRuns.delete(key);}}@@ -358,7 +382,7 @@ export async function refreshFileDiagnostics(path: string): Promise<void> {export async function refreshAllDiagnostics(): Promise<void> {if (!current) return;const ctx = current;- const raw = await call<ProblemFile[]>("diagnostics", {});+ const raw = await call<ProblemFile[]>("diagnostics", null, () => ({}));if (!raw || current !== ctx) return;// Files with unsaved changes keep what their own text gave (the servers hold the disk copy's).const before = useProblemsStore.getState().byWorkspace[ctx.workspaceId] ?? [];@@ -383,7 +407,6 @@ export function clearLanguageFeatures() {export function setLanguageContext(ctx: Context | null) {current = ctx;unavailable = false;- support = null;symbolCache.clear();diagnosticsRuns.clear();useProblemsStore.getState().setAvailable(true);@@ -399,7 +422,7 @@ export function installLanguageFeatures(monaco: Monaco) {// 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 || !isLspActive(path)) return null;- const contents = hoverContents(await call("hover", payloadFor(model, path, position)));+ const contents = hoverContents(await call("hover", path, () => payloadFor(model, path, position)));return contents.length ? { contents } : null;},});@@ -408,7 +431,7 @@ export function installLanguageFeatures(monaco: Monaco) {const path = modelPath(model);if (!path) return null;activateLsp(path);- return toLocations(await call("definition", payloadFor(model, path, position)));+ return toLocations(await call("definition", path, () => payloadFor(model, path, position)));},});monaco.languages.registerReferenceProvider(selector, {@@ -416,7 +439,7 @@ export function installLanguageFeatures(monaco: Monaco) {const path = modelPath(model);if (!path) return null;activateLsp(path);- return toLocations(await call("references", payloadFor(model, path, position)));+ return toLocations(await call("references", path, () => payloadFor(model, path, position)));},});monaco.languages.registerDocumentSymbolProvider(selector, {@@ -436,7 +459,7 @@ export function installLanguageFeatures(monaco: Monaco) {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 raw = await call<unknown[]>("rename", path, () => ({ ...payloadFor(model, path, position), newName }));const edits: MonacoApi.languages.IWorkspaceTextEdit[] = [];type TextEdit = { range: LspRange; newText: string };const addEdits = async (uri: string, list: TextEdit[]) => {diff --git a/apps/server/src/editor-search.e2e.test.ts b/apps/server/src/editor-search.e2e.test.tsindex 6801cd5d..030822d7 100644--- a/apps/server/src/editor-search.e2e.test.ts+++ b/apps/server/src/editor-search.e2e.test.ts@@ -81,3 +81,8 @@ test("ripgrep from the desktop engine's data folder", async () => {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));});++test("a search tool that cannot start is an error, not an empty result", async () => {+ const root = await project();+ await expect(searchWorkspace(root, options({}), join(root, "no-such-rg"))).rejects.toThrow();+});diff --git a/apps/server/src/routes/editor-search.ts b/apps/server/src/routes/editor-search.tsindex 81b4b691..2b781ce3 100644--- a/apps/server/src/routes/editor-search.ts+++ b/apps/server/src/routes/editor-search.ts@@ -101,7 +101,9 @@ function byteToIndex(line: string, byteOffset: number): number {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 }> {+type RunOutcome = { timedOut: boolean; code: number | null; stderr: string; spawnError?: string };++function run(cmd: string, args: string[], cwd: string, onLine: (line: string) => boolean): Promise<RunOutcome> {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 = "";@@ -132,7 +134,7 @@ function run(cmd: string, args: string[], cwd: string, onLine: (line: string) =>});child.on("error", (error) => {clearTimeout(timer);- resolvePromise({ timedOut, code: null, stderr: error.message });+ resolvePromise({ timedOut, code: null, stderr: error.message, spawnError: error.message });});child.on("close", (code) => {clearTimeout(timer);@@ -193,6 +195,7 @@ export async function searchWorkspace(root: string, options: SearchOptions, rg =}return true;});+ if (outcome.spawnError) throw new ApiError(500, "search_failed", `ripgrep could not start: ${outcome.spawnError.slice(0, 200)}`);if (outcome.code === 2 && !matchCount && /regex|parse/i.test(outcome.stderr)) {throw new ApiError(400, "invalid_regex", outcome.stderr.trim().slice(0, 300));}@@ -232,6 +235,7 @@ export async function searchWorkspace(root: string, options: SearchOptions, rg =});};let outcome = await gitGrep(options.regex ? "-P" : "-F");+ if (outcome.spawnError) throw new ApiError(500, "search_failed", `git could not start: ${outcome.spawnError.slice(0, 200)}`);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) {