Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: discover runtime model catalogs (#624)

Gustavo Ye18861c0e5016
diff --git a/src/daemon/agent-driver/src/adapters/claude/index.test.ts b/src/daemon/agent-driver/src/adapters/claude/index.test.ts
index d727a641e..3b6b85f3e 100644
--- a/src/daemon/agent-driver/src/adapters/claude/index.test.ts
+++ b/src/daemon/agent-driver/src/adapters/claude/index.test.ts
@@ -4,18 +4,25 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { PassThrough } from "node:stream";
import { afterEach, describe, expect, it, vi } from "vitest";
+import type { ProbeResult } from "../../internal/adapter.js";
import { fakeLaunchContext } from "../../testing/adapter-fixture.js";
import { ClaudeDriver } from "./index.js";
const spawnAgentProcess = vi.hoisted(() => vi.fn());
+const probeClaude = vi.hoisted(() => vi.fn<() => ProbeResult>());
vi.mock("../../internal/killTree.js", async () => ({
...(await vi.importActual<typeof import("../../internal/killTree.js")>("../../internal/killTree.js")),
spawnAgentProcess,
}));
+vi.mock("../../internal/probe.js", async () => ({
+ ...(await vi.importActual<typeof import("../../internal/probe.js")>("../../internal/probe.js")),
+ probeClaude,
+}));
const directories: string[] = [];
afterEach(() => {
spawnAgentProcess.mockReset();
+ probeClaude.mockReset();
for (const directory of directories.splice(0)) rmSync(directory, { recursive: true, force: true });
});
@@ -27,6 +34,32 @@ describe("ClaudeDriver", () => {
});
});
+ it("reports only the three stable Claude aliases after a healthy probe", () => {
+ probeClaude.mockReturnValue({ status: "healthy", version: "1.2.3" });
+
+ expect(new ClaudeDriver().probe()).toEqual({
+ status: "healthy",
+ version: "1.2.3",
+ reasoning: {
+ updateMode: "unsupported",
+ models: [
+ { id: "opus", supportedReasoningEfforts: [] },
+ { id: "sonnet", supportedReasoningEfforts: [] },
+ { id: "haiku", supportedReasoningEfforts: [] },
+ ],
+ },
+ });
+ });
+
+ it("keeps an unhealthy default Claude probe unchanged without adding a catalog", () => {
+ probeClaude.mockReturnValue({ status: "unhealthy", lastError: "not_on_path" });
+
+ expect(new ClaudeDriver().probe()).toEqual({
+ status: "unhealthy",
+ lastError: "not_on_path",
+ });
+ });
+
it("encodes same-turn safe-boundary input with the active resumed session", () => {
const driver = new ClaudeDriver();
expect(driver.currentSessionId).toBeNull();
diff --git a/src/daemon/agent-driver/src/adapters/claude/index.ts b/src/daemon/agent-driver/src/adapters/claude/index.ts
index 39290fc97..8efe9fff6 100644
--- a/src/daemon/agent-driver/src/adapters/claude/index.ts
+++ b/src/daemon/agent-driver/src/adapters/claude/index.ts
@@ -9,7 +9,7 @@
*/
import type {
BackendAdapter, EncodeMessageOptions, AdapterLaunchContext, AdapterEvent, RuntimeLane,
- RuntimeLaneOpenOptions, SpawnedProcess,
+ RuntimeLaneOpenOptions, SpawnedProcess, ProbeResult,
} from "../../internal/adapter.js";
import { createProcessLane } from "../../controller/process-host.js";
import { prepareCliTransport } from "../../internal/cliTransport.js";
@@ -21,6 +21,14 @@ import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";
import { spawnAgentProcess } from "../../internal/killTree.js";
import { ClaudeTurnProtocol } from "./turnProtocol.js";
+const CLAUDE_MODEL_CATALOG = {
+ updateMode: "unsupported" as const,
+ models: ["opus", "sonnet", "haiku"].map((id) => ({
+ id,
+ supportedReasoningEfforts: [],
+ })),
+};
+
export class ClaudeDriver implements BackendAdapter {
readonly id = "claude";
readonly instructionDelivery = { kind: "workspace_file", canonical: "AGENTS.md", aliases: ["CLAUDE.md"] } as const;
@@ -38,13 +46,19 @@ export class ClaudeDriver implements BackendAdapter {
return this.turnProtocol.beginTurn();
}
- probe(command?: string) {
+ probe(command?: string): ProbeResult {
const explicit = command?.trim();
- if (!explicit) return probeClaude();
- const result = probeCommandVersion(explicit);
- return result.ok
- ? { status: "healthy" as const, version: result.version }
- : { status: "unhealthy" as const, lastError: result.error };
+ const base: ProbeResult = explicit
+ ? (() => {
+ const result = probeCommandVersion(explicit);
+ return result.ok
+ ? { status: "healthy", version: result.version }
+ : { status: "unhealthy", lastError: result.error };
+ })()
+ : probeClaude();
+ return base.status === "healthy"
+ ? { ...base, reasoning: CLAUDE_MODEL_CATALOG }
+ : base;
}
async openLane(ctx: AdapterLaunchContext, options?: RuntimeLaneOpenOptions): Promise<RuntimeLane> {
diff --git a/src/daemon/agent-driver/src/adapters/codex/index.test.ts b/src/daemon/agent-driver/src/adapters/codex/index.test.ts
index ad6d1ea39..6ed2126a6 100644
--- a/src/daemon/agent-driver/src/adapters/codex/index.test.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/index.test.ts
@@ -226,15 +226,13 @@ describe("CodexDriver reasoning catalog probe", () => {
});
});
- it("treats a non-array model/list data field as an empty catalog", async () => {
+ it("treats a non-array model/list data field as an unavailable catalog", async () => {
const proc = probingProcess((request) => request.method === "initialize"
? { jsonrpc: "2.0", id: request.id, result: {} }
: { jsonrpc: "2.0", id: request.id, result: { data: "invalid", nextCursor: null } });
runtimeMocks.spawnAgentProcess.mockReturnValueOnce(proc as never);
- await expect(new CodexDriver().probe()).resolves.toMatchObject({
- reasoning: { models: [] },
- });
+ await expect(new CodexDriver().probe()).resolves.toMatchObject({ reasoning: undefined });
});
it("ignores malformed and unrelated lines before consuming the catalog response", async () => {
@@ -256,8 +254,55 @@ describe("CodexDriver reasoning catalog probe", () => {
await expect(new CodexDriver().probe()).resolves.toMatchObject({
status: "healthy",
- reasoning: { models: [] },
+ reasoning: undefined,
+ });
+ });
+
+ it("returns no catalog rather than a truncated list when pagination exceeds 512 models", async () => {
+ const models = Array.from({ length: 512 }, (_, index) => ({
+ id: `gpt-model-${index}`,
+ supportedReasoningEfforts: [],
+ }));
+ const proc = probingProcess((request) => request.method === "initialize"
+ ? { jsonrpc: "2.0", id: request.id, result: {} }
+ : { jsonrpc: "2.0", id: request.id, result: { data: models, nextCursor: "more" } });
+ runtimeMocks.spawnAgentProcess.mockReturnValueOnce(proc as never);
+
+ await expect(new CodexDriver().probe()).resolves.toMatchObject({
+ status: "healthy",
+ reasoning: undefined,
+ });
+ });
+
+ it("returns no catalog when a producer ignores the page limit and sends 513 unique models", async () => {
+ const models = Array.from({ length: 513 }, (_, index) => ({
+ id: `gpt-model-${index}`,
+ supportedReasoningEfforts: [],
+ }));
+ const proc = probingProcess((request) => request.method === "initialize"
+ ? { jsonrpc: "2.0", id: request.id, result: {} }
+ : { jsonrpc: "2.0", id: request.id, result: { data: models, nextCursor: null } });
+ runtimeMocks.spawnAgentProcess.mockReturnValueOnce(proc as never);
+
+ await expect(new CodexDriver().probe()).resolves.toMatchObject({ reasoning: undefined });
+ });
+
+ it("returns no catalog when app-server output exceeds the byte bound", async () => {
+ const proc = probingProcess(() => ({ jsonrpc: "2.0", id: -1, result: {} }));
+ proc.stdin.write = vi.fn((line: string) => {
+ const request = JSON.parse(line.trim()) as Record<string, any>;
+ queueMicrotask(() => {
+ if (request.method === "initialize") {
+ proc.stdout.emit("data", Buffer.from(`${JSON.stringify({ id: request.id, result: {} })}\n`));
+ } else {
+ proc.stdout.emit("data", Buffer.alloc(1024 * 1024 + 1, "x"));
+ }
+ });
+ return true;
});
+ runtimeMocks.spawnAgentProcess.mockReturnValueOnce(proc as never);
+
+ await expect(new CodexDriver().probe()).resolves.toMatchObject({ reasoning: undefined });
});
it("treats initialize rejection as an unavailable catalog", async () => {
diff --git a/src/daemon/agent-driver/src/adapters/codex/index.ts b/src/daemon/agent-driver/src/adapters/codex/index.ts
index be44ca953..0daf559d0 100644
--- a/src/daemon/agent-driver/src/adapters/codex/index.ts
+++ b/src/daemon/agent-driver/src/adapters/codex/index.ts
@@ -32,10 +32,15 @@ import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";
import { killProcessTree, spawnAgentProcess } from "../../internal/killTree.js";
import { jsonRpcRequest, tryParseJsonLine } from "../../internal/utils.js";
import { scrubDriverErrorMessage } from "../../internal/errors.js";
+import {
+ normalizeRuntimeModelId,
+ RUNTIME_MODEL_CATALOG_MAX,
+} from "../../internal/modelCatalog.js";
const SETTINGS_UPDATE_TIMEOUT_MS = 5_000;
const MODEL_LIST_TIMEOUT_MS = 5_000;
-const MODEL_LIST_MAX = 64;
+const MODEL_LIST_OUTPUT_MAX_BYTES = 1024 * 1024;
+const MODEL_LIST_MAX = RUNTIME_MODEL_CATALOG_MAX;
const MODEL_EFFORT_MAX = 16;
/** True when Codex cannot resume because the prior thread rollout is gone. */
@@ -152,11 +157,13 @@ export class CodexDriver implements BackendAdapter {
return new Promise((resolve) => {
let settled = false;
let buffer = "";
+ let outputBytes = 0;
let nextId = 0;
let initializeId = 0;
let listId = 0;
const models: RuntimeReasoningCatalog["models"][number][] = [];
const seenModels = new Set<string>();
+ let overflow = false;
let defaultModelId: string | undefined;
const finish = (catalog?: RuntimeReasoningCatalog) => {
if (settled) return;
@@ -176,10 +183,14 @@ export class CodexDriver implements BackendAdapter {
) + "\n");
};
const consumeModel = (value: unknown) => {
- if (!value || typeof value !== "object" || models.length >= MODEL_LIST_MAX) return;
+ if (!value || typeof value !== "object") return;
const model = value as Record<string, unknown>;
- const id = typeof model.id === "string" ? model.id.trim() : "";
- if (!id || id.length > 100 || seenModels.has(id)) return;
+ const id = normalizeRuntimeModelId(model.id);
+ if (!id || seenModels.has(id)) return;
+ if (models.length >= MODEL_LIST_MAX) {
+ overflow = true;
+ return;
+ }
const rawOptions = Array.isArray(model.supportedReasoningEfforts)
? model.supportedReasoningEfforts
: [];
@@ -226,8 +237,11 @@ export class CodexDriver implements BackendAdapter {
if (message.error || !message.result || typeof message.result !== "object") return finish();
const result = message.result as Record<string, unknown>;
for (const model of Array.isArray(result.data) ? result.data : []) consumeModel(model);
+ if (overflow) return finish();
const cursor = typeof result.nextCursor === "string" ? result.nextCursor : undefined;
- if (cursor && models.length < MODEL_LIST_MAX) return requestModelPage(cursor);
+ if (cursor && models.length >= MODEL_LIST_MAX) return finish();
+ if (cursor) return requestModelPage(cursor);
+ if (models.length === 0) return finish();
finish({
updateMode: "live_next_turn",
...(defaultModelId ? { defaultModelId } : {}),
@@ -237,7 +251,10 @@ export class CodexDriver implements BackendAdapter {
const timer = setTimeout(() => finish(), MODEL_LIST_TIMEOUT_MS);
timer.unref?.();
proc.stdout?.on("data", (chunk) => {
- buffer += chunk.toString();
+ const text = chunk.toString();
+ outputBytes += Buffer.byteLength(text);
+ if (outputBytes > MODEL_LIST_OUTPUT_MAX_BYTES) return finish();
+ buffer += text;
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) if (line.trim()) onLine(line);
diff --git a/src/daemon/agent-driver/src/adapters/cursor/index.test.ts b/src/daemon/agent-driver/src/adapters/cursor/index.test.ts
index cd9d57dce..a34befee8 100644
--- a/src/daemon/agent-driver/src/adapters/cursor/index.test.ts
+++ b/src/daemon/agent-driver/src/adapters/cursor/index.test.ts
@@ -187,6 +187,30 @@ afterEach(() => {
});
describe("CursorDriver persistent ACP transport", () => {
+ it("uses --list-models output for a non-fatal startup catalog", () => {
+ const outputProbe = vi.fn(() => ({
+ ok: true as const,
+ output: "Available models\ngpt-5.6-sol - GPT 5.6 Sol\nclaude-opus - Claude Opus\n",
+ }));
+ const result = new CursorDriver(outputProbe).probe(process.execPath);
+
+ expect(outputProbe).toHaveBeenCalledWith(process.execPath, ["--list-models"]);
+ expect(result).toMatchObject({
+ status: "healthy",
+ reasoning: {
+ models: [
+ { id: "gpt-5.6-sol", supportedReasoningEfforts: [] },
+ { id: "claude-opus", supportedReasoningEfforts: [] },
+ ],
+ },
+ });
+ });
+
+ it("keeps runtime health healthy when --list-models fails", () => {
+ expect(new CursorDriver(() => ({ ok: false, error: "ETIMEDOUT" })).probe(process.execPath))
+ .toMatchObject({ status: "healthy", reasoning: undefined });
+ });
+
it("spawns cursor-agent acp once with piped stdin and performs the strict handshake before prompt", async () => {
const server = installServer();
const driver = new CursorDriver();
diff --git a/src/daemon/agent-driver/src/adapters/cursor/index.ts b/src/daemon/agent-driver/src/adapters/cursor/index.ts
index 7c7f5bd53..9a2246af1 100644
--- a/src/daemon/agent-driver/src/adapters/cursor/index.ts
+++ b/src/daemon/agent-driver/src/adapters/cursor/index.ts
@@ -17,7 +17,13 @@ import type {
import { prepareCliTransport } from "../../internal/cliTransport.js";
import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";
import { spawnAgentProcess } from "../../internal/killTree.js";
-import { probeCliRuntime, resolveSpawnSpec } from "../../internal/probe.js";
+import {
+ probeCliRuntime,
+ probeCommandOutput,
+ resolveSpawnSpec,
+ type CommandOutputProbeResult,
+} from "../../internal/probe.js";
+import { parseCursorModelCatalog } from "../../internal/modelCatalog.js";
import { CursorAcpLane, type CursorAcpProcessFactory } from "./acp-lane.js";
export class CursorDriver implements BackendAdapter, CursorAcpProcessFactory {
@@ -30,8 +36,19 @@ export class CursorDriver implements BackendAdapter, CursorAcpProcessFactory {
terminalOwnership: "transport_request",
} as const;
+ constructor(
+ private readonly outputProbe: (command: string, args: string[]) => CommandOutputProbeResult = probeCommandOutput,
+ ) {}
+
probe(command?: string) {
- return probeCliRuntime("cursor-agent", {}, command);
+ const result = probeCliRuntime("cursor-agent", {}, command);
+ if (result.status !== "healthy") return result;
+ const spec = resolveSpawnSpec("cursor-agent", ["--list-models"], command);
+ const output = this.outputProbe(spec.command, spec.args);
+ return {
+ ...result,
+ reasoning: output.ok ? parseCursorModelCatalog(output.output) : undefined,
+ };
}
async openLane(ctx: AdapterLaunchContext, options?: RuntimeLaneOpenOptions): Promise<RuntimeLane> {
diff --git a/src/daemon/agent-driver/src/adapters/opencode/index.test.ts b/src/daemon/agent-driver/src/adapters/opencode/index.test.ts
index bcce85eca..0987e9640 100644
--- a/src/daemon/agent-driver/src/adapters/opencode/index.test.ts
+++ b/src/daemon/agent-driver/src/adapters/opencode/index.test.ts
@@ -26,6 +26,30 @@ describe("OpenCodeDriver persistent v2 service", () => {
driver = new OpenCodeDriver();
});
+ it("uses models --pure output for a non-fatal startup catalog", () => {
+ const outputProbe = vi.fn(() => ({
+ ok: true as const,
+ output: "openai/gpt-5\nanthropic/claude-sonnet\n",
+ }));
+ const result = new OpenCodeDriver(outputProbe).probe(process.execPath);
+
+ expect(outputProbe).toHaveBeenCalledWith(process.execPath, ["models", "--pure"]);
+ expect(result).toMatchObject({
+ status: "healthy",
+ reasoning: {
+ models: [
+ { id: "openai/gpt-5", supportedReasoningEfforts: [] },
+ { id: "anthropic/claude-sonnet", supportedReasoningEfforts: [] },
+ ],
+ },
+ });
+ });
+
+ it("keeps runtime health healthy when models --pure fails", () => {
+ expect(new OpenCodeDriver(() => ({ ok: false, error: "ETIMEDOUT" })).probe(process.execPath))
+ .toMatchObject({ status: "healthy", reasoning: undefined });
+ });
+
it("declares persistent HTTP/SSE steering with transport-owned terminal receipts", () => {
expect(driver.execution).toEqual({
lifetime: "session",
diff --git a/src/daemon/agent-driver/src/adapters/opencode/index.ts b/src/daemon/agent-driver/src/adapters/opencode/index.ts
index 87fd93c8d..b9b310429 100644
--- a/src/daemon/agent-driver/src/adapters/opencode/index.ts
+++ b/src/daemon/agent-driver/src/adapters/opencode/index.ts
@@ -16,7 +16,13 @@ import type {
import { prepareCliTransport } from "../../internal/cliTransport.js";
import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";
import { spawnAgentProcess } from "../../internal/killTree.js";
-import { probeCliRuntime, resolveSpawnSpec } from "../../internal/probe.js";
+import {
+ probeCliRuntime,
+ probeCommandOutput,
+ resolveSpawnSpec,
+ type CommandOutputProbeResult,
+} from "../../internal/probe.js";
+import { parseOpenCodeModelCatalog } from "../../internal/modelCatalog.js";
import {
OpenCodeServiceLane,
type OpenCodeServiceProcessFactory,
@@ -36,8 +42,19 @@ export class OpenCodeDriver implements BackendAdapter, OpenCodeServiceProcessFac
terminalOwnership: "transport_request",
} as const;
+ constructor(
+ private readonly outputProbe: (command: string, args: string[]) => CommandOutputProbeResult = probeCommandOutput,
+ ) {}
+
probe(command?: string) {
- return probeCliRuntime("opencode", {}, command);
+ const result = probeCliRuntime("opencode", {}, command);
+ if (result.status !== "healthy") return result;
+ const spec = resolveSpawnSpec("opencode", ["models", "--pure"], command);
+ const output = this.outputProbe(spec.command, spec.args);
+ return {
+ ...result,
+ reasoning: output.ok ? parseOpenCodeModelCatalog(output.output) : undefined,
+ };
}
beginTurn(): string {
diff --git a/src/daemon/agent-driver/src/adapters/pi/index.test.ts b/src/daemon/agent-driver/src/adapters/pi/index.test.ts
index 1a2ed62f6..c23bd20fd 100644
--- a/src/daemon/agent-driver/src/adapters/pi/index.test.ts
+++ b/src/daemon/agent-driver/src/adapters/pi/index.test.ts
@@ -17,6 +17,7 @@ import { createFakeAgentDriverHost } from "../../testing/fake-host.js";
import type { BuiltinBackendSpecs } from "../../contract.js";
import type { AdapterLaunchContext } from "../../internal/adapter.js";
import { fakeLaunchContext } from "../../testing/adapter-fixture.js";
+import type { PiSdkModule } from "./sessionDeps.js";
let tmpDir: string;
@@ -49,6 +50,64 @@ function fakeDeps() {
return { buildSpawnEnv, createAgentSession, session };
}
+describe("PiDriver startup model catalog", () => {
+ function loader(getAvailable: () => unknown[] | Promise<unknown[]>): () => Promise<PiSdkModule> {
+ return async () => ({
+ AuthStorage: { create: () => ({ setRuntimeApiKey: vi.fn() }) },
+ ModelRegistry: { create: () => ({ find: vi.fn(), getAvailable }) },
+ }) as unknown as PiSdkModule;
+ }
+
+ it("uses authenticated ModelRegistry.getAvailable and formats provider/id", async () => {
+ const getAvailable = vi.fn(() => [
+ { provider: "google", id: "gemini-2.5-pro" },
+ { provider: "openai", id: "gpt-5" },
+ ]);
+ const result = await new PiDriver(undefined, loader(getAvailable), () => "1.2.3").probe();
+
+ expect(getAvailable).toHaveBeenCalledOnce();
+ expect(result).toMatchObject({
+ status: "healthy",
+ version: "1.2.3",
+ reasoning: {
+ models: [
+ { id: "google/gemini-2.5-pro", supportedReasoningEfforts: [] },
+ { id: "openai/gpt-5", supportedReasoningEfforts: [] },
+ ],
+ },
+ });
+ });
+
+ it("keeps runtime health healthy when SDK catalog discovery fails", async () => {
+ const result = await new PiDriver(
+ undefined,
+ async () => { throw new Error("catalog failed"); },
+ () => "1.2.3",
+ ).probe();
+ expect(result).toEqual({ status: "healthy", version: "1.2.3", reasoning: undefined });
+ });
+
+ it("keeps runtime health healthy when SDK catalog discovery times out", async () => {
+ vi.useFakeTimers();
+ try {
+ const result = new PiDriver(
+ undefined,
+ () => new Promise<PiSdkModule>(() => {}),
+ () => "1.2.3",
+ ).probe();
+
+ await vi.advanceTimersByTimeAsync(5_000);
+ await expect(result).resolves.toEqual({
+ status: "healthy",
+ version: "1.2.3",
+ reasoning: undefined,
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
describe("PiDriver.openLane — AGENTS.md packing", () => {
it("maps SDK retry lifecycle into bounded recovery activity", () => {
expect(mapPiSdkEvent({ type: "auto_retry_start" }, "sess_1", { sawTextDelta: false }))
diff --git a/src/daemon/agent-driver/src/adapters/pi/index.ts b/src/daemon/agent-driver/src/adapters/pi/index.ts
index 4ef50deea..5457e47b4 100644
--- a/src/daemon/agent-driver/src/adapters/pi/index.ts
+++ b/src/daemon/agent-driver/src/adapters/pi/index.ts
@@ -9,9 +9,16 @@ import type {
import { SdkLane } from "../../controller/sdk-host.js";
import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";
import { resolveCommandOnPath, type ProbeDeps } from "../../internal/probe.js";
-import { createPiSessionDependencies, type PiSessionDependencies } from "./sessionDeps.js";
+import { parsePiModelCatalog } from "../../internal/modelCatalog.js";
+import {
+ createPiSessionDependencies,
+ loadPiSdkModule,
+ type PiSdkLoader,
+ type PiSessionDependencies,
+} from "./sessionDeps.js";
const PI_SDK_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
+const PI_MODEL_PROBE_TIMEOUT_MS = 5_000;
interface PiSdkAgentSession {
prompt(text: string, options?: { streamingBehavior?: "steer" | "followUp" }): Promise<void>;
@@ -209,17 +216,37 @@ export class PiDriver implements BackendAdapter {
constructor(
private readonly dependenciesFor: (ctx: AdapterLaunchContext) => PiSessionDependencies = createPiSessionDependencies,
+ private readonly loadSdk: PiSdkLoader = loadPiSdkModule,
+ private readonly readVersion: () => string | undefined = readPiSdkVersion,
) {}
- probe() {
- const version = readPiSdkVersion();
+ async probe() {
+ const version = this.readVersion();
if (!version) {
// The Pi SDK is a native runtime — no CLI to spawn. If the npm module
// isn't require-able, treat the runtime as unhealthy so /community
// reflects reality and the bot picker filters it out.
return { status: "unhealthy" as const, lastError: "sdk_not_installed" };
}
- return { status: "healthy" as const, version };
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ const reasoning = await Promise.race([
+ this.loadSdk().then(async (sdk) => {
+ const authStorage = sdk.AuthStorage.create();
+ const registry = sdk.ModelRegistry.create(authStorage);
+ return parsePiModelCatalog(await registry.getAvailable());
+ }),
+ new Promise<undefined>((resolve) => {
+ timer = setTimeout(() => resolve(undefined), PI_MODEL_PROBE_TIMEOUT_MS);
+ timer.unref?.();
+ }),
+ ]);
+ return { status: "healthy" as const, version, reasoning };
+ } catch {
+ return { status: "healthy" as const, version, reasoning: undefined };
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
}
/**
diff --git a/src/daemon/agent-driver/src/adapters/pi/sessionDeps.test.ts b/src/daemon/agent-driver/src/adapters/pi/sessionDeps.test.ts
index 8a283376a..0c049e21e 100644
--- a/src/daemon/agent-driver/src/adapters/pi/sessionDeps.test.ts
+++ b/src/daemon/agent-driver/src/adapters/pi/sessionDeps.test.ts
@@ -70,7 +70,7 @@ function fakeSdk(opts: {
const sdk: PiSdkModule = {
AuthStorage: { create: () => ({ setRuntimeApiKey }) },
- ModelRegistry: { create: () => ({ find: findModel }) },
+ ModelRegistry: { create: () => ({ find: findModel, getAvailable: () => [] }) },
SessionManager: {
create: sessionManagerCreate,
open: sessionManagerOpen,
diff --git a/src/daemon/agent-driver/src/adapters/pi/sessionDeps.ts b/src/daemon/agent-driver/src/adapters/pi/sessionDeps.ts
index edba40673..bc6998706 100644
--- a/src/daemon/agent-driver/src/adapters/pi/sessionDeps.ts
+++ b/src/daemon/agent-driver/src/adapters/pi/sessionDeps.ts
@@ -42,6 +42,7 @@ export interface PiAuthStorage {
}
export interface PiModelRegistry {
find(provider: string, modelId: string): unknown | undefined;
+ getAvailable(): unknown[] | Promise<unknown[]>;
}
interface PiBashSpawnContext {
command: string;
diff --git a/src/daemon/agent-driver/src/internal/config.test.ts b/src/daemon/agent-driver/src/internal/config.test.ts
index c170cc10d..d6ed789bf 100644
--- a/src/daemon/agent-driver/src/internal/config.test.ts
+++ b/src/daemon/agent-driver/src/internal/config.test.ts
@@ -21,6 +21,24 @@ describe("resolveLaunchFieldsOrDefault", () => {
});
});
+ it("sets the Claude custom-endpoint model option for a named model", () => {
+ expect(resolveLaunchFieldsOrDefault({
+ model: { kind: "named", name: "sonnet" },
+ provider: { kind: "custom_endpoint", apiUrl: "https://example.invalid", apiKey: "secret" },
+ }).providerEnv).toEqual({
+ ANTHROPIC_CUSTOM_MODEL_OPTION: "sonnet",
+ ANTHROPIC_BASE_URL: "https://example.invalid",
+ ANTHROPIC_API_KEY: "secret",
+ });
+ });
+
+ it.each(["opus", "sonnet", "haiku"])("passes the Claude %s alias to launch verbatim", (alias) => {
+ expect(resolveLaunchFieldsOrDefault({
+ model: { kind: "named", name: alias },
+ provider: { kind: "default" },
+ })).toMatchObject({ model: alias, providerEnv: {} });
+ });
+
it("maps known Pi providers and ignores unknown provider ids", () => {
expect(resolveLaunchFieldsOrDefault({
model: { kind: "default" },
diff --git a/src/daemon/agent-driver/src/internal/config.ts b/src/daemon/agent-driver/src/internal/config.ts
index 572794520..0ff0b6b9c 100644
--- a/src/daemon/agent-driver/src/internal/config.ts
+++ b/src/daemon/agent-driver/src/internal/config.ts
@@ -48,8 +48,8 @@ export function resolveLaunchFieldsOrDefault(
);
const providerEnv: Record<string, string> = {};
const model = normalized.model.kind === "default" ? undefined : normalized.model.name;
- if (normalized.model.kind === "custom" && normalized.provider?.kind === "custom_endpoint") {
- providerEnv.ANTHROPIC_CUSTOM_MODEL_OPTION = normalized.model.name;
+ if (model && normalized.provider?.kind === "custom_endpoint") {
+ providerEnv.ANTHROPIC_CUSTOM_MODEL_OPTION = model;
}
if (normalized.provider?.kind === "custom_endpoint") {
providerEnv.ANTHROPIC_BASE_URL = normalized.provider.apiUrl;
diff --git a/src/daemon/agent-driver/src/internal/modelCatalog.test.ts b/src/daemon/agent-driver/src/internal/modelCatalog.test.ts
new file mode 100644
index 000000000..1a95e3d20
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/modelCatalog.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from "vitest";
+import {
+ parseCursorModelCatalog,
+ parseOpenCodeModelCatalog,
+ parsePiModelCatalog,
+ RUNTIME_MODEL_CATALOG_MAX,
+} from "./modelCatalog.js";
+
+function ids(catalog: ReturnType<typeof parseCursorModelCatalog>): string[] | undefined {
+ return catalog?.models.map((model) => model.id);
+}
+
+describe("runtime startup model catalog parsers", () => {
+ it("parses Cursor id-label rows and ignores headers, tips, malformed rows, and duplicates", () => {
+ expect(ids(parseCursorModelCatalog([
+ "Available models",
+ "",
+ "gpt-5.6-sol - GPT 5.6 Sol",
+ "not a model row",
+ "gpt-5.6-sol - duplicate",
+ "claude-4.6-opus - Claude Opus",
+ "Tip: choose with --model",
+ ].join("\n")))).toEqual(["gpt-5.6-sol", "claude-4.6-opus"]);
+ });
+
+ it("parses only OpenCode provider/model rows and deduplicates them", () => {
+ expect(ids(parseOpenCodeModelCatalog([
+ "openai/gpt-5",
+ "anthropic/claude-sonnet",
+ "openai/gpt-5",
+ "header without slash",
+ "bad provider/model with spaces",
+ ].join("\n")))).toEqual(["openai/gpt-5", "anthropic/claude-sonnet"]);
+ });
+
+ it("formats only valid Pi getAvailable entries as provider/id", () => {
+ expect(ids(parsePiModelCatalog([
+ { provider: "google", id: "gemini-2.5-pro" },
+ { provider: "openai", id: "gpt-5" },
+ { provider: "openai", id: "gpt-5" },
+ { provider: "bad/provider", id: "model" },
+ { provider: "missing-id" },
+ ]))).toEqual(["google/gemini-2.5-pro", "openai/gpt-5"]);
+ });
+
+ it("returns no catalog for empty or wholly malformed producer output", () => {
+ expect(parseCursorModelCatalog("Available models\nTip: log in")).toBeUndefined();
+ expect(parseOpenCodeModelCatalog("not a model\n")).toBeUndefined();
+ expect(parsePiModelCatalog([{ nope: true }])).toBeUndefined();
+ });
+
+ it("returns no catalog instead of truncating when unique IDs overflow the bound", () => {
+ const cursor = Array.from(
+ { length: RUNTIME_MODEL_CATALOG_MAX + 1 },
+ (_, index) => `model-${index} - Model ${index}`,
+ ).join("\n");
+ const opencode = Array.from(
+ { length: RUNTIME_MODEL_CATALOG_MAX + 1 },
+ (_, index) => `provider/model-${index}`,
+ ).join("\n");
+ const pi = Array.from(
+ { length: RUNTIME_MODEL_CATALOG_MAX + 1 },
+ (_, index) => ({ provider: "provider", id: `model-${index}` }),
+ );
+
+ expect(parseCursorModelCatalog(cursor)).toBeUndefined();
+ expect(parseOpenCodeModelCatalog(opencode)).toBeUndefined();
+ expect(parsePiModelCatalog(pi)).toBeUndefined();
+ });
+});
diff --git a/src/daemon/agent-driver/src/internal/modelCatalog.ts b/src/daemon/agent-driver/src/internal/modelCatalog.ts
new file mode 100644
index 000000000..5b925d612
--- /dev/null
+++ b/src/daemon/agent-driver/src/internal/modelCatalog.ts
@@ -0,0 +1,56 @@
+import type { RuntimeReasoningCatalog } from "../contract.js";
+
+export const RUNTIME_MODEL_CATALOG_MAX = 512;
+const RUNTIME_MODEL_ID_MAX = 100;
+
+export function normalizeRuntimeModelId(value: unknown): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const id = value.trim();
+ if (!id || id.length > RUNTIME_MODEL_ID_MAX || /\s/.test(id)) return undefined;
+ return id;
+}
+
+function catalogFromIds(ids: Iterable<string>): RuntimeReasoningCatalog | undefined {
+ const seen = new Set<string>();
+ const models: RuntimeReasoningCatalog["models"][number][] = [];
+ for (const rawId of ids) {
+ const id = normalizeRuntimeModelId(rawId);
+ if (!id || seen.has(id)) continue;
+ if (models.length >= RUNTIME_MODEL_CATALOG_MAX) return undefined;
+ seen.add(id);
+ models.push({ id, supportedReasoningEfforts: [] });
+ }
+ if (models.length === 0) return undefined;
+ return { updateMode: "unsupported", models };
+}
+
+/** Parse Cursor's `id - label` rows while ignoring headers and footer hints. */
+export function parseCursorModelCatalog(output: string): RuntimeReasoningCatalog | undefined {
+ const ids = output.split(/\r?\n/).flatMap((line) => {
+ const match = line.trim().match(/^(\S+)\s+-\s+\S.*$/);
+ return match?.[1] ? [match[1]] : [];
+ });
+ return catalogFromIds(ids);
+}
+
+/** Parse OpenCode's `--pure` output: exactly one `provider/model` id per row. */
+export function parseOpenCodeModelCatalog(output: string): RuntimeReasoningCatalog | undefined {
+ const ids = output.split(/\r?\n/).flatMap((line) => {
+ const id = normalizeRuntimeModelId(line);
+ return id && /^[^/]+\/.+$/.test(id) ? [id] : [];
+ });
+ return catalogFromIds(ids);
+}
+
+/** Format Pi SDK `ModelRegistry.getAvailable()` entries as canonical provider/id ids. */
+export function parsePiModelCatalog(values: unknown): RuntimeReasoningCatalog | undefined {
+ if (!Array.isArray(values)) return undefined;
+ const ids = values.flatMap((value) => {
+ if (!value || typeof value !== "object") return [];
+ const model = value as Record<string, unknown>;
+ const provider = normalizeRuntimeModelId(model.provider);
+ const id = normalizeRuntimeModelId(model.id);
+ return provider && id && !provider.includes("/") ? [`${provider}/${id}`] : [];
+ });
+ return catalogFromIds(ids);
+}
diff --git a/src/daemon/agent-driver/src/internal/probe.test.ts b/src/daemon/agent-driver/src/internal/probe.test.ts
index d296cc817..1cf3cc289 100644
--- a/src/daemon/agent-driver/src/internal/probe.test.ts
+++ b/src/daemon/agent-driver/src/internal/probe.test.ts
@@ -3,7 +3,13 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, it, expect, vi } from "vitest";
import { execFileSync } from "child_process";
-import { resolveClaudeCommand, resolveSpawnSpec, probeCliRuntime, probeCommandVersion } from "./probe.js";
+import {
+ resolveClaudeCommand,
+ resolveSpawnSpec,
+ probeCliRuntime,
+ probeCommandOutput,
+ probeCommandVersion,
+} from "./probe.js";
vi.mock("child_process", () => ({ execFileSync: vi.fn() }));
@@ -221,3 +227,39 @@ describe("probeCliRuntime command override", () => {
);
});
});
+
+describe("probeCommandOutput", () => {
+ it("runs the exact command and args with bounded, non-interactive options", () => {
+ vi.mocked(execFileSync).mockReturnValue("provider/model\n");
+
+ expect(probeCommandOutput("/custom/opencode", ["models", "--pure"], "darwin"))
+ .toEqual({ ok: true, output: "provider/model\n" });
+ expect(execFileSync).toHaveBeenCalledWith(
+ "/custom/opencode",
+ ["models", "--pure"],
+ expect.objectContaining({
+ timeout: 5000,
+ maxBuffer: 1024 * 1024,
+ input: "",
+ shell: false,
+ env: expect.objectContaining({ CI: "1" }),
+ }),
+ );
+ });
+
+ it("uses a shell for Windows shims and converts failures to a non-throwing result", () => {
+ vi.mocked(execFileSync).mockImplementation(() => {
+ const error = new Error("timed out") as NodeJS.ErrnoException;
+ error.code = "ETIMEDOUT";
+ throw error;
+ });
+
+ expect(probeCommandOutput("C:\\tools\\cursor-agent.cmd", ["--list-models"], "win32"))
+ .toEqual({ ok: false, error: "ETIMEDOUT" });
+ expect(execFileSync).toHaveBeenCalledWith(
+ "C:\\tools\\cursor-agent.cmd",
+ ["--list-models"],
+ expect.objectContaining({ shell: true }),
+ );
+ });
+});
diff --git a/src/daemon/agent-driver/src/internal/probe.ts b/src/daemon/agent-driver/src/internal/probe.ts
index 5182f520d..c2af1cb01 100644
--- a/src/daemon/agent-driver/src/internal/probe.ts
+++ b/src/daemon/agent-driver/src/internal/probe.ts
@@ -14,6 +14,7 @@ import type { ProbeResult } from "./adapter.js";
* every second here is a second of user-visible wait.
*/
const PROBE_TIMEOUT_MS = 5000;
+const PROBE_OUTPUT_MAX_BYTES = 1024 * 1024;
export interface ProbeDeps {
homeDir?: string;
@@ -52,6 +53,10 @@ type VersionProbeResult =
| { ok: true; version: string }
| { ok: false; error: string };
+export type CommandOutputProbeResult =
+ | { ok: true; output: string }
+ | { ok: false; error: string };
+
/**
* A `--version` line must look like a version to be accepted: it has to contain
* a digit-dotted token (e.g. `1.2.3`, `v0.4`, `2024.1`). This is the
@@ -129,6 +134,28 @@ export function probeCommandVersion(
}
}
+export function probeCommandOutput(
+ command: string,
+ args: string[],
+ platform: NodeJS.Platform = process.platform,
+): CommandOutputProbeResult {
+ try {
+ const output = execFileSync(command, args, {
+ encoding: "utf8",
+ timeout: PROBE_TIMEOUT_MS,
+ maxBuffer: PROBE_OUTPUT_MAX_BYTES,
+ shell: needsWindowsShimShell(command, platform),
+ stdio: ["pipe", "pipe", "ignore"],
+ input: "",
+ env: { ...process.env, CI: "1" },
+ });
+ return { ok: true, output };
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException | undefined)?.code ?? "command_probe_failed";
+ return { ok: false, error: String(code) };
+ }
+}
+
function resolveHomePath(relativePath: string, deps: ProbeDeps = {}): string {
return path.join(deps.homeDir || process.env.HOME || ".", relativePath);
}
diff --git a/src/daemon/src/discovery.test.ts b/src/daemon/src/discovery.test.ts
index 03d221272..986820b69 100644
--- a/src/daemon/src/discovery.test.ts
+++ b/src/daemon/src/discovery.test.ts
@@ -208,8 +208,9 @@ describe("detectRuntimes", () => {
defaultReasoningEffort: "minimal",
}],
};
+ const probe = vi.fn(async () => ({ status: "healthy" as const, version: "9.8.7", reasoning }));
vi.spyOn(drivers, "getDriver").mockReturnValue({
- probe: async () => ({ status: "healthy", version: "9.8.7", reasoning }),
+ probe,
} as never);
const result = await detectRuntimes();
@@ -220,6 +221,7 @@ describe("detectRuntimes", () => {
version: "9.8.7",
reasoning,
});
+ expect(probe).toHaveBeenCalledTimes(EXPECTED_RUNTIMES.length);
});
});
diff --git a/src/daemon/src/manager/agentRouter.test.ts b/src/daemon/src/manager/agentRouter.test.ts
index c69461dfa..ae5dbc66f 100644
--- a/src/daemon/src/manager/agentRouter.test.ts
+++ b/src/daemon/src/manager/agentRouter.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect } from "vitest";
+import { describe, it, expect, vi } from "vitest";
import { AgentRouter, UnknownRuntimeError, UnknownBotError } from "./agentRouter";
import type { AgentProcessManager } from "./managerRuntime";
import type { HostControlChannel, HostCommand, SessionErrorFrame } from "../server/contract";
@@ -637,6 +637,36 @@ describe("AgentRouter — buildReady runtimeReport", () => {
await router.start();
expect(readys[0]).toMatchObject({ runtimeReport: [{ id: "claude" }] });
});
+
+ it("keeps the one-shot startup catalog unchanged in unhealthy → healthy ready resends", () => {
+ const { mgr } = fakeManager();
+ const { ch, readyResends } = fakeChannelWithSendReady();
+ const reasoning = {
+ updateMode: "unsupported" as const,
+ models: [{ id: "machine-model", supportedReasoningEfforts: [] }],
+ };
+ const startupProbe = vi.fn(() => reasoning);
+ const router = new AgentRouter({
+ manager: mgr,
+ channel: ch,
+ runtimeReport: [{ id: "cursor", reasoning: startupProbe() }],
+ scheduleReadyResend: (send) => send(),
+ });
+
+ router.markRuntimeUnhealthy("cursor", "ENOENT");
+ expect(readyResends[0]?.runtimeReport[0]).toMatchObject({
+ id: "cursor",
+ status: "unhealthy",
+ reasoning,
+ });
+ router.markRuntimeHealthy("cursor");
+ expect(readyResends[1]?.runtimeReport[0]).toMatchObject({
+ id: "cursor",
+ status: "healthy",
+ reasoning,
+ });
+ expect(startupProbe).toHaveBeenCalledOnce();
+ });
});
// ---------------------------------------------------------------------------
diff --git a/src/daemon/src/manager/agentRouter.ts b/src/daemon/src/manager/agentRouter.ts
index d282ff211..1df63cd93 100644
--- a/src/daemon/src/manager/agentRouter.ts
+++ b/src/daemon/src/manager/agentRouter.ts
@@ -303,11 +303,10 @@ export class AgentRouter {
const existing = this.runtimes.get(id);
if (!existing) return;
if (existing.status === "healthy" && !existing.lastError && !existing.lastErrorAt) return;
- this.runtimes.set(id, {
- id: existing.id,
- version: existing.version,
- status: "healthy",
- });
+ const healthy = { ...existing, status: "healthy" as const };
+ delete healthy.lastError;
+ delete healthy.lastErrorAt;
+ this.runtimes.set(id, healthy);
this.log.info("runtime marked healthy again", { runtimeId: id });
this.scheduleReadyFrameResend();
}
diff --git a/src/daemon/src/server/wsControlChannel.test.ts b/src/daemon/src/server/wsControlChannel.test.ts
index d2df9d206..17f5d6c0f 100644
--- a/src/daemon/src/server/wsControlChannel.test.ts
+++ b/src/daemon/src/server/wsControlChannel.test.ts
@@ -73,9 +73,17 @@ function stubLogger(): Logger & { calls: Record<"debug" | "info" | "warn" | "err
describe("WsControlChannel — resync on (re)connect", () => {
it("re-announces ready + live sessions on the new socket after a reconnect", async () => {
const { ch, sockets } = makeChannel();
- const ready: HostReady = { runtimeReport: [{ id: "mock" }], runningAgents: ["a1"] };
+ const reasoning = {
+ updateMode: "unsupported" as const,
+ models: [{ id: "startup-model", supportedReasoningEfforts: [] }],
+ };
+ const ready: HostReady = {
+ runtimeReport: [{ id: "mock", reasoning }],
+ runningAgents: ["a1"],
+ };
const sessions: AgentSessionReport[] = [{ agentId: "a1", sessionId: "s1", launchId: "l1" }];
- ch.onResync(() => ({ ready, sessions, activities: [] }));
+ const resync = vi.fn(() => ({ ready, sessions, activities: [] }));
+ ch.onResync(resync);
ch.connect();
sockets[0].emit("open");
@@ -83,6 +91,7 @@ describe("WsControlChannel — resync on (re)connect", () => {
// so the shape matches HostReadyMessageSchema in @alook/shared.
let f = sockets[0].frames();
expect(f[0]).toMatchObject({ type: "ready", runningAgents: ["a1"] });
+ expect(f[0].runtimeReport[0].reasoning).toEqual(reasoning);
expect(f[1]).toMatchObject({ type: "agent_session", agentId: "a1", sessionId: "s1" });
// Drop the socket → channel schedules a reconnect → new socket created.
@@ -93,8 +102,9 @@ describe("WsControlChannel — resync on (re)connect", () => {
// The NEW socket must carry a fresh ready + session (state recovered).
f = sockets[1].frames();
- expect(f.some((x) => x.type === "ready")).toBe(true);
+ expect(f.find((x) => x.type === "ready")?.runtimeReport[0].reasoning).toEqual(reasoning);
expect(f.some((x) => x.type === "agent_session" && x.agentId === "a1")).toBe(true);
+ expect(resync).toHaveBeenCalledTimes(2);
});
it("2a — replays each live agent's current activity on (re)connect, recovering a frame dropped mid-disconnect", async () => {
@@ -295,7 +305,14 @@ describe("WsControlChannel — ready frame", () => {
it("round-trips runtimeReport on the ready frame", async () => {
const { ch, sockets } = makeChannel();
const ready: HostReady = {
- runtimeReport: [{ id: "claude", version: "1.0.0" }],
+ runtimeReport: [{
+ id: "claude",
+ version: "1.0.0",
+ reasoning: {
+ updateMode: "unsupported",
+ models: [{ id: "opus", supportedReasoningEfforts: [] }],
+ },
+ }],
runningAgents: [],
};
ch.onResync(() => ({ ready, sessions: [], activities: [] }));
@@ -304,7 +321,14 @@ describe("WsControlChannel — ready frame", () => {
const frames = sockets[0].frames();
expect(frames[0]).toMatchObject({
type: "ready",
- runtimeReport: [{ id: "claude", version: "1.0.0" }],
+ runtimeReport: [{
+ id: "claude",
+ version: "1.0.0",
+ reasoning: {
+ updateMode: "unsupported",
+ models: [{ id: "opus", supportedReasoningEfforts: [] }],
+ },
+ }],
});
});
});
diff --git a/src/shared/src/community/bot-model.test.ts b/src/shared/src/community/bot-model.test.ts
index 73ec455be..bc4bea99e 100644
--- a/src/shared/src/community/bot-model.test.ts
+++ b/src/shared/src/community/bot-model.test.ts
@@ -11,27 +11,16 @@ import {
describe("resolveModelConfig", () => {
it("treats null, empty, and whitespace-only as default", () => {
for (const v of [null, "", " "]) {
- expect(resolveModelConfig("claude", v)).toEqual({ kind: "default" });
+ expect(resolveModelConfig(v)).toEqual({ kind: "default" });
}
});
- it("resolves a catalog id to named and a non-catalog id to custom", () => {
- expect(resolveModelConfig("claude", "claude-opus-4-6")).toEqual({
+ it("resolves every non-empty stored model as launchable named config", () => {
+ expect(resolveModelConfig("opus")).toEqual({
kind: "named",
- name: "claude-opus-4-6",
+ name: "opus",
});
- expect(resolveModelConfig("claude", "my-ft")).toEqual({ kind: "custom", name: "my-ft" });
- // Empty catalog ⇒ always custom.
- expect(resolveModelConfig("cursor", "anything")).toEqual({ kind: "custom", name: "anything" });
- // Null runtime ⇒ fallback empty catalog ⇒ custom.
- expect(resolveModelConfig(null, "x")).toEqual({ kind: "custom", name: "x" });
- });
-
- it("a model added to the catalog later resolves custom → named with no stored change (derive-at-read)", () => {
- // Same stored string; membership decides the kind. Simulate a not-yet-catalogued
- // id (custom) vs a catalogued id (named) without mutating storage.
- expect(resolveModelConfig("codex", "gpt-6-future")).toEqual({ kind: "custom", name: "gpt-6-future" });
- expect(resolveModelConfig("codex", "gpt-5.4")).toEqual({ kind: "named", name: "gpt-5.4" });
+ expect(resolveModelConfig("my-ft")).toEqual({ kind: "named", name: "my-ft" });
});
});
@@ -53,17 +42,17 @@ describe("formatModelLabel", () => {
describe("modelSelectState / modelNameFromSelect round-trip", () => {
it("round-trips default", () => {
- const s = modelSelectState("claude", null);
+ const s = modelSelectState(["opus", "sonnet", "haiku"], null);
expect(s).toEqual({ selectValue: MODEL_SELECT_DEFAULT, customName: "" });
expect(modelNameFromSelect(s.selectValue, s.customName)).toBeNull();
});
it("round-trips a catalog id", () => {
- const s = modelSelectState("claude", "claude-opus-4-6");
- expect(s).toEqual({ selectValue: "claude-opus-4-6", customName: "" });
- expect(modelNameFromSelect(s.selectValue, s.customName)).toBe("claude-opus-4-6");
+ const s = modelSelectState(["opus", "sonnet", "haiku"], "opus");
+ expect(s).toEqual({ selectValue: "opus", customName: "" });
+ expect(modelNameFromSelect(s.selectValue, s.customName)).toBe("opus");
});
it("round-trips a custom name", () => {
- const s = modelSelectState("claude", "my-ft");
+ const s = modelSelectState(["opus", "sonnet", "haiku"], "my-ft");
expect(s).toEqual({ selectValue: MODEL_SELECT_CUSTOM, customName: "my-ft" });
expect(modelNameFromSelect(s.selectValue, s.customName)).toBe("my-ft");
});
diff --git a/src/shared/src/community/bot-model.ts b/src/shared/src/community/bot-model.ts
index 05457c2d6..7a6559853 100644
--- a/src/shared/src/community/bot-model.ts
+++ b/src/shared/src/community/bot-model.ts
@@ -7,16 +7,12 @@
* two wake sites, two write routes, and the picker cannot drift on how a stored
* name maps to `{ kind }`.
*
- * The `kind` (`default` / `named` / `custom`) is DERIVED from catalog
- * membership at read time, never stored: a value in the runtime's catalog is
- * `named`, anything else is `custom`, `null`/empty is `default`. Deriving at
- * read time always reflects the CURRENT catalog — a model entering our catalog
- * means it's first-party and should shed the custom-model env var — which a
- * persisted kind could not do.
+ * Stored model names are advisory picker values, not a catalog gate. Every
+ * non-empty name is launchable as `named`; the UI's `Custom…` state only
+ * describes how an absent suggestion is edited.
*/
import type { ModelConfig } from "../runtime-config";
-import { getRuntimeModelCatalog } from "../constants/runtime-models";
/** Select sentinel for "Default (the runtime's own default)". */
export const MODEL_SELECT_DEFAULT = "__default__";
@@ -26,17 +22,13 @@ export const MODEL_SELECT_CUSTOM = "__custom__";
/**
* The ONLY place a `ModelConfig` is constructed from stored model-name state
* (outside `makeRuntimeConfig`'s own default). `null`, `""`, and
- * whitespace-only all mean the runtime's default. A catalog-member id resolves
- * to `named`; anything else to `custom`.
+ * whitespace-only all mean the runtime's default. Every other value resolves
+ * to `named`; catalog membership is only a picker-display concern.
*/
-export function resolveModelConfig(
- runtime: string | null,
- modelName: string | null
-): ModelConfig {
+export function resolveModelConfig(modelName: string | null): ModelConfig {
const name = (modelName ?? "").trim();
if (name.length === 0) return { kind: "default" };
- const inCatalog = getRuntimeModelCatalog(runtime).models.includes(name);
- return inCatalog ? { kind: "named", name } : { kind: "custom", name };
+ return { kind: "named", name };
}
/**
@@ -72,12 +64,12 @@ export function formatModelLabel(
* with the stored name in the text field.
*/
export function modelSelectState(
- runtime: string | null,
+ modelIds: readonly string[],
modelName: string | null
): { selectValue: string; customName: string } {
const name = (modelName ?? "").trim();
if (name.length === 0) return { selectValue: MODEL_SELECT_DEFAULT, customName: "" };
- const inCatalog = getRuntimeModelCatalog(runtime).models.includes(name);
+ const inCatalog = modelIds.includes(name);
if (inCatalog) return { selectValue: name, customName: "" };
return { selectValue: MODEL_SELECT_CUSTOM, customName: name };
}
diff --git a/src/shared/src/community/wake-dispatch.ts b/src/shared/src/community/wake-dispatch.ts
index 3517cb87c..8c4c7cae9 100644
--- a/src/shared/src/community/wake-dispatch.ts
+++ b/src/shared/src/community/wake-dispatch.ts
@@ -211,7 +211,7 @@ export async function buildUnreadWakeCommand(
};
const config = makeRuntimeConfig({
runtime: botCtx.runtime,
- model: resolveModelConfig(botCtx.runtime, botCtx.modelName),
+ model: resolveModelConfig(botCtx.modelName),
reasoningEffort: botCtx.reasoningEffort ?? undefined,
runtimeConfigRevision: botCtx.runtimeConfigRevision,
agentName: botCtx.name,
diff --git a/src/shared/src/constants/runtime-models.test.ts b/src/shared/src/constants/runtime-models.test.ts
deleted file mode 100644
index 6e1accbad..000000000
--- a/src/shared/src/constants/runtime-models.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { describe, it, expect } from "vitest";
-import {
- RUNTIME_MODEL_CATALOG,
- getRuntimeModelCatalog,
-} from "./runtime-models";
-
-const SEEDED_RUNTIMES = [
- "claude",
- "codex",
- "cursor",
- "opencode",
- "pi",
-];
-
-describe("getRuntimeModelCatalog", () => {
- it("returns the seeded entry for each of the 5 supported runtime ids", () => {
- for (const id of SEEDED_RUNTIMES) {
- expect(getRuntimeModelCatalog(id)).toBe(RUNTIME_MODEL_CATALOG[id]);
- }
- expect(getRuntimeModelCatalog("claude").models).toContain("claude-opus-4-6");
- expect(getRuntimeModelCatalog("codex").models).toContain("gpt-5.4");
- expect(getRuntimeModelCatalog("cursor").models).toEqual([]);
- });
-
- it("falls back to {models:[]} for an unknown id and null", () => {
- expect(getRuntimeModelCatalog("does-not-exist")).toEqual({ models: [] });
- expect(getRuntimeModelCatalog(null)).toEqual({ models: [] });
- });
-});
diff --git a/src/shared/src/constants/runtime-models.ts b/src/shared/src/constants/runtime-models.ts
deleted file mode 100644
index 1ce367ace..000000000
--- a/src/shared/src/constants/runtime-models.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * Runtime model catalog — a static, runtime-keyed suggestion list for the
- * per-bot model picker. This is the community-bot analogue of the legacy,
- * provider-keyed `RUNTIME_MODEL_OPTIONS` env var (wired only to `/w` agent
- * forms); it is keyed by RUNTIME id instead, seeded from what each daemon
- * driver actually does at launch today.
- *
- * The catalog SUGGESTS; it does not GATE. `named` vs `custom` is derived from
- * membership at read time (see `resolveModelConfig` in
- * `community/bot-model.ts`) — a value in `models` resolves to `named`,
- * anything else to `custom`. This preserves the distinction the daemon's
- * `resolveLaunchFields` needs (a `custom` model on `claude` additionally sets
- * `ANTHROPIC_CUSTOM_MODEL_OPTION`) without hard-rejecting a model the vendor
- * shipped after our last deploy — and, unlike a persisted kind, it stays
- * correct when the catalog grows.
- */
-
-export interface RuntimeModelCatalogEntry {
- /** Known-good ids for the picker. Empty ⇒ Default + free text only. */
- readonly models: readonly string[];
-}
-
-/**
- * Seeded from what each driver does today. `claude`/`codex` mirror the ids
- * already in `RUNTIME_MODEL_OPTIONS`; runtimes with no curated list get
- * `{ models: [] }` (Default + free text).
- */
-export const RUNTIME_MODEL_CATALOG: Record<string, RuntimeModelCatalogEntry> = {
- claude: {
- models: ["claude-opus-4-6", "claude-sonnet-4-6", "claude-haiku-4-5"],
- },
- codex: {
- models: ["gpt-5.4", "gpt-5.3-codex"],
- },
- cursor: { models: [] },
- opencode: { models: [] },
- pi: { models: [] },
-};
-
-/** Fallback for unknown/`null` runtime ids — a usable free-text field. */
-const FALLBACK_ENTRY: RuntimeModelCatalogEntry = { models: [] };
-
-/**
- * Catalog entry for a runtime id. Unknown or `null` runtimes fall back to
- * `{ models: [] }` so a runtime added to the daemon before the catalog still
- * gets a usable free-text field.
- */
-export function getRuntimeModelCatalog(runtime: string | null): RuntimeModelCatalogEntry {
- if (runtime === null) return FALLBACK_ENTRY;
- return RUNTIME_MODEL_CATALOG[runtime] ?? FALLBACK_ENTRY;
-}
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index b665306a8..90726c172 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -504,11 +504,6 @@ export type {
} from "./runtime-config";
export { RUNTIME_CONFIG_VERSION, KNOWN_REASONING_EFFORTS, makeRuntimeConfig } from "./runtime-config";
-export type { RuntimeModelCatalogEntry } from "./constants/runtime-models";
-export {
- RUNTIME_MODEL_CATALOG,
- getRuntimeModelCatalog,
-} from "./constants/runtime-models";
export type {
RuntimeReasoningDescriptor,
ReasoningEffortResolution,
diff --git a/src/shared/src/runtime-config.ts b/src/shared/src/runtime-config.ts
index 7358edf71..7621e5537 100644
--- a/src/shared/src/runtime-config.ts
+++ b/src/shared/src/runtime-config.ts
@@ -39,6 +39,11 @@ export type ReasoningEffortOption = {
description?: string;
};
+/**
+ * Machine/runtime-scoped startup catalog. The historical `reasoning` wire
+ * field jointly carries model IDs and any model-specific reasoning metadata;
+ * models with no effort metadata use an empty options array.
+ */
export type RuntimeReasoningCatalog = {
readonly updateMode: "live_next_turn" | "context_preserving_restart" | "unsupported";
readonly defaultModelId?: string;
@@ -52,8 +57,8 @@ export type RuntimeReasoningCatalog = {
/** Model selection — structured, not a bare string. */
export type ModelConfig =
| { kind: "default" } // use the runtime's default model
- | { kind: "named"; name: string } // a specific catalog model
- | { kind: "custom"; name: string }; // a custom/BYO model id
+ | { kind: "named"; name: string } // any explicit launchable model name
+ | { kind: "custom"; name: string }; // legacy-compatible custom/BYO shape
/**
* Provider / endpoint selection — distinct from model. Lets a host point a
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 117b81546..e4aecb867 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -837,7 +837,7 @@ const REASONING_EFFORT_RE = /^[A-Za-z0-9._-]+$/;
export const COMMUNITY_REASONING_EFFORT_MAX = 32;
export const COMMUNITY_REASONING_DESCRIPTION_MAX = 256;
export const COMMUNITY_REASONING_OPTIONS_MAX = 16;
-export const COMMUNITY_REASONING_MODELS_MAX = 64;
+export const COMMUNITY_REASONING_MODELS_MAX = 512;
export const ReasoningEffortSchema = z
.string()
diff --git a/src/shared/test/community/wake-dispatch-build.test.ts b/src/shared/test/community/wake-dispatch-build.test.ts
index 5f8afb921..9ccf9d4c4 100644
--- a/src/shared/test/community/wake-dispatch-build.test.ts
+++ b/src/shared/test/community/wake-dispatch-build.test.ts
@@ -220,18 +220,17 @@ describe("buildUnreadWakeCommand", () => {
expect(result.command.unreadNotice.channel).toBe("/srv_1/general/#3");
});
- it("ready: config.model reflects the binding's model_name (named / custom / default)", async () => {
- // Catalog id ⇒ named.
+ it("ready: config.model maps every non-empty binding model to named and null to default", async () => {
seedHappyPath({ bot: { modelName: "claude-opus-4-6" } });
let result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });
if (result.state !== "ready" || result.command.type !== "agent:wake") throw new Error("expected ready wake");
expect(result.command.config.model).toEqual({ kind: "named", name: "claude-opus-4-6" });
- // Non-catalog id ⇒ custom.
+ // Catalog absence is advisory; manual model names remain normally launchable.
seedHappyPath({ bot: { modelName: "my-ft-model" } });
result = await buildUnreadWakeCommand(fakeDb, { messageId: "msg_1", botUserId: "bot_1" });
if (result.state !== "ready" || result.command.type !== "agent:wake") throw new Error("expected ready wake");
- expect(result.command.config.model).toEqual({ kind: "custom", name: "my-ft-model" });
+ expect(result.command.config.model).toEqual({ kind: "named", name: "my-ft-model" });
// NULL ⇒ default.
seedHappyPath({ bot: { modelName: null } });
diff --git a/src/shared/test/schemas/community-runtime.test.ts b/src/shared/test/schemas/community-runtime.test.ts
index ae035ac2d..ab7af4464 100644
--- a/src/shared/test/schemas/community-runtime.test.ts
+++ b/src/shared/test/schemas/community-runtime.test.ts
@@ -8,6 +8,7 @@ import {
SessionErrorFrameSchema,
COMMUNITY_RUNTIME_ID_MAX,
COMMUNITY_RUNTIME_LIST_MAX,
+ COMMUNITY_REASONING_MODELS_MAX,
} from "../../src/schemas";
describe("CommunityMachineRuntimeSchema", () => {
@@ -144,6 +145,28 @@ describe("CommunityMachineRuntimeSchema", () => {
reasoning: { updateMode: "eventually", models: [] },
})).toEqual({ id: "codex", status: "healthy" });
});
+
+ it("accepts the full 512-model startup snapshot", () => {
+ const models = Array.from({ length: COMMUNITY_REASONING_MODELS_MAX }, (_, index) => ({
+ id: `provider/model-${index}`,
+ supportedReasoningEfforts: [],
+ }));
+ expect(CommunityMachineRuntimeSchema.parse({
+ id: "opencode",
+ reasoning: { updateMode: "unsupported", models },
+ }).reasoning?.models).toHaveLength(COMMUNITY_REASONING_MODELS_MAX);
+ });
+
+ it("drops only an overflowing optional catalog and keeps the runtime", () => {
+ const models = Array.from({ length: COMMUNITY_REASONING_MODELS_MAX + 1 }, (_, index) => ({
+ id: `provider/model-${index}`,
+ supportedReasoningEfforts: [],
+ }));
+ expect(CommunityMachineRuntimeSchema.parse({
+ id: "opencode",
+ reasoning: { updateMode: "unsupported", models },
+ })).toEqual({ id: "opencode", status: "healthy" });
+ });
});
describe("CommunityMachineRuntimeListSchema", () => {
diff --git a/src/web/src/app/api/community/bots/[id]/reset-session/route.ts b/src/web/src/app/api/community/bots/[id]/reset-session/route.ts
index f28e06a3e..da70c2319 100644
--- a/src/web/src/app/api/community/bots/[id]/reset-session/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/reset-session/route.ts
@@ -31,7 +31,7 @@ export const POST = withAuth(async (_req, ctx) => {
const config = makeRuntimeConfig({
runtime: wakeCtx.runtime,
- model: resolveModelConfig(wakeCtx.runtime, wakeCtx.modelName),
+ model: resolveModelConfig(wakeCtx.modelName),
reasoningEffort: wakeCtx.reasoningEffort ?? undefined,
runtimeConfigRevision: wakeCtx.runtimeConfigRevision,
agentName: wakeCtx.name,
diff --git a/src/web/src/app/api/community/bots/[id]/route.ts b/src/web/src/app/api/community/bots/[id]/route.ts
index 5e7eec4eb..e5d4f3f11 100644
--- a/src/web/src/app/api/community/bots/[id]/route.ts
+++ b/src/web/src/app/api/community/bots/[id]/route.ts
@@ -182,7 +182,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
runtimeConfigRevision = wrote.runtimeConfigRevision
const config = makeRuntimeConfig({
runtime: targetRuntime,
- model: resolveModelConfig(targetRuntime, storedModel),
+ model: resolveModelConfig(storedModel),
reasoningEffort: storedEffort ?? undefined,
runtimeConfigRevision,
agentName: updated.name,
@@ -270,7 +270,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
agentId: id,
config: makeRuntimeConfig({
runtime: targetRuntime,
- model: resolveModelConfig(targetRuntime, storedModel),
+ model: resolveModelConfig(storedModel),
reasoningEffort: storedEffort ?? undefined,
runtimeConfigRevision,
agentName: updated.name,
diff --git a/src/web/src/app/api/community/bots/me/nap/route.ts b/src/web/src/app/api/community/bots/me/nap/route.ts
index 71452b7a1..02db36406 100644
--- a/src/web/src/app/api/community/bots/me/nap/route.ts
+++ b/src/web/src/app/api/community/bots/me/nap/route.ts
@@ -72,7 +72,7 @@ export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
const config = makeRuntimeConfig({
runtime: wakeCtx.runtime,
- model: resolveModelConfig(wakeCtx.runtime, wakeCtx.modelName),
+ model: resolveModelConfig(wakeCtx.modelName),
reasoningEffort: wakeCtx.reasoningEffort ?? undefined,
runtimeConfigRevision: wakeCtx.runtimeConfigRevision,
agentName: wakeCtx.name,
diff --git a/src/web/src/app/api/community/bots/route.test.ts b/src/web/src/app/api/community/bots/route.test.ts
index 06e2646cc..ee0fba7ba 100644
--- a/src/web/src/app/api/community/bots/route.test.ts
+++ b/src/web/src/app/api/community/bots/route.test.ts
@@ -109,6 +109,16 @@ describe("POST /api/community/bots — model", () => {
)
})
+ it.each(["opus", "sonnet", "haiku"])("persists the Claude %s alias verbatim", async (alias) => {
+ const res = await POST(postReq(base(alias)), ctx)
+ expect(res.status).toBe(201)
+ expect((await res.json()).bot.modelName).toBe(alias)
+ expect(mockCreateBot).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ modelName: alias }),
+ )
+ })
+
it("omitting model leaves modelName null", async () => {
const res = await POST(postReq(base()), ctx)
expect(res.status).toBe(201)
diff --git a/src/web/src/app/api/community/machines/[id]/reset-agents/route.ts b/src/web/src/app/api/community/machines/[id]/reset-agents/route.ts
index e51da2523..1e237a37f 100644
--- a/src/web/src/app/api/community/machines/[id]/reset-agents/route.ts
+++ b/src/web/src/app/api/community/machines/[id]/reset-agents/route.ts
@@ -42,7 +42,7 @@ export const POST = withAuth(async (_req, ctx) => {
agentId: bot.id,
config: makeRuntimeConfig({
runtime: bot.runtime,
- model: resolveModelConfig(bot.runtime, bot.modelName),
+ model: resolveModelConfig(bot.modelName),
reasoningEffort: bot.reasoningEffort ?? undefined,
runtimeConfigRevision: bot.runtimeConfigRevision,
agentName: bot.name,
diff --git a/src/web/src/app/api/community/machines/route.test.ts b/src/web/src/app/api/community/machines/route.test.ts
index 4c4c739a6..6f43166a2 100644
--- a/src/web/src/app/api/community/machines/route.test.ts
+++ b/src/web/src/app/api/community/machines/route.test.ts
@@ -39,6 +39,32 @@ describe("GET /api/community/machines — provider quota", () => {
vi.clearAllMocks()
})
+ it("keeps same-runtime catalogs isolated between machine rows", async () => {
+ const runtime = (modelId: string) => ({
+ id: "codex",
+ status: "healthy",
+ reasoning: {
+ updateMode: "unsupported",
+ models: [{ id: modelId, supportedReasoningEfforts: [] }],
+ },
+ })
+ mockListMachinesForUser.mockResolvedValue([
+ { id: "machine-a", status: "online", availableRuntimes: [runtime("a-model")] },
+ { id: "machine-b", status: "online", availableRuntimes: [runtime("b-model")] },
+ ])
+ mockListMachineBackendQuotasForUser.mockResolvedValue(new Map())
+
+ const response = await GET(new NextRequest("http://localhost/api/community/machines"))
+ const body = await response.json() as { machines: Array<{ id: string; availableRuntimes: any[] }> }
+ expect(body.machines.map((machine) => ({
+ id: machine.id,
+ models: machine.availableRuntimes[0]?.reasoning?.models.map((model: any) => model.id),
+ }))).toEqual([
+ { id: "machine-a", models: ["a-model"] },
+ { id: "machine-b", models: ["b-model"] },
+ ])
+ })
+
it("projects one safe machine/backend quota entry per reported runtime", async () => {
const observedAt = new Date().toISOString()
mockListMachinesForUser.mockResolvedValue([{
diff --git a/src/web/src/components/community/bots/bot-runtime-fields.test.ts b/src/web/src/components/community/bots/bot-runtime-fields.test.ts
index f2a7acfc9..cce44dd39 100644
--- a/src/web/src/components/community/bots/bot-runtime-fields.test.ts
+++ b/src/web/src/components/community/bots/bot-runtime-fields.test.ts
@@ -16,8 +16,8 @@ vi.mock("@/lib/utils", () => ({
}))
vi.mock("./model-field", () => ({
- ModelField: ({ runtime, value }: { runtime: string; value: string | null }) =>
- React.createElement("div", { "data-runtime": runtime, "data-model": value }),
+ ModelField: ({ runtime, value }: { runtime: { id: string } | null; value: string | null }) =>
+ React.createElement("div", { "data-runtime": runtime?.id, "data-model": value }),
}))
import { BotRuntimeFields } from "./bot-runtime-fields"
diff --git a/src/web/src/components/community/bots/bot-runtime-fields.tsx b/src/web/src/components/community/bots/bot-runtime-fields.tsx
index 666c24b8f..14615d6bd 100644
--- a/src/web/src/components/community/bots/bot-runtime-fields.tsx
+++ b/src/web/src/components/community/bots/bot-runtime-fields.tsx
@@ -44,6 +44,8 @@ export function BotRuntimeFields({
runtimeError?: string
disableUnhealthyOptions?: boolean
}) {
+ const selectedRuntime = options.find((option) => option.id === runtime) ?? null
+
function selectRuntime(next: string) {
if (next === runtime) return
onRuntimeChange(next)
@@ -107,9 +109,9 @@ export function BotRuntimeFields({
</div>
{runtime ? (
<div data-motion-target={modelMotionTarget} className={cn("flex flex-col gap-4", modelClassName)}>
- <ModelField runtime={runtime} value={model} onChange={onModelChange} />
+ <ModelField runtime={selectedRuntime} value={model} onChange={onModelChange} />
<ReasoningEffortField
- runtime={options.find((option) => option.id === runtime) ?? null}
+ runtime={selectedRuntime}
model={model}
value={reasoningEffort}
onChange={onReasoningEffortChange}
diff --git a/src/web/src/components/community/bots/create-bot-sheet.test.ts b/src/web/src/components/community/bots/create-bot-sheet.test.ts
index dcdfcbc81..fabba8d7d 100644
--- a/src/web/src/components/community/bots/create-bot-sheet.test.ts
+++ b/src/web/src/components/community/bots/create-bot-sheet.test.ts
@@ -140,9 +140,9 @@ vi.mock("./bot-form-fields", () => ({
// Capture ModelField's incoming `value` so we can assert the create sheet
// resets the model to null (Default) on a runtime change.
-const modelFieldRenders: Array<{ runtime: string | null; value: string | null }> = []
+const modelFieldRenders: Array<{ runtime: { id: string; reasoning?: unknown } | null; value: string | null }> = []
vi.mock("./model-field", () => ({
- ModelField: ({ runtime, value }: { runtime: string | null; value: string | null }) => {
+ ModelField: ({ runtime, value }: { runtime: { id: string; reasoning?: unknown } | null; value: string | null }) => {
modelFieldRenders.push({ runtime, value })
return React.createElement("div", { "data-mock": "model-field", "data-value": value ?? "" })
},
@@ -317,10 +317,46 @@ describe("CreateBotSheet — auto-select defaults", () => {
serverRadio.props.onChange()
})
const last = modelFieldRenders.at(-1)!
- expect(last.runtime).toBe("codex")
+ expect(last.runtime?.id).toBe("codex")
expect(last.value).toBeNull()
})
+ it("passes only the selected machine's same-runtime catalog to ModelField", () => {
+ const catalog = (id: string) => ({
+ updateMode: "unsupported" as const,
+ models: [{ id, supportedReasoningEfforts: [] }],
+ })
+ useMachinesMock.mockReturnValue({
+ machines: [
+ machine({
+ id: "machine-a",
+ status: "online",
+ availableRuntimes: [{ id: "codex", status: "healthy", reasoning: catalog("a-model") }],
+ }),
+ machine({
+ id: "machine-b",
+ status: "online",
+ availableRuntimes: [{ id: "codex", status: "healthy", reasoning: catalog("b-model") }],
+ }),
+ ],
+ })
+ modelFieldRenders.length = 0
+ const renderer = render()
+ expect(modelFieldRenders.at(-1)?.runtime?.reasoning).toEqual(catalog("a-model"))
+
+ const machineB = renderer.root.find(
+ (node) => node.type === "input" && node.props.name === "bot-machine" && node.props.value === "machine-b",
+ )
+ act(() => machineB.props.onChange())
+ expect(modelFieldRenders.at(-1)?.runtime?.reasoning).toEqual(catalog("b-model"))
+
+ const machineA = renderer.root.find(
+ (node) => node.type === "input" && node.props.name === "bot-machine" && node.props.value === "machine-a",
+ )
+ act(() => machineA.props.onChange())
+ expect(modelFieldRenders.at(-1)?.runtime?.reasoning).toEqual(catalog("a-model"))
+ })
+
it("includes the selected runtime-reported reasoning effort in create", async () => {
useMachinesMock.mockReturnValue({
machines: [
diff --git a/src/web/src/components/community/bots/create-bot-sheet.tsx b/src/web/src/components/community/bots/create-bot-sheet.tsx
index 9246900d8..78bb3901d 100644
--- a/src/web/src/components/community/bots/create-bot-sheet.tsx
+++ b/src/web/src/components/community/bots/create-bot-sheet.tsx
@@ -259,7 +259,12 @@ export function CreateBotSheet({
No paired machines — pair one first.
</p>
) : (
- <div className="flex flex-col gap-2" role="radiogroup" aria-label="Machine">
+ <div
+ className="flex flex-col gap-2"
+ role="radiogroup"
+ aria-label="Machine"
+ data-testid="bot-machine-picker"
+ >
{machines.map((m) => {
const online = isPresenceOnline(m.status)
const selected = machineId === m.id
diff --git a/src/web/src/components/community/bots/edit-bot-sheet.test.ts b/src/web/src/components/community/bots/edit-bot-sheet.test.ts
index d3f8579db..13af56dfa 100644
--- a/src/web/src/components/community/bots/edit-bot-sheet.test.ts
+++ b/src/web/src/components/community/bots/edit-bot-sheet.test.ts
@@ -120,14 +120,20 @@ vi.mock("@/lib/utils", () => ({
vi.mock("./bot-form-fields", () => ({
BotFormFields: () => require("react").createElement("div"),
}))
+const modelFieldRenders: Array<{ runtime: { id: string; reasoning?: unknown } | null }> = []
vi.mock("./model-field", () => {
const React = require("react")
return {
- ModelField: ({ onChange }: { onChange: (v: string | null) => void }) =>
- React.createElement("button", {
+ ModelField: ({ runtime, onChange }: {
+ runtime: { id: string; reasoning?: unknown } | null
+ onChange: (v: string | null) => void
+ }) => {
+ modelFieldRenders.push({ runtime })
+ return React.createElement("button", {
"data-testid": "set-model",
onClick: () => onChange("claude-sonnet-4-6"),
- }),
+ })
+ },
}
})
vi.mock("./reasoning-effort-field", () => {
@@ -207,6 +213,22 @@ describe("EditBotSheet — model switch toast (online-only)", () => {
useMachinesMock.mockReturnValue(HEALTHY_MACHINES)
})
+ it("uses only the bot machine's catalog when another machine reports the same runtime", () => {
+ const reasoning = (id: string) => ({
+ updateMode: "unsupported",
+ models: [{ id, supportedReasoningEfforts: [] }],
+ })
+ useMachinesMock.mockReturnValue({
+ machines: [
+ { id: "mac1", availableRuntimes: [{ id: "claude", status: "healthy", reasoning: reasoning("mac-model") }] },
+ { id: "mac2", availableRuntimes: [{ id: "claude", status: "healthy", reasoning: reasoning("other-model") }] },
+ ],
+ })
+ modelFieldRenders.length = 0
+ renderSheet()
+ expect(modelFieldRenders.at(-1)?.runtime?.reasoning).toEqual(reasoning("mac-model"))
+ })
+
it("PATCH success → 'Model switch to <new> dispatched'", async () => {
updateMutateAsync.mockResolvedValue({ bot: { ...BOT, modelName: "claude-sonnet-4-6" } })
const renderer = renderSheet()
diff --git a/src/web/src/components/community/bots/model-field.test.ts b/src/web/src/components/community/bots/model-field.test.ts
index a048c4e25..e3a0e1d1e 100644
--- a/src/web/src/components/community/bots/model-field.test.ts
+++ b/src/web/src/components/community/bots/model-field.test.ts
@@ -7,19 +7,24 @@ import TestRenderer, { act } from "react-test-renderer"
// passthrough that (a) records the current value and (b) exposes an onValueChange
// hook the test can drive, and render SelectItem children as plain nodes so we
// can assert which options exist.
-const selectCalls: Array<{ value: string; onValueChange: (v: string | null) => void }> = []
+const selectCalls: Array<{
+ value: string
+ onValueChange: (v: string | null) => void
+ onOpenChange?: (open: boolean) => void
+}> = []
vi.mock("@/components/ui/select", () => {
const React = require("react")
return {
- Select: ({ value, onValueChange, children }: any) => {
- selectCalls.push({ value, onValueChange })
+ Select: ({ value, onValueChange, onOpenChange, children }: any) => {
+ selectCalls.push({ value, onValueChange, onOpenChange })
return React.createElement("div", { "data-mock": "select", "data-value": value }, children)
},
SelectTrigger: ({ children, ...props }: any) =>
React.createElement("button", { "data-mock": "trigger", ...props }, children),
SelectValue: ({ placeholder }: any) =>
React.createElement("span", { "data-mock": "value" }, placeholder),
- SelectContent: ({ children }: any) => React.createElement("div", { "data-mock": "content" }, children),
+ SelectContent: ({ children, ...props }: any) =>
+ React.createElement("div", { "data-mock": "content", ...props }, children),
SelectItem: ({ value, children }: any) =>
React.createElement("div", { "data-mock": "item", "data-value": value }, children),
SelectSeparator: () => React.createElement("hr", { "data-mock": "separator" }),
@@ -36,6 +41,7 @@ vi.mock("@/components/ui/input", () => {
})
import { ModelField } from "./model-field"
+import type { CommunityMachineRuntime } from "@alook/shared"
function itemValues(renderer: TestRenderer.ReactTestRenderer): string[] {
return renderer.root
@@ -44,7 +50,7 @@ function itemValues(renderer: TestRenderer.ReactTestRenderer): string[] {
}
function render(props: {
- runtime: string | null
+ runtime: Pick<CommunityMachineRuntime, "id" | "reasoning"> | null
value: string | null
onChange?: (v: string | null) => void
}): TestRenderer.ReactTestRenderer {
@@ -58,27 +64,81 @@ function render(props: {
}
describe("ModelField", () => {
- it("renders Default + the catalog options + Custom… for claude", () => {
- const renderer = render({ runtime: "claude", value: null })
- const values = itemValues(renderer)
- expect(values).toContain("__default__")
- expect(values).toContain("claude-opus-4-6")
- expect(values).toContain("claude-sonnet-4-6")
- expect(values).toContain("__custom__")
+ const runtime = (id: string, models: string[]) => ({
+ id,
+ reasoning: {
+ updateMode: "unsupported" as const,
+ models: models.map((modelId) => ({ id: modelId, supportedReasoningEfforts: [] })),
+ },
})
- it("renders only Default + Custom… for cursor (empty catalog)", () => {
- const values = itemValues(render({ runtime: "cursor", value: null }))
+ it("renders exactly Default + aliases + Custom… for Claude's reported catalog", () => {
+ const values = itemValues(render({
+ runtime: runtime("claude", ["opus", "sonnet", "haiku"]),
+ value: null,
+ }))
+ expect(values).toEqual(["__default__", "__custom__", "opus", "sonnet", "haiku"])
+ expect(values.some((value) => value.startsWith("claude-"))).toBe(false)
+ })
+
+ it("renders only Default + Custom… when the selected runtime has no catalog", () => {
+ const renderer = render({ runtime: { id: "cursor" }, value: null })
+ const values = itemValues(renderer)
expect(values).toEqual(["__default__", "__custom__"])
+ expect(renderer.root.findAllByProps({ "data-testid": "bot-model-filter-input" })).toHaveLength(0)
+ expect(renderer.root.findAllByProps({ "data-testid": "bot-model-probe-results" })).toHaveLength(0)
+ expect(renderer.root.findAllByProps({ "data-mock": "separator" })).toHaveLength(0)
+ })
+
+ it("does not let reported IDs collide with picker sentinels", () => {
+ expect(itemValues(render({
+ runtime: runtime("cursor", ["__default__", "real-model", "__custom__"]),
+ value: null,
+ }))).toEqual(["__default__", "__custom__", "real-model"])
+ })
+
+ it("switches strictly between same-runtime catalogs from different machines", () => {
+ const first = runtime("codex", ["machine-a-model"])
+ const second = runtime("codex", ["machine-b-model"])
+ const renderer = render({ runtime: first, value: null })
+ expect(itemValues(renderer)).toEqual(["__default__", "__custom__", "machine-a-model"])
+ act(() => renderer.update(React.createElement(ModelField, {
+ runtime: second,
+ value: null,
+ onChange: vi.fn(),
+ })))
+ expect(itemValues(renderer)).toEqual(["__default__", "__custom__", "machine-b-model"])
+ })
+
+ it("reclassifies an unchanged stored value when the machine snapshot changes", () => {
+ selectCalls.length = 0
+ const renderer = render({ runtime: runtime("codex", ["machine-a-model"]), value: "machine-a-model" })
+ expect(selectCalls.at(-1)?.value).toBe("machine-a-model")
+
+ act(() => renderer.update(React.createElement(ModelField, {
+ runtime: runtime("codex", ["machine-b-model"]),
+ value: "machine-a-model",
+ onChange: vi.fn(),
+ })))
+ expect(selectCalls.at(-1)?.value).toBe("__custom__")
+ expect(renderer.root.findByProps({ "data-testid": "bot-model-custom-input" }).props.value)
+ .toBe("machine-a-model")
+ })
+
+ it("preserves an absent stored model as Custom… with a prefilled input", () => {
+ const renderer = render({ runtime: runtime("codex", ["observed"]), value: "stored-old" })
+ expect(selectCalls.at(-1)?.value).toBe("__custom__")
+ expect(renderer.root.findByProps({ "data-testid": "bot-model-custom-input" }).props.value)
+ .toBe("stored-old")
})
it("selecting a catalog entry emits that id; selecting Default emits null", () => {
const onChange = vi.fn()
selectCalls.length = 0
- render({ runtime: "claude", value: null, onChange })
+ render({ runtime: runtime("claude", ["opus", "sonnet", "haiku"]), value: null, onChange })
const latest = selectCalls.at(-1)!
- act(() => latest.onValueChange("claude-opus-4-6"))
- expect(onChange).toHaveBeenLastCalledWith("claude-opus-4-6")
+ act(() => latest.onValueChange("opus"))
+ expect(onChange).toHaveBeenLastCalledWith("opus")
act(() => selectCalls.at(-1)!.onValueChange("__default__"))
expect(onChange).toHaveBeenLastCalledWith(null)
})
@@ -86,7 +146,7 @@ describe("ModelField", () => {
it("Custom… reveals the input; typing emits the raw string; clearing emits null", () => {
const onChange = vi.fn()
selectCalls.length = 0
- const renderer = render({ runtime: "claude", value: null, onChange })
+ const renderer = render({ runtime: runtime("claude", ["opus", "sonnet", "haiku"]), value: null, onChange })
// No custom input until Custom… is chosen.
expect(renderer.root.findAll((n) => n.props?.["data-testid"] === "bot-model-custom-input")).toHaveLength(0)
act(() => selectCalls.at(-1)!.onValueChange("__custom__"))
@@ -97,4 +157,101 @@ describe("ModelField", () => {
act(() => input.props.onChange({ target: { value: "" } }))
expect(onChange).toHaveBeenLastCalledWith(null)
})
+
+ it("filters a 204-item catalog by case-insensitive substring while keeping Default and Custom", () => {
+ const models = Array.from({ length: 204 }, (_, index) => `Cursor-MODEL-${index}`)
+ const renderer = render({ runtime: runtime("cursor", models), value: null })
+ const filter = renderer.root.findByProps({ "data-testid": "bot-model-filter-input" })
+
+ act(() => filter.props.onChange({ target: { value: "mOdEl-20" } }))
+
+ expect(itemValues(renderer)).toEqual([
+ "__default__",
+ "__custom__",
+ "Cursor-MODEL-20",
+ "Cursor-MODEL-200",
+ "Cursor-MODEL-201",
+ "Cursor-MODEL-202",
+ "Cursor-MODEL-203",
+ ])
+ })
+
+ it("shows an explicit no-match state for a 479-item catalog and keeps Custom usable", () => {
+ const models = Array.from({ length: 479 }, (_, index) => `provider/model-${index}`)
+ const renderer = render({ runtime: runtime("opencode", models), value: null })
+ const filter = renderer.root.findByProps({ "data-testid": "bot-model-filter-input" })
+
+ act(() => filter.props.onChange({ target: { value: "not-in-catalog" } }))
+
+ expect(itemValues(renderer)).toEqual(["__default__", "__custom__"])
+ expect(renderer.root.findByProps({ role: "status" }).children).toEqual(["No matching models"])
+ })
+
+ it("clears the filter when the list closes", () => {
+ selectCalls.length = 0
+ const renderer = render({ runtime: runtime("codex", ["gpt-one", "gpt-two"]), value: null })
+ const filter = renderer.root.findByProps({ "data-testid": "bot-model-filter-input" })
+ act(() => filter.props.onChange({ target: { value: "two" } }))
+ expect(itemValues(renderer)).toEqual(["__default__", "__custom__", "gpt-two"])
+
+ act(() => selectCalls.at(-1)?.onOpenChange?.(false))
+ expect(renderer.root.findByProps({ "data-testid": "bot-model-filter-input" }).props.value).toBe("")
+ expect(itemValues(renderer)).toEqual(["__default__", "__custom__", "gpt-one", "gpt-two"])
+ })
+
+ it("clears the filter and never leaks results when switching same-runtime machines", () => {
+ const renderer = render({
+ runtime: runtime("codex", ["machine-a-one", "machine-a-two"]),
+ value: null,
+ })
+ const filter = renderer.root.findByProps({ "data-testid": "bot-model-filter-input" })
+ act(() => filter.props.onChange({ target: { value: "two" } }))
+ expect(itemValues(renderer)).toEqual(["__default__", "__custom__", "machine-a-two"])
+
+ act(() => renderer.update(React.createElement(ModelField, {
+ runtime: runtime("codex", ["machine-b-three"]),
+ value: null,
+ onChange: vi.fn(),
+ })))
+ expect(renderer.root.findByProps({ "data-testid": "bot-model-filter-input" }).props.value).toBe("")
+ expect(itemValues(renderer)).toEqual(["__default__", "__custom__", "machine-b-three"])
+ })
+
+ it("supports immediate mobile/keyboard filtering without swallowing list navigation keys", () => {
+ const renderer = render({ runtime: runtime("cursor", ["one", "two"]), value: null })
+ const filter = renderer.root.findByProps({ "data-testid": "bot-model-filter-input" })
+ expect(filter.props.autoFocus).toBe(true)
+ expect(filter.props.className).toContain("h-10")
+ expect(filter.props.className).toContain("sm:h-8")
+ const content = renderer.root.findByProps({ "data-mock": "content" })
+ expect(content.props.className).toContain("overflow-y-hidden")
+ const controls = renderer.root.findByProps({ "data-testid": "bot-model-fixed-controls" })
+ expect(controls.props.className).toContain("shrink-0")
+ const results = renderer.root.findByProps({ "data-testid": "bot-model-probe-results" })
+ expect(results.props.className).toContain("max-h-[min(18rem,50dvh)]")
+ expect(results.props.className).toContain("overflow-y-auto")
+ expect(results.props.className).toContain("thin-scrollbar")
+
+ const printable = { key: "o", stopPropagation: vi.fn() }
+ filter.props.onKeyDown(printable)
+ expect(printable.stopPropagation).toHaveBeenCalledOnce()
+
+ const navigation = { key: "ArrowDown", stopPropagation: vi.fn() }
+ filter.props.onKeyDown(navigation)
+ expect(navigation.stopPropagation).not.toHaveBeenCalled()
+
+ const highlighted = { click: vi.fn() }
+ const enter = {
+ key: "Enter",
+ preventDefault: vi.fn(),
+ stopPropagation: vi.fn(),
+ currentTarget: {
+ closest: vi.fn(() => ({ querySelector: vi.fn(() => highlighted) })),
+ },
+ }
+ filter.props.onKeyDown(enter)
+ expect(enter.preventDefault).toHaveBeenCalledOnce()
+ expect(enter.stopPropagation).toHaveBeenCalledOnce()
+ expect(highlighted.click).toHaveBeenCalledOnce()
+ })
})
diff --git a/src/web/src/components/community/bots/model-field.tsx b/src/web/src/components/community/bots/model-field.tsx
index 1e22214d0..69ea7ef21 100644
--- a/src/web/src/components/community/bots/model-field.tsx
+++ b/src/web/src/components/community/bots/model-field.tsx
@@ -2,12 +2,12 @@
import { useEffect, useMemo, useState } from "react"
import {
- getRuntimeModelCatalog,
modelSelectState,
modelNameFromSelect,
MODEL_SELECT_DEFAULT,
MODEL_SELECT_CUSTOM,
} from "@alook/shared"
+import type { CommunityMachineRuntime } from "@alook/shared"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import {
@@ -20,7 +20,7 @@ import {
} from "@/components/ui/select"
/**
- * Per-bot model picker. A `Select` over `[Default, ...catalog, Custom…]` plus a
+ * Per-bot model picker. A `Select` over `[Default, Custom…, ...catalog]` plus a
* conditionally-rendered custom text input. All model-name ↔ Select translation
* goes through the shared `bot-model` helpers — never ad-hoc string logic.
*
@@ -38,30 +38,38 @@ export function ModelField({
onChange,
disabled,
}: {
- runtime: string | null
+ runtime: Pick<CommunityMachineRuntime, "id" | "reasoning"> | null
value: string | null
onChange: (v: string | null) => void
disabled?: boolean
}) {
- const catalog = useMemo(() => getRuntimeModelCatalog(runtime), [runtime])
- const seed = useMemo(() => modelSelectState(runtime, value), [runtime, value])
+ const modelIds = useMemo(
+ () => runtime?.reasoning?.models
+ .map((model) => model.id)
+ .filter((id) => id !== MODEL_SELECT_DEFAULT && id !== MODEL_SELECT_CUSTOM) ?? [],
+ [runtime],
+ )
+ const seed = useMemo(() => modelSelectState(modelIds, value), [modelIds, value])
const [selectValue, setSelectValue] = useState(seed.selectValue)
const [customName, setCustomName] = useState(seed.customName)
+ const [filterQuery, setFilterQuery] = useState("")
- // Re-seed on external value/runtime changes only. Our own onChange echoes back
- // as a `value` that already round-trips to local state, so this no-ops for it.
+ // Re-seed whenever the selected machine/runtime snapshot or stored value
+ // changes. This is required even when the stored string is unchanged: a
+ // value can be a reported option on machine A and Custom… on machine B.
useEffect(() => {
- const resolved = modelNameFromSelect(selectValue, customName)
- if (resolved !== (value ?? null)) {
- setSelectValue(seed.selectValue)
- setCustomName(seed.customName)
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [runtime, value])
+ setSelectValue(seed.selectValue)
+ setCustomName(seed.customName)
+ setFilterQuery("")
+ }, [seed])
const isCustom = selectValue === MODEL_SELECT_CUSTOM
- const defaultLabel = runtime ? `Default (${runtime}'s own default)` : "Default"
+ const defaultLabel = runtime ? `Default (${runtime.id}'s own default)` : "Default"
+ const normalizedFilter = filterQuery.trim().toLowerCase()
+ const filteredModelIds = normalizedFilter
+ ? modelIds.filter((model) => model.toLowerCase().includes(normalizedFilter))
+ : modelIds
// Base UI resolves the collapsed-trigger label from `items` (value → label).
// Without it, SelectValue renders the raw value — fine for catalog ids
@@ -69,8 +77,8 @@ export function ModelField({
// Same pattern as runtime-select.tsx.
const items = [
{ value: MODEL_SELECT_DEFAULT, label: defaultLabel },
- ...catalog.models.map((m) => ({ value: m, label: m })),
{ value: MODEL_SELECT_CUSTOM, label: "Custom…" },
+ ...modelIds.map((model) => ({ value: model, label: model })),
]
return (
@@ -87,6 +95,9 @@ export function ModelField({
// until something is typed); any other value maps through the helper.
onChange(modelNameFromSelect(nextValue, customName))
}}
+ onOpenChange={(open) => {
+ if (!open) setFilterQuery("")
+ }}
disabled={disabled}
>
<SelectTrigger
@@ -95,15 +106,63 @@ export function ModelField({
>
<SelectValue placeholder={defaultLabel} />
</SelectTrigger>
- <SelectContent>
- <SelectItem value={MODEL_SELECT_DEFAULT}>{defaultLabel}</SelectItem>
- {catalog.models.map((m) => (
- <SelectItem key={m} value={m}>
- <span className="font-mono">{m}</span>
- </SelectItem>
- ))}
- <SelectSeparator />
- <SelectItem value={MODEL_SELECT_CUSTOM}>Custom…</SelectItem>
+ <SelectContent className="overflow-y-hidden">
+ {modelIds.length === 0 ? (
+ <>
+ <SelectItem value={MODEL_SELECT_DEFAULT}>{defaultLabel}</SelectItem>
+ <SelectItem value={MODEL_SELECT_CUSTOM}>Custom…</SelectItem>
+ </>
+ ) : (
+ <>
+ <div data-testid="bot-model-fixed-controls" className="shrink-0 bg-popover">
+ <div className="p-1.5">
+ <Input
+ autoFocus
+ data-testid="bot-model-filter-input"
+ value={filterQuery}
+ placeholder="Filter models…"
+ aria-label="Filter models"
+ onChange={(event) => setFilterQuery(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ const highlighted = event.currentTarget
+ .closest('[role="listbox"]')
+ ?.querySelector<HTMLElement>("[data-highlighted]")
+ if (highlighted) {
+ event.preventDefault()
+ event.stopPropagation()
+ highlighted.click()
+ }
+ return
+ }
+ if (!["ArrowDown", "ArrowUp", "Escape", "Tab"].includes(event.key)) {
+ event.stopPropagation()
+ }
+ }}
+ className="h-10 font-mono sm:h-8"
+ />
+ </div>
+ <SelectItem value={MODEL_SELECT_DEFAULT}>{defaultLabel}</SelectItem>
+ <SelectItem value={MODEL_SELECT_CUSTOM}>Custom…</SelectItem>
+ <SelectSeparator />
+ </div>
+ <div
+ data-testid="bot-model-probe-results"
+ className="thin-scrollbar max-h-[min(18rem,50dvh)] overflow-y-auto"
+ >
+ {filteredModelIds.map((model) => (
+ <SelectItem key={model} value={model}>
+ <span className="font-mono">{model}</span>
+ </SelectItem>
+ ))}
+ {normalizedFilter && filteredModelIds.length === 0 ? (
+ <p role="status" className="px-2 py-2 text-xs text-muted-foreground">
+ No matching models
+ </p>
+ ) : null}
+ </div>
+ </>
+ )}
</SelectContent>
</Select>
{isCustom && (
@@ -111,7 +170,7 @@ export function ModelField({
data-testid="bot-model-custom-input"
value={customName}
disabled={disabled}
- placeholder="e.g. claude-sonnet-4-6"
+ placeholder="e.g. provider/model-id"
onChange={(e) => {
setCustomName(e.target.value)
onChange(modelNameFromSelect(MODEL_SELECT_CUSTOM, e.target.value))
diff --git a/src/ws-do/src/ws-durable/machine-frames.test.ts b/src/ws-do/src/ws-durable/machine-frames.test.ts
index 1b575d3cd..7277037b8 100644
--- a/src/ws-do/src/ws-durable/machine-frames.test.ts
+++ b/src/ws-do/src/ws-durable/machine-frames.test.ts
@@ -160,7 +160,14 @@ describe("WebSocketDurableObject", () => {
// The wire frame the daemon actually sends — see WsControlChannel.reportReady.
const frame = JSON.stringify({
type: "ready",
- runtimeReport: [{ id: "claude", version: "1.0.0" }],
+ runtimeReport: [{
+ id: "claude",
+ version: "1.0.0",
+ reasoning: {
+ updateMode: "unsupported",
+ models: [{ id: "opus", supportedReasoningEfforts: [] }],
+ },
+ }],
capabilities: ["control-heartbeat-v1"],
runningAgents: [],
hostname: "my-mac",
@@ -181,11 +188,113 @@ describe("WebSocketDurableObject", () => {
arch: "arm64",
osRelease: "23.0.0",
daemonVersion: "0.1.0",
- availableRuntimes: [{ id: "claude", version: "1.0.0" }],
+ availableRuntimes: [{
+ id: "claude",
+ version: "1.0.0",
+ reasoning: {
+ updateMode: "unsupported",
+ models: [{ id: "opus", supportedReasoningEfforts: [] }],
+ },
+ }],
})
expect(credentialHash).toBe("0".repeat(64))
})
+ it("replaces an older catalog with an honestly absent current snapshot", async () => {
+ const { durable, store } = createDO()
+ store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "cm_1",
+ credentialHash: "0".repeat(64),
+ })
+ mockUpsertMachineByMachineId.mockResolvedValue({
+ machine: { id: "cm_1", availableRuntimes: [{ id: "codex" }], status: "online" },
+ priorAvailableRuntimes: [{
+ id: "codex",
+ reasoning: {
+ updateMode: "unsupported",
+ models: [{ id: "old-model", supportedReasoningEfforts: [] }],
+ },
+ }],
+ priorStatus: "online",
+ })
+ const ws = createMockWebSocket()
+ ws.serializeAttachment({
+ type: "community-machine",
+ machineId: "cm_1",
+ userId: "u_1",
+ authenticated: true,
+ })
+
+ await durable.webSocketMessage(ws as any, JSON.stringify({
+ type: "ready",
+ runtimeReport: [{ id: "codex", status: "healthy" }],
+ capabilities: ["control-heartbeat-v1"],
+ runningAgents: [],
+ }))
+
+ expect(mockUpsertMachineByMachineId.mock.calls[0]?.[3]).toMatchObject({
+ availableRuntimes: [{ id: "codex", status: "healthy" }],
+ })
+ expect(mockUpsertMachineByMachineId.mock.calls[0]?.[3].availableRuntimes[0].reasoning)
+ .toBeUndefined()
+ })
+
+ it("keeps same-runtime catalogs distinct in two machine persistence writes", async () => {
+ const first = createDO()
+ const second = createDO()
+ first.store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "machine-a",
+ credentialHash: "a".repeat(64),
+ })
+ second.store.set("community-machine-identity", {
+ userId: "u_1",
+ machineId: "machine-b",
+ credentialHash: "b".repeat(64),
+ })
+ mockUpsertMachineByMachineId
+ .mockResolvedValueOnce({ machine: { id: "machine-a" }, priorStatus: "online" })
+ .mockResolvedValueOnce({ machine: { id: "machine-b" }, priorStatus: "online" })
+ const socketA = createMockWebSocket()
+ const socketB = createMockWebSocket()
+ socketA.serializeAttachment({
+ type: "community-machine",
+ machineId: "machine-a",
+ userId: "u_1",
+ authenticated: true,
+ })
+ socketB.serializeAttachment({
+ type: "community-machine",
+ machineId: "machine-b",
+ userId: "u_1",
+ authenticated: true,
+ })
+ const frame = (modelId: string) => JSON.stringify({
+ type: "ready",
+ capabilities: ["control-heartbeat-v1"],
+ runtimeReport: [{
+ id: "codex",
+ reasoning: {
+ updateMode: "unsupported",
+ models: [{ id: modelId, supportedReasoningEfforts: [] }],
+ },
+ }],
+ runningAgents: [],
+ })
+
+ await first.durable.webSocketMessage(socketA as any, frame("a-model"))
+ await second.durable.webSocketMessage(socketB as any, frame("b-model"))
+
+ expect(mockUpsertMachineByMachineId.mock.calls.map((call) => ({
+ machineId: call[2],
+ modelId: call[3].availableRuntimes[0].reasoning.models[0].id,
+ }))).toEqual([
+ { machineId: "machine-a", modelId: "a-model" },
+ { machineId: "machine-b", modelId: "b-model" },
+ ])
+ })
+
it("persists only valid quotas for backends present in the accepted runtime report", async () => {
const { durable, store } = createDO()
store.set("community-machine-identity", {