A desktop coding agent with free access to frontier models.
TypeScript
fix: a refused model switch keeps the chat on its own model
ogsamrat6081f3c1396b
diff --git a/apps/server/src/broker-model-switch.test.ts b/apps/server/src/broker-model-switch.test.tsnew file mode 100644index 00000000..4c5f6b80--- /dev/null+++ b/apps/server/src/broker-model-switch.test.ts@@ -0,0 +1,35 @@+// A chat's model switch on the 2.x engine (POST /api/session/:id/model) to another provider is refused before the+// engine takes it, so the session keeps its own model and its compaction still runs (server.ts, the v2 mount).+import { expect, test } from "bun:test";++import { OmniRushGatewayBroker } from "./omnirush-gateway-broker.js";++const sse = "event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":{\"id\":\"r1\",\"output\":[]}}\n\n";++function broker() {+ return new OmniRushGatewayBroker({+ credentials: { gatewayUrl: "https://gateway.example/omnirush/v1", accessToken: "access-token", refreshToken: "refresh-token" },+ engineToken: "local-engine-token",+ fetch: async () => new Response(sse, { status: 200, headers: { "content-type": "text/event-stream" } }),+ // One provider: the GPT models (the catalog's switch_group "openai").+ switchable: async (bound: string, asked: string) => bound === asked || (bound.startsWith("gpt-") && asked.startsWith("gpt-")),+ });+}++const turn = (session: string, model: string) => new Request("http://127.0.0.1/omnirush-gateway/v1/responses", {+ method: "POST",+ headers: { Authorization: "Bearer local-engine-token", "Content-Type": "application/json", "x-omnirush-session-id": session },+ body: JSON.stringify({ model: `omnirush/${model}`, input: [], stream: true }),+});++test("a pinned chat may switch within its provider; another provider is refused before the engine switches", async () => {+ const gateway = broker();+ expect(await gateway.modelSwitchRefusal("ses_new", "kimi-k3.1-pro")).toBeNull();+ await (await gateway.handle(turn("ses_a", "gpt-6-astra"), "responses")).text();+ expect(await gateway.modelSwitchRefusal("ses_a", "gpt-6-astra")).toBeNull();+ expect(await gateway.modelSwitchRefusal("ses_a", "omnirush/gpt-6.1-sol")).toBeNull();+ const refused = await gateway.modelSwitchRefusal("ses_a", "kimi-k3.1-pro");+ expect(refused?.status).toBe(400);+ expect(refused?.headers.get("x-should-retry")).toBe("false");+ expect(((await refused!.json()) as { error: { message: string } }).error.message).toBe("This chat runs on gpt-6-astra. Start a new chat to use kimi-k3.1-pro.");+});diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.tsindex 35b000d2..6e0059e6 100644--- a/apps/server/src/omnirush-gateway-broker.ts+++ b/apps/server/src/omnirush-gateway-broker.ts@@ -2245,6 +2245,19 @@ export class OmniRushGatewayBroker {});}+ /**+ * A chat's switch to `model` on the 2.x engine (POST /api/session/:id/model): refused as its next request would+ * be (fixedModelRefusal) when the chat is pinned to another provider, so the engine session keeps its own model.+ * A chat not pinned yet, the same model, or one of its provider: null.+ */+ async modelSwitchRefusal(session: string, model: string): Promise<Response | null> {+ const pin = this.sessionModels.get(session);+ const asked = model.replace(/^omnirush\//, "");+ if (!pin || pin === asked || (await this.switchable(pin, asked))) return null;+ this.log?.("info", "omnirush.ai chat model switch refused (another provider)", { pin, asked });+ return Response.json({ detail: SESSION_MODEL_FIXED, error: { type: "invalid_request_error", code: SESSION_MODEL_FIXED, message: `This chat runs on ${pin}. Start a new chat to use ${asked}.` } }, { status: 400, headers: { "x-should-retry": "false", [REFUSED_HEADER]: "1" } });+ }+/*** Every context-bearing request keeps the chat's provider, including* summaries, compaction and children: a model of another provider neverdiff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex e6e76769..bb1e043e 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -215,6 +215,7 @@ import { describeIgnored, type McpAllowEntry } from "./mcp-allow/mcp-allow.mjs";import { omnirushModelWantsReasoningSummary, readOmniRushModelCatalog } from "./omnirush-model-catalog.js";import { modelAllowedIn, modelModes, projectMode, serverModelStart } from "./model-modes/model-modes.mjs";import { switchableModels } from "./model-modes/strict-sessions.mjs";+import { OMNIRUSH_PROVIDER_ID } from "./provider-lock/provider-lock.mjs";import { serverLocalBox } from "./box/launch.js";import {SUBAGENT_MODEL_FALLBACK_TRACE,@@ -371,6 +372,7 @@ export function stopTurnActivity(config: ServerConfig): void {const voiceServicesByServer = new WeakMap<ServerConfig, OmniRushVoiceService>();/** The broker's integrity read (rate-limited there), per server, for the checklist bar's "Good session ★". */const sessionIntegrityByServer = new WeakMap<ServerConfig, OmniRushGatewayBroker["sessionIntegrity"]>();+const modelSwitchRefusalsByServer = new WeakMap<ServerConfig, OmniRushGatewayBroker["modelSwitchRefusal"]>();/** Recent gateway fallbacks per sub-agent session, for the swarm plugin's task-result note. */const subagentGatewayFallbacks = new WeakMap<ServerConfig, Map<string, Array<Record<string, unknown>>>>();@@ -1377,6 +1379,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {}));}if (gatewayBroker.enabled) sessionIntegrityByServer.set(config, (sessionId, options) => gatewayBroker.sessionIntegrity(sessionId, options));+ if (gatewayBroker.enabled) modelSwitchRefusalsByServer.set(config, (sessionId, model) => gatewayBroker.modelSwitchRefusal(sessionId, model));if (gatewayBroker.enabled) sideCallsByServer.set(config, brokerSideCall(gatewayBroker, config.omnirushEngineToken ?? ""));if (gatewayBroker.enabled) computerUseCapabilitiesByServer.set(config, (maxAgeMs) => gatewayBroker.sessionUploadCapabilities({ strict: true, maxAgeMs }));voiceServicesByServer.set(config, new OmniRushVoiceService(gatewayBroker, {@@ -2250,6 +2253,17 @@ export async function proxyOpencodeV2Request(input: {headers.delete("content-length");headers.set("content-type", "application/json");}+ // A chat's model switch (POST /api/session/:id/model) to another provider is refused here, as its next request+ // would be: the engine session keeps the chat's own model, so its compaction and later turns still run.+ if (method === "POST" && sessionId && /^\/api\/session\/[^/]+\/model$/.test(routePath) && requestBody) {+ let pick: unknown = null;+ try { pick = JSON.parse(new TextDecoder().decode(requestBody)); } catch { pick = null; }+ const model = isRecord(pick) && isRecord(pick.model) ? pick.model : null;+ if (model && model.providerID === OMNIRUSH_PROVIDER_ID && typeof model.id === "string") {+ const refusal = await modelSwitchRefusalsByServer.get(input.config)?.(sessionId, model.id);+ if (refusal) return refusal;+ }+ }// Archiving (archived-chats.ts): the app's own flag, taken off the PATCH before the engine sees it.if (method === "PATCH" && sessionId && /^\/api\/session\/[^/]+$/.test(routePath) && requestBody) {let patch: unknown = null;