Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 42 additions & 1 deletion app/api/agent/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand Down
20 changes: 20 additions & 0 deletions hooks/useAgentSession.rpc.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]);
Expand Down
7 changes: 6 additions & 1 deletion hooks/useAgentSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions lib/api-contract.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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"/);
Expand Down
24 changes: 24 additions & 0 deletions lib/rpc-manager.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
22 changes: 20 additions & 2 deletions lib/rpc-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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(
Expand Down
Loading