Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

fix: a failed sub-agent setting save is reported, never shown as saved

Samrat Talukdar53f25307cf1b
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.ts
index cf2ca482..122ca884 100644
--- a/apps/app/src/app/lib/omnirush-server.ts
+++ b/apps/app/src/app/lib/omnirush-server.ts
@@ -1482,15 +1482,24 @@ async function requestJson<T>(
);
const text = await response.text();
- const json = text ? JSON.parse(text) : null;
if (!response.ok) {
+ // The server's readable message when it sent one; a non-JSON error page
+ // (a proxy, a crash) still rejects with the status, not a parse error.
+ let json: { code?: unknown; message?: unknown; details?: unknown } | null = null;
+ try {
+ json = text ? JSON.parse(text) : null;
+ } catch {
+ json = null;
+ }
const code = typeof json?.code === "string" ? json.code : "request_failed";
- const message = typeof json?.message === "string" ? json.message : response.statusText;
+ const message = typeof json?.message === "string" && json.message
+ ? json.message
+ : response.statusText || `Request failed (${response.status})`;
throw new OmniRushServerError(response.status, code, message, json?.details);
}
- return json as T;
+ return (text ? JSON.parse(text) : null) as T;
}
async function requestAgentContextDiagnosticsJson(
diff --git a/apps/app/tests/subagent-model-menu.test.tsx b/apps/app/tests/subagent-model-menu.test.tsx
index dfcaa2c9..a8a4f763 100644
--- a/apps/app/tests/subagent-model-menu.test.tsx
+++ b/apps/app/tests/subagent-model-menu.test.tsx
@@ -25,8 +25,9 @@ if (typeof globalThis.window === "undefined" || typeof globalThis.document === "
}
Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", { configurable: true, value: true });
-const [{ SubagentModelMenu }] = await Promise.all([
+const [{ SubagentModelMenu }, { createOmniRushServerClient, OmniRushServerError }] = await Promise.all([
import("../src/react-app/domains/session/surface/composer/subagent-model-menu"),
+ import("../src/app/lib/omnirush-server"),
]);
const codex = ["low", "high", "xhigh", "max"];
@@ -118,3 +119,56 @@ test("hidden without an omnirush.ai account", async () => {
await mount(<SubagentModelMenu client={null} />);
expect(trigger()).toBeNull();
});
+
+test("a save the server could not write shows its message and keeps the previous setting", async () => {
+ const { client } = fakeClient({ model: "gpt-6-astra", effort: null });
+ const attempts: OmniRushSubagentModelSetting[] = [];
+ client.setSubagentModel = async (next: OmniRushSubagentModelSetting) => {
+ attempts.push(next);
+ throw new OmniRushServerError(500, "settings_write_failed", "The sub-agent setting could not be saved: EPERM", { code: "EPERM" });
+ };
+ await mount(<SubagentModelMenu client={client} />);
+ expect(trigger()?.textContent).toBe("GPT 6 Astra");
+
+ await act(async () => { trigger()!.click(); });
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 10)); });
+ await act(async () => { document.querySelector<HTMLElement>('[data-testid="subagent-model-gpt-6-sol"]')!.click(); });
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 10)); });
+
+ expect(attempts).toEqual([{ model: "gpt-6-sol", effort: null }]);
+ expect(toasts).toEqual(["error:The sub-agent setting could not be saved: EPERM"]);
+ // Not shown as saved: the trigger and the checked item stay on the previous model.
+ expect(trigger()?.textContent).toBe("GPT 6 Astra");
+ expect(document.querySelector('[data-testid="subagent-model-gpt-6-astra"]')?.getAttribute("aria-checked")).toBe("true");
+ expect(document.querySelector('[data-testid="subagent-model-gpt-6-sol"]')?.getAttribute("aria-checked")).toBe("false");
+ expect(document.querySelector('[role="alert"]')?.textContent).toBe("The sub-agent setting could not be saved: EPERM");
+});
+
+test("the server client rejects a failed save with the server's readable message", async () => {
+ const originalFetch = globalThis.fetch;
+ const calls: Array<{ url: string; method: string }> = [];
+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
+ calls.push({ url: String(input), method: init?.method ?? "GET" });
+ return new Response(
+ JSON.stringify({ code: "settings_write_failed", message: "The sub-agent setting could not be saved: EBUSY", details: { code: "EBUSY" } }),
+ { status: 500, headers: { "content-type": "application/json" } },
+ );
+ }) as typeof fetch;
+ try {
+ const server = createOmniRushServerClient({ baseUrl: "http://127.0.0.1:1", token: "token" });
+ const error = await server.setSubagentModel({ model: "gpt-6-sol", effort: "high" }).catch((caught: unknown) => caught);
+ expect(error).toBeInstanceOf(OmniRushServerError);
+ expect((error as InstanceType<typeof OmniRushServerError>).status).toBe(500);
+ expect((error as InstanceType<typeof OmniRushServerError>).code).toBe("settings_write_failed");
+ expect((error as Error).message).toBe("The sub-agent setting could not be saved: EBUSY");
+ expect(calls).toEqual([{ url: "http://127.0.0.1:1/omnirush/subagent-model", method: "PUT" }]);
+
+ // A non-JSON error page still rejects with the status, not a JSON parse error.
+ globalThis.fetch = (async () => new Response("<html>bad gateway</html>", { status: 502 })) as unknown as typeof fetch;
+ const proxied = await server.setSubagentModel({ model: null, effort: null }).catch((caught: unknown) => caught);
+ expect(proxied).toBeInstanceOf(OmniRushServerError);
+ expect((proxied as Error).message).toBe("Request failed (502)");
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+});
diff --git a/apps/server/src/omnirush-subagent-model.routes.test.ts b/apps/server/src/omnirush-subagent-model.routes.test.ts
index 1a15c999..9150c1c0 100644
--- a/apps/server/src/omnirush-subagent-model.routes.test.ts
+++ b/apps/server/src/omnirush-subagent-model.routes.test.ts
@@ -3,6 +3,7 @@ import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { atomicWriteFs } from "./atomic-write.js";
import { managedDesktopPolicy } from "./managed-desktop-policy.js";
import { policyRequestActions } from "./managed-policy-rules.js";
import { readSubagentModelSetting } from "./omnirush-subagent-model.js";
@@ -107,6 +108,40 @@ describe("sub-agent model routes", () => {
});
});
+ test("a save the disk keeps refusing answers a readable error and keeps the previous setting", async () => {
+ await withServer(async ({ base, config }) => {
+ const client = { authorization: "Bearer token", "content-type": "application/json" };
+ const put = (body: unknown) => fetch(`${base}/omnirush/subagent-model`, { method: "PUT", headers: client, body: JSON.stringify(body) });
+ expect((await put({ model: "gpt-6-astra", effort: "low" })).status).toBe(200);
+
+ const original = { ...atomicWriteFs };
+ let renames = 0;
+ // Windows: antivirus or the indexer holds the file for longer than the retries last.
+ atomicWriteFs.rename = async () => {
+ renames += 1;
+ throw Object.assign(new Error("EPERM: operation not permitted, rename"), { code: "EPERM" });
+ };
+ atomicWriteFs.sleep = async () => undefined;
+ let failed: Response;
+ try {
+ failed = await put({ model: "gpt-6-sol", effort: "high" });
+ } finally {
+ Object.assign(atomicWriteFs, original);
+ }
+ expect(failed.status).toBe(500);
+ expect(await failed.json()).toEqual({
+ code: "settings_write_failed",
+ message: "The sub-agent setting could not be saved: EPERM",
+ details: { code: "EPERM" },
+ });
+ expect(renames).toBe(10);
+
+ const read = await fetch(`${base}/omnirush/subagent-model`, { headers: client });
+ expect(((await read.json()) as { setting: unknown }).setting).toEqual({ model: "gpt-6-astra", effort: "low" });
+ expect(await readSubagentModelSetting(config)).toEqual({ model: "gpt-6-astra", effort: "low" });
+ });
+ });
+
test("organizations that lock settings lock the sub-agent setting too", () => {
expect(policyRequestActions("PUT", "/omnirush/subagent-model")).toEqual(["settings"]);
expect(policyRequestActions("POST", "/omnirush/subagent-model/resolve")).toEqual([]);
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 1786774a..47c10d2c 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -65,6 +65,7 @@ import {
import { deleteSkill, listSkills, renderSkillContentForResponse, upsertSkill } from "./skills.js";
import { deleteCommand, listCommands, repairCommands, upsertCommand } from "./commands.js";
import { ApiError, formatError } from "./errors.js";
+import { errorCode } from "./atomic-write.js";
import { readJsoncFile, updateJsoncTopLevel, writeJsoncFile } from "./jsonc.js";
import { recordAudit, readAuditEntries, readLastAudit } from "./audit.js";
import { ReloadEventStore } from "./events.js";
@@ -171,6 +172,7 @@ import {
subagentModelRefusals,
writeSubagentModelSetting,
type EngineModelRef,
+ type SubagentModelSetting,
} from "./omnirush-subagent-model.js";
import { findManagedEngineWorkspace } from "./workspaces.js";
import { startThreadApprovalReplayer, type ThreadApprovalReplayer } from "./thread-approvals.js";
@@ -3638,7 +3640,15 @@ function createRoutes(
if ((body.model && !setting.model) || (body.effort && !setting.effort)) {
throw new ApiError(400, "invalid_payload", "unknown model id or effort");
}
- return jsonResponse({ ok: true, setting: await writeSubagentModelSetting(config, setting) });
+ let saved: SubagentModelSetting;
+ try {
+ saved = await writeSubagentModelSetting(config, setting);
+ } catch (error) {
+ // Never a silent success: the app shows this and keeps the previous setting.
+ const code = errorCode(error);
+ throw new ApiError(500, "settings_write_failed", `The sub-agent setting could not be saved: ${code}`, { code });
+ }
+ return jsonResponse({ ok: true, setting: saved });
});
addRoute(routes, "POST", "/omnirush/subagent-model/resolve", "policy", async (ctx) => {