Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(cursor): use ACP-native model catalog (#631)

Gustavo Yec51e0802695d
diff --git a/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts b/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts
index b9a3730b1..27e42a162 100644
--- a/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts
+++ b/src/daemon/agent-driver/src/adapters/cursor/acp-lane.ts
@@ -14,6 +14,7 @@ import type {
} from "../../internal/adapter.js";
import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";
import { killProcessTree, SESSION_STOP_GRACE_MS } from "../../internal/killTree.js";
+import { flattenCursorAcpSelectOptions } from "./catalog-probe.js";
const ACP_PROTOCOL_VERSION = 1;
const HANDSHAKE_TIMEOUT_MS = 15_000;
@@ -103,24 +104,6 @@ function isMissingSessionError(error: unknown): boolean {
|| /\b(not found|missing|unknown|invalid)\b.*\bsession\b/i.test(message);
}
-function flattenSelectOptions(value: unknown): Array<{ value: string; name?: string }> {
- if (!Array.isArray(value)) return [];
- const out: Array<{ value: string; name?: string }> = [];
- for (const item of value) {
- if (Array.isArray(item)) {
- out.push(...flattenSelectOptions(item));
- continue;
- }
- const candidate = record(item);
- if (!candidate) continue;
- if (typeof candidate.value === "string") {
- out.push({ value: candidate.value, ...(typeof candidate.name === "string" ? { name: candidate.name } : {}) });
- }
- if (Array.isArray(candidate.options)) out.push(...flattenSelectOptions(candidate.options));
- }
- return out;
-}
-
export class CursorAcpLane implements RuntimeLane {
private readonly events = new EventEmitter();
private readonly pending = new Map<number, PendingRequest>();
@@ -287,15 +270,25 @@ export class CursorAcpLane implements RuntimeLane {
} else {
session = record(await this.call("session/new", { cwd: ctx.workingDirectory, mcpServers: [] }));
}
- if (!session || typeof session.sessionId !== "string" || !session.sessionId.trim()) {
+ if (!session) throw new Error("Cursor ACP did not return a valid session response");
+ const returnedSessionId = session.sessionId;
+ if (returnedSessionId !== undefined
+ && (typeof returnedSessionId !== "string" || !returnedSessionId.trim())) {
throw new Error("Cursor ACP did not return a valid session id");
}
- if (ctx.config.sessionId && session.sessionId !== ctx.config.sessionId) {
- throw new CursorAcpResetRequiredError(
- "Cursor ACP loaded a different session; reset this agent before continuing",
- );
+ if (ctx.config.sessionId) {
+ if (returnedSessionId !== undefined && returnedSessionId !== ctx.config.sessionId) {
+ throw new CursorAcpResetRequiredError(
+ "Cursor ACP loaded a different session; reset this agent before continuing",
+ );
+ }
+ this.sessionId = ctx.config.sessionId;
+ } else {
+ if (typeof returnedSessionId !== "string") {
+ throw new Error("Cursor ACP did not return a valid session id");
+ }
+ this.sessionId = returnedSessionId;
}
- this.sessionId = session.sessionId;
await this.configureModel(session, ctx);
}
@@ -307,21 +300,26 @@ export class CursorAcpLane implements RuntimeLane {
if (!modelConfig) {
throw new CursorAcpIncompatibleError("Installed Cursor ACP does not support model configuration");
}
- const options = flattenSelectOptions(modelConfig.options);
- const match = options.find((option) => option.value === requestedModel)
- ?? options.find((option) => option.name === requestedModel);
+ const options = flattenCursorAcpSelectOptions(modelConfig.options);
+ const match = options.find((option) => option.value === requestedModel);
if (!match) {
throw new CursorAcpIncompatibleError(`Configured Cursor model is unavailable through ACP: ${requestedModel}`);
}
+ let response: JsonRecord | null;
try {
- await this.call("session/set_config_option", {
+ response = record(await this.call("session/set_config_option", {
sessionId: this.sessionId,
configId: "model",
value: match.value,
- });
+ }));
} catch {
throw new CursorAcpIncompatibleError("Installed Cursor ACP rejected model configuration");
}
+ const confirmedOptions = Array.isArray(response?.configOptions) ? response.configOptions : [];
+ const confirmedModel = confirmedOptions.map(record).find((option) => option?.id === "model") ?? null;
+ if (confirmedModel?.currentValue !== match.value) {
+ throw new CursorAcpIncompatibleError("Cursor ACP did not confirm the exact configured model");
+ }
}
private admitPrompt(text: string): LaneAdmission {
diff --git a/src/daemon/agent-driver/src/adapters/cursor/catalog-probe.test.ts b/src/daemon/agent-driver/src/adapters/cursor/catalog-probe.test.ts
new file mode 100644
index 000000000..9defa71d4
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/cursor/catalog-probe.test.ts
@@ -0,0 +1,255 @@
+import { EventEmitter } from "node:events";
+import { PassThrough } from "node:stream";
+import { describe, expect, it, vi } from "vitest";
+import type { SpawnedProcessHandle } from "../../internal/adapter.js";
+import {
+ parseCursorAcpModelCatalog,
+ probeCursorAcpCatalog,
+} from "./catalog-probe.js";
+
+type FakeProcess = SpawnedProcessHandle & {
+ stdout: PassThrough;
+ stderr: PassThrough;
+ stdin: PassThrough;
+ emit(event: string, ...args: unknown[]): boolean;
+};
+
+function fakeProcess(onMessage: (process: FakeProcess, message: Record<string, unknown>) => void): FakeProcess {
+ const stdout = new PassThrough();
+ const stderr = new PassThrough();
+ const stdin = new PassThrough();
+ const process = Object.assign(new EventEmitter(), {
+ stdout,
+ stderr,
+ stdin,
+ pid: 4242,
+ exitCode: null,
+ signalCode: null,
+ kill: vi.fn(() => true),
+ }) as unknown as FakeProcess;
+ let buffer = "";
+ stdin.on("data", (chunk) => {
+ buffer += chunk.toString();
+ const lines = buffer.split("\n");
+ buffer = lines.pop() ?? "";
+ for (const line of lines) {
+ if (line.trim()) onMessage(process, JSON.parse(line) as Record<string, unknown>);
+ }
+ });
+ return process;
+}
+
+function respond(process: FakeProcess, request: Record<string, unknown>, result: unknown): void {
+ process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id: request.id, result })}\n`);
+}
+
+describe("Cursor ACP model catalog", () => {
+ it("normalizes nested exact values, preserves duplicate labels, and omits ACP Auto", () => {
+ expect(parseCursorAcpModelCatalog({
+ sessionId: "probe",
+ configOptions: [{
+ id: "model",
+ options: [
+ { value: "default[]", name: "Auto" },
+ [
+ { value: "grok-4.6[effort=high,fast=true]", name: "grok-4.6" },
+ { value: "grok-4.6[effort=max,fast=true]", name: "grok-4.6" },
+ ],
+ {
+ name: "Anthropic",
+ options: [{ value: "claude-opus-4.1", name: "Claude Opus 4.1" }],
+ },
+ { value: "claude-opus-4.1", name: "duplicate loses" },
+ { value: "bad value", name: "invalid whitespace" },
+ ],
+ }],
+ })).toEqual({
+ updateMode: "unsupported",
+ models: [
+ {
+ id: "grok-4.6[effort=high,fast=true]",
+ displayName: "grok-4.6",
+ supportedReasoningEfforts: [],
+ },
+ {
+ id: "grok-4.6[effort=max,fast=true]",
+ displayName: "grok-4.6",
+ supportedReasoningEfforts: [],
+ },
+ {
+ id: "claude-opus-4.1",
+ displayName: "Claude Opus 4.1",
+ supportedReasoningEfforts: [],
+ },
+ ],
+ });
+ });
+
+ it("drops malformed labels without dropping exact values and fails closed on overflow", () => {
+ expect(parseCursorAcpModelCatalog({
+ configOptions: [{
+ id: "model",
+ options: [{ value: "gpt-5.6-sol", name: "x".repeat(257) }],
+ }],
+ })).toEqual({
+ updateMode: "unsupported",
+ models: [{ id: "gpt-5.6-sol", supportedReasoningEfforts: [] }],
+ });
+ expect(parseCursorAcpModelCatalog({
+ configOptions: [{
+ id: "model",
+ options: Array.from({ length: 513 }, (_, index) => ({ value: `model-${index}` })),
+ }],
+ })).toBeUndefined();
+ });
+
+ it("uses only initialize/auth/session-new, returns exact ACP values, and cleans once", async () => {
+ const messages: Record<string, unknown>[] = [];
+ const cleanup = vi.fn(async () => {});
+ const process = fakeProcess((proc, message) => {
+ messages.push(message);
+ if (message.method === "initialize") {
+ respond(proc, message, {
+ protocolVersion: 1,
+ authMethods: [{ id: "cursor_login", name: "Cursor Login" }],
+ });
+ } else if (message.method === "authenticate") {
+ respond(proc, message, null);
+ } else if (message.method === "session/new") {
+ respond(proc, message, {
+ sessionId: "empty-probe-session",
+ configOptions: [{
+ id: "model",
+ options: [{ value: "grok-4.6[effort=high,fast=true]", name: "grok-4.6" }],
+ }],
+ });
+ }
+ });
+ const spawn = vi.fn(() => process);
+
+ await expect(probeCursorAcpCatalog("/custom/cursor-agent", {
+ cwd: "/safe/workspace",
+ spawn,
+ cleanup,
+ timeoutMs: 100,
+ })).resolves.toEqual({
+ updateMode: "unsupported",
+ models: [{
+ id: "grok-4.6[effort=high,fast=true]",
+ displayName: "grok-4.6",
+ supportedReasoningEfforts: [],
+ }],
+ });
+ expect(spawn).toHaveBeenCalledWith(
+ "/custom/cursor-agent",
+ ["acp"],
+ expect.objectContaining({ cwd: "/safe/workspace" }),
+ );
+ expect(messages.map((message) => message.method)).toEqual([
+ "initialize",
+ "authenticate",
+ "session/new",
+ ]);
+ expect(messages.some((message) => message.method === "session/prompt")).toBe(false);
+ expect(messages.at(-1)?.params).toEqual({ cwd: "/safe/workspace", mcpServers: [] });
+ expect(cleanup).toHaveBeenCalledTimes(1);
+ });
+
+ it("fails non-fatally and cleans on protocol/auth errors, malformed output, size, exit races, and timeout", async () => {
+ const cases = [
+ (process: FakeProcess, message: Record<string, unknown>) => {
+ if (message.method === "initialize") respond(process, message, { protocolVersion: 2, authMethods: [] });
+ },
+ (process: FakeProcess, message: Record<string, unknown>) => {
+ if (message.method === "initialize") respond(process, message, { protocolVersion: 1, authMethods: [] });
+ },
+ (process: FakeProcess) => {
+ process.stdout.write("not-json\n");
+ process.emit("exit", 1, null);
+ process.emit("error", new Error("late"));
+ },
+ ];
+
+ for (const onMessage of cases) {
+ const cleanup = vi.fn(async () => {});
+ const process = fakeProcess(onMessage);
+ await expect(probeCursorAcpCatalog(undefined, {
+ spawn: () => process,
+ cleanup,
+ timeoutMs: 25,
+ })).resolves.toBeUndefined();
+ expect(cleanup).toHaveBeenCalledTimes(1);
+ }
+
+ const sizeCleanup = vi.fn(async () => {});
+ const oversized = fakeProcess((process) => process.stdout.write("x".repeat(65)));
+ await expect(probeCursorAcpCatalog(undefined, {
+ spawn: () => oversized,
+ cleanup: sizeCleanup,
+ timeoutMs: 25,
+ outputMaxBytes: 64,
+ })).resolves.toBeUndefined();
+ expect(sizeCleanup).toHaveBeenCalledTimes(1);
+
+ const timeoutCleanup = vi.fn(async () => {});
+ await expect(probeCursorAcpCatalog(undefined, {
+ spawn: () => fakeProcess(() => {}),
+ cleanup: timeoutCleanup,
+ timeoutMs: 10,
+ })).resolves.toBeUndefined();
+ expect(timeoutCleanup).toHaveBeenCalledTimes(1);
+ });
+
+ it("covers spawn, write, session-id, stderr-size, and pidless cleanup failures", async () => {
+ await expect(probeCursorAcpCatalog(undefined, {
+ spawn: () => { throw new Error("spawn failed"); },
+ })).resolves.toBeUndefined();
+
+ const unwritable = fakeProcess(() => {});
+ unwritable.stdin.write = vi.fn(() => { throw new Error("write failed"); });
+ const writeCleanup = vi.fn(async () => {});
+ await expect(probeCursorAcpCatalog(undefined, {
+ spawn: () => unwritable,
+ cleanup: writeCleanup,
+ timeoutMs: 25,
+ })).resolves.toBeUndefined();
+ expect(writeCleanup).toHaveBeenCalledTimes(1);
+
+ const invalidSessionCleanup = vi.fn(async () => {});
+ const invalidSession = fakeProcess((process, message) => {
+ if (message.method === "initialize") {
+ respond(process, message, { protocolVersion: 1, authMethods: [{ id: "cursor_login" }] });
+ } else if (message.method === "authenticate") {
+ respond(process, message, null);
+ } else if (message.method === "session/new") {
+ respond(process, message, { sessionId: "" });
+ }
+ });
+ await expect(probeCursorAcpCatalog(undefined, {
+ spawn: () => invalidSession,
+ cleanup: invalidSessionCleanup,
+ timeoutMs: 25,
+ })).resolves.toBeUndefined();
+ expect(invalidSessionCleanup).toHaveBeenCalledTimes(1);
+
+ const stderrCleanup = vi.fn(async () => {});
+ const stderrOversized = fakeProcess((process) => process.stderr.write("x".repeat(65)));
+ await expect(probeCursorAcpCatalog(undefined, {
+ spawn: () => stderrOversized,
+ cleanup: stderrCleanup,
+ timeoutMs: 25,
+ outputMaxBytes: 64,
+ })).resolves.toBeUndefined();
+ expect(stderrCleanup).toHaveBeenCalledTimes(1);
+
+ const pidless = fakeProcess((process, message) => {
+ if (message.method === "initialize") respond(process, message, { protocolVersion: 2 });
+ });
+ Object.defineProperty(pidless, "pid", { value: undefined });
+ await expect(probeCursorAcpCatalog(undefined, {
+ spawn: () => pidless,
+ timeoutMs: 25,
+ })).resolves.toBeUndefined();
+ expect(pidless.kill).toHaveBeenCalledWith("SIGTERM");
+ });
+});
diff --git a/src/daemon/agent-driver/src/adapters/cursor/catalog-probe.ts b/src/daemon/agent-driver/src/adapters/cursor/catalog-probe.ts
new file mode 100644
index 000000000..126392b44
--- /dev/null
+++ b/src/daemon/agent-driver/src/adapters/cursor/catalog-probe.ts
@@ -0,0 +1,196 @@
+import type { RuntimeReasoningCatalog } from "../../contract.js";
+import type { SpawnedProcessHandle } from "../../internal/adapter.js";
+import { killProcessTree, spawnAgentProcess } from "../../internal/killTree.js";
+import {
+ normalizeRuntimeModelId,
+ RUNTIME_MODEL_CATALOG_MAX,
+} from "../../internal/modelCatalog.js";
+import { resolveSpawnSpec } from "../../internal/probe.js";
+import { jsonRpcRequest, tryParseJsonLine } from "../../internal/utils.js";
+
+const ACP_PROTOCOL_VERSION = 1;
+const AUTH_METHOD_ID = "cursor_login";
+const CATALOG_PROBE_TIMEOUT_MS = 15_000;
+const CATALOG_PROBE_OUTPUT_MAX_BYTES = 1024 * 1024;
+const MODEL_DISPLAY_NAME_MAX = 256;
+const MODEL_OPTION_NESTING_MAX = 16;
+
+type JsonRecord = Record<string, unknown>;
+
+type ProbeSpawn = (
+ command: string,
+ args: string[],
+ options: { cwd: string; env: NodeJS.ProcessEnv; shell: boolean },
+) => SpawnedProcessHandle;
+
+interface CursorAcpCatalogProbeOptions {
+ readonly cwd?: string;
+ readonly timeoutMs?: number;
+ readonly outputMaxBytes?: number;
+ readonly spawn?: ProbeSpawn;
+ readonly cleanup?: (process: SpawnedProcessHandle) => Promise<void>;
+}
+
+function record(value: unknown): JsonRecord | null {
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? value as JsonRecord
+ : null;
+}
+
+function normalizeDisplayName(value: unknown): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const displayName = value.trim();
+ return displayName && displayName.length <= MODEL_DISPLAY_NAME_MAX ? displayName : undefined;
+}
+
+export function flattenCursorAcpSelectOptions(
+ value: unknown,
+ depth = 0,
+): Array<{ value: string; name?: string }> {
+ if (!Array.isArray(value) || depth > MODEL_OPTION_NESTING_MAX) return [];
+ const options: Array<{ value: string; name?: string }> = [];
+ for (const item of value) {
+ if (Array.isArray(item)) {
+ options.push(...flattenCursorAcpSelectOptions(item, depth + 1));
+ continue;
+ }
+ const candidate = record(item);
+ if (!candidate) continue;
+ const exactValue = normalizeRuntimeModelId(candidate.value);
+ if (exactValue) {
+ const name = normalizeDisplayName(candidate.name);
+ options.push({ value: exactValue, ...(name ? { name } : {}) });
+ }
+ if (Array.isArray(candidate.options)) {
+ options.push(...flattenCursorAcpSelectOptions(candidate.options, depth + 1));
+ }
+ }
+ return options;
+}
+
+export function parseCursorAcpModelCatalog(session: unknown): RuntimeReasoningCatalog | undefined {
+ const payload = record(session);
+ const configOptions = Array.isArray(payload?.configOptions) ? payload.configOptions : [];
+ const modelConfig = configOptions.map(record).find((option) => option?.id === "model") ?? null;
+ if (!modelConfig) return undefined;
+ const seen = new Set<string>();
+ const models: RuntimeReasoningCatalog["models"][number][] = [];
+ for (const option of flattenCursorAcpSelectOptions(modelConfig.options)) {
+ if (option.value === "default[]" || seen.has(option.value)) continue;
+ if (models.length >= RUNTIME_MODEL_CATALOG_MAX) return undefined;
+ seen.add(option.value);
+ models.push({
+ id: option.value,
+ ...(option.name ? { displayName: option.name } : {}),
+ supportedReasoningEfforts: [],
+ });
+ }
+ return models.length > 0 ? { updateMode: "unsupported", models } : undefined;
+}
+
+async function cleanupProbeProcess(process: SpawnedProcessHandle): Promise<void> {
+ if (process.pid) {
+ await killProcessTree(process.pid, { graceMs: 250 }).catch(() => {});
+ return;
+ }
+ if (process.exitCode === null && process.signalCode === null) process.kill("SIGTERM");
+}
+
+export async function probeCursorAcpCatalog(
+ command?: string,
+ options: CursorAcpCatalogProbeOptions = {},
+): Promise<RuntimeReasoningCatalog | undefined> {
+ const cwd = options.cwd ?? process.cwd();
+ const spec = resolveSpawnSpec("cursor-agent", ["acp"], command);
+ let processHandle: SpawnedProcessHandle;
+ try {
+ processHandle = (options.spawn ?? spawnAgentProcess)(spec.command, spec.args, {
+ cwd,
+ env: { ...process.env, CI: "1" },
+ shell: spec.shell,
+ });
+ } catch {
+ return undefined;
+ }
+
+ return new Promise((resolve) => {
+ let settled = false;
+ let buffer = "";
+ let outputBytes = 0;
+ let requestId = 0;
+ let expectedId = 0;
+ let expectedMethod = "";
+ const finish = (catalog?: RuntimeReasoningCatalog) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ const cleanup = options.cleanup ?? cleanupProbeProcess;
+ void Promise.resolve().then(() => cleanup(processHandle)).catch(() => {}).finally(() => resolve(catalog));
+ };
+ const request = (method: string, params: JsonRecord) => {
+ if (settled) return;
+ const stdin = processHandle.stdin;
+ if (!stdin || stdin.destroyed || stdin.writableEnded || stdin.writable === false) return finish();
+ expectedId = ++requestId;
+ expectedMethod = method;
+ try {
+ stdin.write(`${jsonRpcRequest(method, params, expectedId)}\n`);
+ } catch {
+ finish();
+ }
+ };
+ const onLine = (line: string) => {
+ const parsed = tryParseJsonLine(line);
+ const message = record(parsed);
+ if (!message) return finish();
+ if (message.id !== expectedId) return;
+ if (message.error !== undefined) return finish();
+ if (!Object.prototype.hasOwnProperty.call(message, "result")) return finish();
+ if (expectedMethod === "authenticate") {
+ request("session/new", { cwd, mcpServers: [] });
+ return;
+ }
+ const result = record(message.result);
+ if (!result) return finish();
+ if (expectedMethod === "initialize") {
+ const authMethods = Array.isArray(result.authMethods) ? result.authMethods : [];
+ if (result.protocolVersion !== ACP_PROTOCOL_VERSION
+ || !authMethods.some((method) => record(method)?.id === AUTH_METHOD_ID)) return finish();
+ request("authenticate", { methodId: AUTH_METHOD_ID });
+ return;
+ }
+ if (expectedMethod !== "session/new"
+ || typeof result.sessionId !== "string"
+ || !result.sessionId.trim()) return finish();
+ finish(parseCursorAcpModelCatalog(result));
+ };
+
+ const timer = setTimeout(() => finish(), options.timeoutMs ?? CATALOG_PROBE_TIMEOUT_MS);
+ timer.unref?.();
+ processHandle.stdout?.on("data", (chunk) => {
+ if (settled) return;
+ const text = chunk.toString();
+ outputBytes += Buffer.byteLength(text);
+ if (outputBytes > (options.outputMaxBytes ?? CATALOG_PROBE_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);
+ });
+ processHandle.stderr?.on("data", (chunk) => {
+ if (settled) return;
+ outputBytes += Buffer.byteLength(chunk.toString());
+ if (outputBytes > (options.outputMaxBytes ?? CATALOG_PROBE_OUTPUT_MAX_BYTES)) finish();
+ });
+ processHandle.on("error", () => finish());
+ processHandle.on("exit", () => finish());
+ request("initialize", {
+ protocolVersion: ACP_PROTOCOL_VERSION,
+ clientCapabilities: {
+ fs: { readTextFile: false, writeTextFile: false },
+ terminal: false,
+ },
+ clientInfo: { name: "alook-agent-driver-probe", version: "0.1.25" },
+ });
+ });
+}
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 a34befee8..dca6d02db 100644
--- a/src/daemon/agent-driver/src/adapters/cursor/index.test.ts
+++ b/src/daemon/agent-driver/src/adapters/cursor/index.test.ts
@@ -104,7 +104,9 @@ interface FakeServer {
function installServer(options: {
sessionId?: string;
loadError?: string;
- modelOptions?: Array<{ value: string; name: string }>;
+ omitLoadSessionId?: boolean;
+ omitNewSessionId?: boolean;
+ modelOptions?: unknown[];
} = {}): FakeServer {
const messages: RpcMessage[] = [];
const prompts: RpcMessage[] = [];
@@ -124,19 +126,24 @@ function installServer(options: {
break;
case "session/new":
respond(process, message, {
- sessionId,
+ ...(options.omitNewSessionId ? {} : { sessionId }),
configOptions: options.modelOptions ? [{ id: "model", options: options.modelOptions }] : [],
});
break;
case "session/load":
if (options.loadError) fail(process, message, "Invalid params", { message: options.loadError });
else respond(process, message, {
- sessionId,
+ ...(options.omitLoadSessionId ? {} : { sessionId }),
configOptions: options.modelOptions ? [{ id: "model", options: options.modelOptions }] : [],
});
break;
case "session/set_config_option":
- respond(process, message, { configOptions: [] });
+ respond(process, message, {
+ configOptions: [{
+ id: "model",
+ currentValue: (message.params as { value?: unknown } | undefined)?.value,
+ }],
+ });
break;
case "session/prompt":
prompts.push(message);
@@ -187,28 +194,34 @@ 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",
+ it("uses the ACP session/new probe for a non-fatal startup catalog", async () => {
+ const catalogProbe = vi.fn(async () => ({
+ updateMode: "unsupported" as const,
+ models: [{
+ id: "grok-4.6[effort=high,fast=true]",
+ displayName: "grok-4.6",
+ supportedReasoningEfforts: [] as const,
+ }],
}));
- const result = new CursorDriver(outputProbe).probe(process.execPath);
+ const result = await new CursorDriver(catalogProbe).probe(process.execPath);
- expect(outputProbe).toHaveBeenCalledWith(process.execPath, ["--list-models"]);
- expect(result).toMatchObject({
+ expect(catalogProbe).toHaveBeenCalledWith(process.execPath);
+ expect(result).toEqual(expect.objectContaining({
status: "healthy",
reasoning: {
- models: [
- { id: "gpt-5.6-sol", supportedReasoningEfforts: [] },
- { id: "claude-opus", supportedReasoningEfforts: [] },
- ],
+ updateMode: "unsupported",
+ models: [{
+ id: "grok-4.6[effort=high,fast=true]",
+ displayName: "grok-4.6",
+ 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("keeps runtime health healthy when ACP catalog discovery fails", async () => {
+ await expect(new CursorDriver(async () => { throw new Error("ETIMEDOUT"); }).probe(process.execPath))
+ .resolves.toMatchObject({ status: "healthy", reasoning: undefined });
});
it("spawns cursor-agent acp once with piped stdin and performs the strict handshake before prompt", async () => {
@@ -285,6 +298,34 @@ describe("CursorDriver persistent ACP transport", () => {
expect(exits).toEqual([]);
});
+ it("keeps the requested id when a successful ACP session/load response does not echo it", async () => {
+ const server = installServer({
+ sessionId: "persistent-session",
+ omitLoadSessionId: true,
+ modelOptions: [{ value: "composer-2.5[fast=true]", name: "composer-2.5" }],
+ });
+ const lane = await new CursorDriver().openLane(baseCtx({ config: {
+ sessionId: "persistent-session",
+ runtimeConfig: { model: { kind: "named", name: "composer-2.5[fast=true]" } },
+ } }));
+ eventsFrom(lane);
+
+ await expect(lane.start({ text: "resume", sessionId: "persistent-session" })).resolves.toMatchObject({
+ ok: true,
+ });
+ expect(lane.currentSessionId).toBe("persistent-session");
+ expect(server.messages.map((message) => message.method)).toEqual([
+ "initialize",
+ "authenticate",
+ "session/load",
+ "session/set_config_option",
+ "session/prompt",
+ ]);
+ expect(server.messages.find((message) => message.method === "session/load")?.params).toMatchObject({
+ sessionId: "persistent-session",
+ });
+ });
+
it("rejects non-missing load failures, invalid new ids, and mismatched resumed ids", async () => {
installServer({ sessionId: "legacy", loadError: "Permission denied" });
const loadFailure = await new CursorDriver().openLane(baseCtx({ config: {
@@ -300,6 +341,11 @@ describe("CursorDriver persistent ACP transport", () => {
eventsFrom(invalid);
await expect(invalid.start({ text: "new" })).rejects.toThrow("valid session id");
+ installServer({ omitNewSessionId: true });
+ const missing = await new CursorDriver().openLane(baseCtx());
+ eventsFrom(missing);
+ await expect(missing.start({ text: "new" })).rejects.toThrow("valid session id");
+
installServer({ sessionId: "different" });
const mismatched = await new CursorDriver().openLane(baseCtx({ config: {
sessionId: "requested",
@@ -416,31 +462,37 @@ describe("CursorDriver persistent ACP transport", () => {
expect(messages.map((message) => message.method)).toEqual(["initialize"]);
});
- it("maps a configured model through ACP config options and fails closed when unavailable", async () => {
+ it("launches only an exact ACP option value and never maps its display name", async () => {
+ const exactValue = "gpt-5.6-sol[reasoning=medium]";
const server = installServer({
- modelOptions: [[{ value: "gpt-5.6-sol[reasoning=medium]", name: "gpt-5.6-sol" }]] as never,
+ modelOptions: [[{ value: exactValue, name: "gpt-5.6-sol" }]],
});
const lane = await new CursorDriver().openLane(baseCtx({
- config: { runtimeConfig: { model: { kind: "named", name: "gpt-5.6-sol" } } },
+ config: { runtimeConfig: { model: { kind: "named", name: exactValue } } },
}));
eventsFrom(lane);
await expect(lane.start({ text: "configured" })).resolves.toMatchObject({ ok: true });
expect(server.messages.find((message) => message.method === "session/set_config_option")?.params).toEqual({
sessionId: "cursor-acp-session",
configId: "model",
- value: "gpt-5.6-sol[reasoning=medium]",
+ value: exactValue,
});
+ expect(server.prompts).toHaveLength(1);
- installServer({ modelOptions: [{ value: "default[]", name: "Auto" }] });
- const incompatible = await new CursorDriver().openLane(baseCtx({
- config: { runtimeConfig: { model: { kind: "named", name: "missing-model" } } },
+ const bareNameServer = installServer({
+ modelOptions: [{ value: exactValue, name: "gpt-5.6-sol" }],
+ });
+ const bareName = await new CursorDriver().openLane(baseCtx({
+ config: { runtimeConfig: { model: { kind: "named", name: "gpt-5.6-sol" } } },
}));
- eventsFrom(incompatible);
- await expect(incompatible.start({ text: "configured" })).resolves.toMatchObject({
+ eventsFrom(bareName);
+ await expect(bareName.start({ text: "configured" })).resolves.toMatchObject({
ok: false,
reason: "incompatible_configuration",
- error: expect.stringContaining("missing-model"),
+ error: expect.stringContaining("gpt-5.6-sol"),
});
+ expect(bareNameServer.messages.some((message) => message.method === "session/set_config_option")).toBe(false);
+ expect(bareNameServer.prompts).toHaveLength(0);
});
it("fails closed when requested model configuration is absent or rejected", async () => {
@@ -455,7 +507,7 @@ describe("CursorDriver persistent ACP transport", () => {
error: expect.stringContaining("does not support model configuration"),
});
- installServer({ modelOptions: [{ value: "gpt-5.6-sol", name: "gpt-5.6-sol" }] });
+ const rejectedServer = installServer({ modelOptions: [{ value: "gpt-5.6-sol", name: "gpt-5.6-sol" }] });
const original = onClientMessage;
onClientMessage = (process, message) => {
if (message.method === "session/set_config_option") fail(process, message, "rejected");
@@ -470,6 +522,29 @@ describe("CursorDriver persistent ACP transport", () => {
reason: "incompatible_configuration",
error: expect.stringContaining("rejected model configuration"),
});
+ expect(rejectedServer.prompts).toHaveLength(0);
+ });
+
+ it.each([
+ { name: "missing", result: { configOptions: [] } },
+ { name: "mismatched", result: { configOptions: [{ id: "model", currentValue: "other-model" }] } },
+ ])("fails before prompt when set_config_option confirmation is $name", async ({ result }) => {
+ const server = installServer({ modelOptions: [{ value: "gpt-5.6-sol", name: "GPT" }] });
+ const original = onClientMessage;
+ onClientMessage = (process, message) => {
+ if (message.method === "session/set_config_option") respond(process, message, result);
+ else original(process, message);
+ };
+ const lane = await new CursorDriver().openLane(baseCtx({
+ config: { runtimeConfig: { model: { kind: "named", name: "gpt-5.6-sol" } } },
+ }));
+ eventsFrom(lane);
+ await expect(lane.start({ text: "must not prompt" })).resolves.toMatchObject({
+ ok: false,
+ reason: "incompatible_configuration",
+ error: expect.stringContaining("confirm"),
+ });
+ expect(server.prompts).toHaveLength(0);
});
it("settles malformed and failed prompt responses without leaking ownership", async () => {
diff --git a/src/daemon/agent-driver/src/adapters/cursor/index.ts b/src/daemon/agent-driver/src/adapters/cursor/index.ts
index 9a2246af1..94217044a 100644
--- a/src/daemon/agent-driver/src/adapters/cursor/index.ts
+++ b/src/daemon/agent-driver/src/adapters/cursor/index.ts
@@ -19,12 +19,11 @@ import { resolveLaunchFieldsOrDefault } from "../../internal/config.js";
import { spawnAgentProcess } from "../../internal/killTree.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";
+import { probeCursorAcpCatalog } from "./catalog-probe.js";
+import type { RuntimeReasoningCatalog } from "../../contract.js";
export class CursorDriver implements BackendAdapter, CursorAcpProcessFactory {
readonly id = "cursor";
@@ -37,17 +36,21 @@ export class CursorDriver implements BackendAdapter, CursorAcpProcessFactory {
} as const;
constructor(
- private readonly outputProbe: (command: string, args: string[]) => CommandOutputProbeResult = probeCommandOutput,
+ private readonly catalogProbe: (command?: string) => Promise<RuntimeReasoningCatalog | undefined> = probeCursorAcpCatalog,
) {}
- probe(command?: string) {
+ async probe(command?: string) {
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);
+ let reasoning: RuntimeReasoningCatalog | undefined;
+ try {
+ reasoning = await this.catalogProbe(command);
+ } catch {
+ reasoning = undefined;
+ }
return {
...result,
- reasoning: output.ok ? parseCursorModelCatalog(output.output) : undefined,
+ reasoning,
};
}
diff --git a/src/daemon/agent-driver/src/contract.ts b/src/daemon/agent-driver/src/contract.ts
index 879dfba65..558e69b6c 100644
--- a/src/daemon/agent-driver/src/contract.ts
+++ b/src/daemon/agent-driver/src/contract.ts
@@ -27,6 +27,7 @@ export type RuntimeReasoningCatalog = {
readonly defaultModelId?: string;
readonly models: readonly {
readonly id: string;
+ readonly displayName?: string;
readonly supportedReasoningEfforts: readonly {
readonly value: ReasoningEffort;
readonly description?: string;
diff --git a/src/daemon/agent-driver/src/internal/modelCatalog.test.ts b/src/daemon/agent-driver/src/internal/modelCatalog.test.ts
index 1a95e3d20..419f0d246 100644
--- a/src/daemon/agent-driver/src/internal/modelCatalog.test.ts
+++ b/src/daemon/agent-driver/src/internal/modelCatalog.test.ts
@@ -1,28 +1,15 @@
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 {
+function ids(catalog: ReturnType<typeof parseOpenCodeModelCatalog>): 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",
@@ -44,16 +31,11 @@ describe("runtime startup model catalog parsers", () => {
});
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}`,
@@ -63,7 +45,6 @@ describe("runtime startup model catalog parsers", () => {
(_, 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
index 5b925d612..f93cfce4c 100644
--- a/src/daemon/agent-driver/src/internal/modelCatalog.ts
+++ b/src/daemon/agent-driver/src/internal/modelCatalog.ts
@@ -24,15 +24,6 @@ function catalogFromIds(ids: Iterable<string>): RuntimeReasoningCatalog | undefi
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) => {
diff --git a/src/shared/src/runtime-config.ts b/src/shared/src/runtime-config.ts
index 7621e5537..f169afad2 100644
--- a/src/shared/src/runtime-config.ts
+++ b/src/shared/src/runtime-config.ts
@@ -49,6 +49,7 @@ export type RuntimeReasoningCatalog = {
readonly defaultModelId?: string;
readonly models: readonly {
readonly id: string;
+ readonly displayName?: string;
readonly supportedReasoningEfforts: readonly ReasoningEffortOption[];
readonly defaultReasoningEffort?: ReasoningEffort;
}[];
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index e4aecb867..dfecc5057 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -852,6 +852,7 @@ const RuntimeReasoningOptionSchema = z.object({
const RuntimeReasoningModelSchema = z.object({
id: z.string().min(1).max(100),
+ displayName: z.string().min(1).max(COMMUNITY_REASONING_DESCRIPTION_MAX).optional().catch(undefined),
supportedReasoningEfforts: z
.array(z.unknown())
.max(COMMUNITY_REASONING_OPTIONS_MAX)
diff --git a/src/shared/test/queries/community-bot.test.ts b/src/shared/test/queries/community-bot.test.ts
index b4aeb3e0e..d03d6fbaf 100644
--- a/src/shared/test/queries/community-bot.test.ts
+++ b/src/shared/test/queries/community-bot.test.ts
@@ -366,6 +366,24 @@ describe("updateBotRuntimeConfig", () => {
}
})
+ it("persists a parameterized ACP model value byte-for-byte", async () => {
+ const { sqlite, db } = createDatabase()
+ const exactValue = "grok-4.6[effort=high,fast=true]"
+ try {
+ await expect(q.updateBotRuntimeConfig(db as never, "bot_1", "owner_1", {
+ runtime: "cursor",
+ modelName: exactValue,
+ reasoningEffort: null,
+ })).resolves.toEqual({ runtimeConfigRevision: 5 })
+ expect(sqlite.prepare(`
+ SELECT runtime, model_name AS modelName
+ FROM community_bot_binding WHERE user_id = 'bot_1'
+ `).get()).toEqual({ runtime: "cursor", modelName: exactValue })
+ } finally {
+ sqlite.close()
+ }
+ })
+
it("does not change the tuple or revision for a different owner", async () => {
const { sqlite, db } = createDatabase()
try {
diff --git a/src/shared/test/schemas/community-runtime.test.ts b/src/shared/test/schemas/community-runtime.test.ts
index ab7af4464..cb9e74174 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_DESCRIPTION_MAX,
COMMUNITY_REASONING_MODELS_MAX,
} from "../../src/schemas";
@@ -139,6 +140,41 @@ describe("CommunityMachineRuntimeSchema", () => {
expect(parsed.reasoning?.models[0]?.defaultReasoningEffort).toBe("medium");
});
+ it("preserves a bounded model display label and drops only a malformed label", () => {
+ const parsed = CommunityMachineRuntimeSchema.parse({
+ id: "cursor",
+ reasoning: {
+ updateMode: "unsupported",
+ models: [
+ {
+ id: "grok-4.6[effort=high,fast=true]",
+ displayName: "grok-4.6",
+ supportedReasoningEfforts: [],
+ },
+ {
+ id: "grok-4.6[effort=max,fast=true]",
+ displayName: "x".repeat(COMMUNITY_REASONING_DESCRIPTION_MAX + 1),
+ supportedReasoningEfforts: [],
+ },
+ { id: "legacy-wire-model", supportedReasoningEfforts: [] },
+ ],
+ },
+ });
+
+ expect(parsed.reasoning?.models).toEqual([
+ {
+ id: "grok-4.6[effort=high,fast=true]",
+ displayName: "grok-4.6",
+ supportedReasoningEfforts: [],
+ },
+ {
+ id: "grok-4.6[effort=max,fast=true]",
+ supportedReasoningEfforts: [],
+ },
+ { id: "legacy-wire-model", supportedReasoningEfforts: [] },
+ ]);
+ });
+
it("drops a malformed reasoning catalog without poisoning runtime health", () => {
expect(CommunityMachineRuntimeSchema.parse({
id: "codex",
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 e3a0e1d1e..2ed250ff0 100644
--- a/src/web/src/components/community/bots/model-field.test.ts
+++ b/src/web/src/components/community/bots/model-field.test.ts
@@ -11,12 +11,13 @@ const selectCalls: Array<{
value: string
onValueChange: (v: string | null) => void
onOpenChange?: (open: boolean) => void
+ items?: Array<{ value: string; label: string }>
}> = []
vi.mock("@/components/ui/select", () => {
const React = require("react")
return {
- Select: ({ value, onValueChange, onOpenChange, children }: any) => {
- selectCalls.push({ value, onValueChange, onOpenChange })
+ Select: ({ value, onValueChange, onOpenChange, items, children }: any) => {
+ selectCalls.push({ value, onValueChange, onOpenChange, items })
return React.createElement("div", { "data-mock": "select", "data-value": value }, children)
},
SelectTrigger: ({ children, ...props }: any) =>
@@ -49,6 +50,16 @@ function itemValues(renderer: TestRenderer.ReactTestRenderer): string[] {
.map((n) => n.props["data-value"] as string)
}
+function itemText(renderer: TestRenderer.ReactTestRenderer, value: string): string {
+ const item = renderer.root.find(
+ (node) => node.props?.["data-mock"] === "item" && node.props?.["data-value"] === value,
+ )
+ const visit = (node: TestRenderer.ReactTestInstance | string): string => typeof node === "string"
+ ? node
+ : node.children.map((child) => visit(child as TestRenderer.ReactTestInstance | string)).join("")
+ return visit(item)
+}
+
function render(props: {
runtime: Pick<CommunityMachineRuntime, "id" | "reasoning"> | null
value: string | null
@@ -72,6 +83,14 @@ describe("ModelField", () => {
},
})
+ const labeledRuntime = (models: Array<{ id: string; displayName?: string }>) => ({
+ id: "cursor",
+ reasoning: {
+ updateMode: "unsupported" as const,
+ models: models.map((model) => ({ ...model, supportedReasoningEfforts: [] })),
+ },
+ })
+
it("renders exactly Default + aliases + Custom… for Claude's reported catalog", () => {
const values = itemValues(render({
runtime: runtime("claude", ["opus", "sonnet", "haiku"]),
@@ -143,6 +162,41 @@ describe("ModelField", () => {
expect(onChange).toHaveBeenLastCalledWith(null)
})
+ it("keeps same-name ACP values distinct in rows, trigger labels, filtering, and onChange", () => {
+ const high = "grok-4.6[effort=high,fast=true]"
+ const max = "grok-4.6[effort=max,fast=true]"
+ const onChange = vi.fn()
+ selectCalls.length = 0
+ const renderer = render({
+ runtime: labeledRuntime([
+ { id: high, displayName: "grok-4.6" },
+ { id: max, displayName: "grok-4.6" },
+ ]),
+ value: high,
+ onChange,
+ })
+
+ expect(itemValues(renderer)).toEqual(["__default__", "__custom__", high, max])
+ expect(itemText(renderer, high)).toContain("grok-4.6")
+ expect(itemText(renderer, high)).toContain(high)
+ expect(itemText(renderer, max)).toContain(max)
+ expect(selectCalls.at(-1)?.items).toEqual(expect.arrayContaining([
+ { value: high, label: `${high} — grok-4.6` },
+ { value: max, label: `${max} — grok-4.6` },
+ ]))
+
+ act(() => selectCalls.at(-1)!.onValueChange(max))
+ expect(onChange).toHaveBeenLastCalledWith(max)
+ act(() => selectCalls.at(-1)!.onValueChange(high))
+ expect(onChange).toHaveBeenLastCalledWith(high)
+
+ const filter = renderer.root.findByProps({ "data-testid": "bot-model-filter-input" })
+ act(() => filter.props.onChange({ target: { value: "EFFORT=MAX" } }))
+ expect(itemValues(renderer)).toEqual(["__default__", "__custom__", max])
+ act(() => filter.props.onChange({ target: { value: "GROK-4.6" } }))
+ expect(itemValues(renderer)).toEqual(["__default__", "__custom__", high, max])
+ })
+
it("Custom… reveals the input; typing emits the raw string; clearing emits null", () => {
const onChange = vi.fn()
selectCalls.length = 0
diff --git a/src/web/src/components/community/bots/model-field.tsx b/src/web/src/components/community/bots/model-field.tsx
index 69ea7ef21..545990223 100644
--- a/src/web/src/components/community/bots/model-field.tsx
+++ b/src/web/src/components/community/bots/model-field.tsx
@@ -43,12 +43,12 @@ export function ModelField({
onChange: (v: string | null) => void
disabled?: boolean
}) {
- const modelIds = useMemo(
+ const models = useMemo(
() => runtime?.reasoning?.models
- .map((model) => model.id)
- .filter((id) => id !== MODEL_SELECT_DEFAULT && id !== MODEL_SELECT_CUSTOM) ?? [],
+ .filter((model) => model.id !== MODEL_SELECT_DEFAULT && model.id !== MODEL_SELECT_CUSTOM) ?? [],
[runtime],
)
+ const modelIds = useMemo(() => models.map((model) => model.id), [models])
const seed = useMemo(() => modelSelectState(modelIds, value), [modelIds, value])
const [selectValue, setSelectValue] = useState(seed.selectValue)
@@ -67,9 +67,10 @@ export function ModelField({
const isCustom = selectValue === MODEL_SELECT_CUSTOM
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
+ const filteredModels = normalizedFilter
+ ? models.filter((model) => model.id.toLowerCase().includes(normalizedFilter)
+ || model.displayName?.toLowerCase().includes(normalizedFilter))
+ : models
// Base UI resolves the collapsed-trigger label from `items` (value → label).
// Without it, SelectValue renders the raw value — fine for catalog ids
@@ -78,7 +79,12 @@ export function ModelField({
const items = [
{ value: MODEL_SELECT_DEFAULT, label: defaultLabel },
{ value: MODEL_SELECT_CUSTOM, label: "Custom…" },
- ...modelIds.map((model) => ({ value: model, label: model })),
+ ...models.map((model) => ({
+ value: model.id,
+ label: model.displayName && model.displayName !== model.id
+ ? `${model.id} — ${model.displayName}`
+ : model.id,
+ })),
]
return (
@@ -150,12 +156,21 @@ export function ModelField({
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>
+ {filteredModels.map((model) => (
+ <SelectItem key={model.id} value={model.id}>
+ {model.displayName && model.displayName !== model.id ? (
+ <div className="flex min-w-0 flex-col items-start gap-0.5">
+ <span>{model.displayName}</span>
+ <span className="max-w-full break-all whitespace-normal font-mono text-xs text-muted-foreground">
+ {model.id}
+ </span>
+ </div>
+ ) : (
+ <span className="font-mono">{model.id}</span>
+ )}
</SelectItem>
))}
- {normalizedFilter && filteredModelIds.length === 0 ? (
+ {normalizedFilter && filteredModels.length === 0 ? (
<p role="status" className="px-2 py-2 text-xs text-muted-foreground">
No matching models
</p>