From b0fea2a4468b5aad7cc59aa68627dd11a2c2ece1 Mon Sep 17 00:00:00 2001 From: K <61059522+kahme247@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:35:56 +0300 Subject: [PATCH 1/2] Add files via upload --- app/api/agent/[id]/route.ts | 43 ++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/app/api/agent/[id]/route.ts b/app/api/agent/[id]/route.ts index d6b394545..6bac94b41 100644 --- a/app/api/agent/[id]/route.ts +++ b/app/api/agent/[id]/route.ts @@ -90,7 +90,48 @@ export async function POST( const header = readSessionHeader(filePath); const { cwd } = resolveSpawnCwdResult(header?.cwd); - const { session } = await startRpcSession(id, filePath, cwd, undefined, advisor, header?.cwd); + // A cold set_model must reach omp before the saved model is restored: + // spawning with only --resume lets omp exit on an unrestorable saved + // model before the RPC below ever runs (#277). Binding the requested + // model at spawn time skips that restore check. Live children never + // reach this path (they take the fast path above), and any other command + // keeps the previous spawn behavior. + const spawnModel = + body.type === "set_model" && + typeof body.provider === "string" && + typeof body.modelId === "string" && + body.provider.trim() && + body.modelId.trim() && + !body.provider.startsWith("-") && + !body.modelId.startsWith("-") && + !/\s/.test(body.provider) && + !/\s/.test(body.modelId) + ? `${body.provider}/${body.modelId}` + : undefined; + + const { session } = await startRpcSession(id, filePath, cwd, undefined, advisor, header?.cwd, undefined, spawnModel); + if (spawnModel) { + // Try the normal RPC first: when it succeeds it also records the new + // model in the session, so later spawns restore it without an override. + // But in omp 18.12.6 set_model can fail spuriously with "Model not + // found" for a catalog model whose provider has no credentials + // configured, even though the spawn already bound it. In that case the + // switch itself succeeded — verify from live state and report success + // rather than a false failure. A mismatch (e.g. an omp without --model + // precedence) rethrows the RPC error, so a real failure still surfaces. + try { + const result = await session.send(body); + return NextResponse.json({ success: true, data: result }); + } catch (error) { + const state = (await session.send({ type: "get_state" })) as { + model?: { id?: unknown; provider?: unknown }; + } | null; + if (state?.model?.provider === body.provider && state?.model?.id === body.modelId) { + return NextResponse.json({ success: true, data: { id: body.modelId, provider: body.provider } }); + } + throw error; + } + } const result = await session.send(body); return NextResponse.json({ success: true, data: result }); From 421f465ba6a18b34b51a460bdf309fced9fd0399 Mon Sep 17 00:00:00 2001 From: kahme247 <61059522+kahme247@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:43:03 +0300 Subject: [PATCH 2/2] fix(agent): recover cold model switches with --model at spawn (#277) --- hooks/useAgentSession.rpc.test.mjs | 20 ++++++++++++++++++++ hooks/useAgentSession.ts | 7 ++++++- lib/api-contract.test.mjs | 17 +++++++++++++++++ lib/rpc-manager.test.mjs | 24 ++++++++++++++++++++++++ lib/rpc-manager.ts | 22 ++++++++++++++++++++-- 5 files changed, 87 insertions(+), 3 deletions(-) diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index 53e2d2471..139d5cd06 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -3115,6 +3115,26 @@ test("a held file snapshot cannot roll back a newer RPC model choice", async () assert.equal(w.latest.thinkingLevel, "high"); }); +test("a failed model switch is shown as a notice instead of failing silently (#277)", async () => { + resetWorld(); + primeSession("s1", [userMsg("u0", "q")]); + Object.assign(world.sessions.get("s1"), { model: { provider: "test", modelId: "old-model" }, thinkingLevel: "low" }); + const w = await mountSession("s1"); + assert.equal(w.latest.displayModel.modelId, "old-model"); + world.holds.push({ + match: (method, _url, body) => method === "POST" && body?.type === "set_model", + produce: async () => ({ + status: 500, + value: { error: "omp exited (code 1, signal none): error: Could not restore model test/old-model" }, + }), + }); + await act(async () => { await w.latest.handleModelChange("test", "chosen-model"); }); + await settle(); + assert.equal(w.latest.displayModel.modelId, "old-model", "a failed switch must not claim the new model"); + assert.equal(w.latest.notices.at(-1)?.type, "error"); + assert.match(w.latest.notices.at(-1)?.message ?? "", /Could not restore model/); +}); + test("idle catch-up cannot overwrite a pending thinking command", async () => { resetWorld(); primeSession("s1", [userMsg("u0", "q")]); diff --git a/hooks/useAgentSession.ts b/hooks/useAgentSession.ts index fec6500f5..b8aed0528 100644 --- a/hooks/useAgentSession.ts +++ b/hooks/useAgentSession.ts @@ -3133,11 +3133,16 @@ export function useAgentSession(opts: UseAgentSessionOptions) { setCurrentModelOverride({ provider, modelId }); await refreshLiveModelState(sid); } catch (e) { + // Previously this was console-only, so a cold-start failure (e.g. an + // unrestorable saved model, #277) left the composer showing the old + // model with no explanation. The override above is only set on success, + // so the displayed model stays honest; the notice explains why. console.error("Failed to set model:", e); + addNotice({ type: "error", message: e instanceof Error ? e.message : String(e) }); } finally { modelCommandPendingRef.current -= 1; } - }, [isNew, setNewSessionModel, refreshLiveModelState]); + }, [isNew, setNewSessionModel, refreshLiveModelState, addNotice]); const handleFastModeChange = useCallback(async (enabled: boolean) => { // A brand-new session has no runtime yet: the model picker updates local diff --git a/lib/api-contract.test.mjs b/lib/api-contract.test.mjs index 45ecd37e8..f5b3298e9 100644 --- a/lib/api-contract.test.mjs +++ b/lib/api-contract.test.mjs @@ -199,6 +199,23 @@ test("agent command route forwards the advisor choice to lazy spawns via query p assert.match(route, /existing\.send\(body\)/); }); +test("agent command route binds a cold set_model to the lazy spawn (#277)", async () => { + const route = await readFile(new URL("../app/api/agent/[id]/route.ts", import.meta.url), "utf8"); + // Only a set_model body may become a spawn model; every other command + // keeps the previous spawn behavior. + assert.match(route, /body\.type === "set_model"/); + assert.match(route, /startRpcSession\(id, filePath, cwd, undefined, advisor, header\?\.cwd, undefined, spawnModel\)/); + assert.match(route, /\$\{body\.provider\}\/\$\{body\.modelId\}/); + // A spawn-bound model is verified from live state when the set_model RPC + // fails spuriously (omp can reject a catalog model for an uncredentialed + // provider even though the spawn already bound it); a real mismatch + // rethrows the RPC error. + assert.match(route, /if \(spawnModel\)/); + assert.match(route, /session\.send\(\{ type: "get_state" \}\)/); + assert.match(route, /state\?\.model\?\.provider === body\.provider && state\?\.model\?\.id === body\.modelId/); + assert.match(route, /throw error;/); +}); + test("mcp listing carries the advisor opinion into fresh spawns only", async () => { const route = await readFile(new URL("../app/api/mcp/route.ts", import.meta.url), "utf8"); assert.match(route, /params\.get\("advisor"\) === "1"/); diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index cc6b615c7..ad392fcb6 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -817,6 +817,30 @@ test("buildSessionSpawnArgs applies workspace launch config safely", async () => assert.deepEqual(buildSessionSpawnArgs("", undefined, false, { profile: "--evil" }), []); }); +test("buildSessionSpawnArgs binds an explicit model on resume only (#277)", async () => { + const { createJiti } = await import("jiti"); + const jiti = createJiti(import.meta.url); + const { buildSessionSpawnArgs } = jiti("./rpc-manager.ts"); + + // A cold set_model must reach omp before the saved model is restored, so + // the spawn carries --model alongside --resume. + assert.deepEqual( + buildSessionSpawnArgs("/tmp/session.jsonl", undefined, false, undefined, "october/gpt-6.1-sol"), + ["--resume", "/tmp/session.jsonl", "--model", "october/gpt-6.1-sol"], + ); + // New sessions apply their model over RPC after spawn, not at spawn time. + assert.deepEqual(buildSessionSpawnArgs("", undefined, false, undefined, "october/gpt-6.1-sol"), []); + // Flag-smuggled / whitespace values never become a flag slot. + assert.deepEqual( + buildSessionSpawnArgs("/tmp/session.jsonl", undefined, false, undefined, "--evil"), + ["--resume", "/tmp/session.jsonl"], + ); + assert.deepEqual( + buildSessionSpawnArgs("/tmp/session.jsonl", undefined, false, undefined, "october/gpt 6"), + ["--resume", "/tmp/session.jsonl"], + ); +}); + test("reload restart respawns with the wrapper's advisor flag", async () => { const source = await readFile(new URL("./rpc-manager.ts", import.meta.url), "utf8"); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 250a8e160..a0bf9e130 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -193,13 +193,21 @@ export function mapPresetToolNames(toolNames: string[]): string[] { const FULL_PRESET_KEY = [...PRESET_FULL].map((n) => n.toLowerCase()).sort().join(","); /** Extra CLI args for spawning `omp --mode rpc-ui` for a session. */ -export function buildSessionSpawnArgs(sessionFile: string, toolNames?: string[], advisor = false, launchConfig?: ProjectLaunchConfig): string[] { +export function buildSessionSpawnArgs(sessionFile: string, toolNames?: string[], advisor = false, launchConfig?: ProjectLaunchConfig, modelOverride?: string): string[] { const args: string[] = []; if (sessionFile) { // An absolute path (or anything containing "/") resolves deterministically: // omp's createSessionManager opens it directly via SessionManager.open // without any interactive resume/fork prompts (main.ts resume handling). args.push("--resume", sessionFile); + // An explicitly chosen model replaces the saved model and skips its + // restore check (omp's --model at startup). Without this, resuming a + // session whose saved model can no longer be restored dies before any + // set_model RPC can run (#277). Args are passed as an argv array, never + // through a shell, so only whitespace / flag-smuggled values are kept out. + if (modelOverride && !modelOverride.startsWith("-") && !/\s/.test(modelOverride)) { + args.push("--model", modelOverride); + } } else if (toolNames !== undefined) { const presetKey = toolNames.map((n) => n.toLowerCase()).sort().join(","); if (toolNames.length === 0) { @@ -2126,6 +2134,16 @@ export async function startRpcSession( * fallback (recorded dir gone) and warn the user. Omit for new sessions. */ recordedCwd?: string | null, launchConfig?: ProjectLaunchConfig, + /** Model to bind at spawn time as `provider/modelId` (--model). Only used + * when resuming: it replaces the saved model and skips its restore check, + * so a cold set_model can recover a session whose saved model is gone + * (#277). Ignored when a live child is reused; the caller's set_model RPC + * then runs against that child as before. The spawn alone does not rewrite + * the session file, so a later spawn without an override still hits the + * old saved model until omp records a new one (a successful set_model RPC + * or a completed turn); the picker path re-binds on each cold switch, so + * the user is never stuck on the unrestorable model. */ + spawnModel?: string, ): Promise<{ session: AgentSessionWrapper; realSessionId: string }> { const registry = getRegistry(); const locks = getLocks(); @@ -2177,7 +2195,7 @@ export async function startRpcSession( cwd, // User-configured variables for MCP servers and generated configs (#104). env: getAgentEnvOverrides(), - extraArgs: buildSessionSpawnArgs(sessionFile, toolNames, advisor === true, launchConfig), + extraArgs: buildSessionSpawnArgs(sessionFile, toolNames, advisor === true, launchConfig, spawnModel), onExit: (info) => holder.wrapper?.handleProcessExit(info, proc), }); const created = new AgentSessionWrapper(