Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix model catalog matching for routed ids

aurorax-neof63431936322
diff --git a/apps/desktop/electron/main/models-dev-catalog.ts b/apps/desktop/electron/main/models-dev-catalog.ts
index 972db9c10..8788b9fe9 100644
--- a/apps/desktop/electron/main/models-dev-catalog.ts
+++ b/apps/desktop/electron/main/models-dev-catalog.ts
@@ -899,56 +899,13 @@ class ModelsDevLookupIndex {
}
}
-/** Index only aliases the matcher can accept: exact IDs, the region-stripped
- * form, full slash-path leaves, known-vendor dash/dot prefixes, the supported
- * thinking/agent/latest variants, and published release stamps. The matcher
- * remains the final authority (including known-vendor conflicts), but the index
- * must register every alias the matcher accepts: a key it never indexed is a
- * lookup that can never reach the record. */
+/** Generate the exact lowercase last `/`-segment used by the catalog matcher. */
function candidateKeys(modelId: string): string[] {
const normalized = normalizedModelId(modelId);
if (!normalized) return [];
- const keys = new Set<string>();
- const at = normalized.indexOf("@");
- const base = at > 0 ? normalized.slice(0, at) : normalized;
-
- const add = (value: string) => {
- if (!value) return;
- keys.add(value);
- const slash = value.lastIndexOf("/");
- if (slash >= 0 && slash < value.length - 1) keys.add(value.slice(slash + 1));
- for (const separator of ["-", "."] as const) {
- for (const vendor of MODEL_VENDOR_PREFIXES) {
- const head = `${vendor}${separator}`;
- if (value.startsWith(head) && value.length > head.length) {
- keys.add(value.slice(head.length));
- }
- }
- }
- };
-
- /*
- Suffixes are stripped after the region, just as `catalogModelIdsMatch`
- does, and either suffix may be the outer one: `foo-0731-thinking` and
- `foo-thinking-0731` both reach `foo`. Aliases are added from both sides so a
- suffixed catalog id and a suffixed request each find the other.
- */
- const variants = new Set<string>();
- for (const value of [normalized, base]) {
- const withoutVariant = stripVariantSuffix(value);
- const withoutRelease = stripReleaseSuffix(value);
- for (const variant of [
- value,
- withoutVariant,
- withoutRelease,
- stripReleaseSuffix(withoutVariant),
- stripVariantSuffix(withoutRelease),
- ]) {
- variants.add(variant);
- }
- }
- for (const value of variants) add(value);
- return [...keys];
+ const slash = normalized.lastIndexOf("/");
+ const leaf = slash >= 0 ? normalized.slice(slash + 1) : normalized;
+ return leaf ? [leaf] : [];
}
function registrationKeys(modelId: string): string[] {
@@ -961,7 +918,54 @@ function lookupCandidateKeys(requested: string): string[] {
const EMPTY_CANDIDATES: readonly IndexedModel[] = [];
+type OfficialProviderFamily = "anthropic" | "openai" | "google" | "xai";
+
+const OFFICIAL_PROVIDER_FAMILIES: Readonly<Record<string, OfficialProviderFamily>> = {
+ anthropic: "anthropic",
+ openai: "openai",
+ google: "google",
+ "google-ai-studio": "google",
+ "google-vertex": "google",
+ xai: "xai",
+ "x-ai": "xai",
+};
+
+function explicitModelSourceFamily(modelId: string): OfficialProviderFamily | undefined {
+ const firstSegment = normalizedModelId(modelId).split("/", 1)[0];
+ return OFFICIAL_PROVIDER_FAMILIES[firstSegment];
+}
+
+function isOfficialSourceProvider(entry: IndexedModel): boolean {
+ const providerFamily = OFFICIAL_PROVIDER_FAMILIES[normalizedProviderKey(entry.provider.providerKey)];
+ if (!providerFamily) return false;
+ const explicitSource = explicitModelSourceFamily(entry.model.modelId);
+ return !explicitSource || explicitSource === providerFamily;
+}
+function capabilitySignature(model: ModelsDevModel): string {
+ return JSON.stringify({
+ attachment: model.attachment ?? null,
+ temperature: model.temperature ?? null,
+ toolCall: model.toolCall ?? null,
+ structuredOutput: model.structuredOutput ?? null,
+ modalities: {
+ input: [...model.modalities.input].sort(),
+ output: [...model.modalities.output].sort(),
+ },
+ reasoning: model.reasoning,
+ reasoningOptions: model.reasoningOptions ?? null,
+ thinkingLevels: model.thinkingLevels,
+ });
+}
+
+function modelWithSharedCapabilities(
+ entries: readonly ModelsDevModel[],
+): ModelsDevModel | undefined {
+ if (entries.length === 0) return undefined;
+ const signature = capabilitySignature(entries[0]);
+ if (entries.some((model) => capabilitySignature(model) !== signature)) return undefined;
+ return borrowedModel(entries);
+}
/**
* Middle value of the numbers the publishers state. Even counts take the lower
@@ -1415,12 +1419,7 @@ export class ModelsDevCatalog {
for (const entry of this.lookupIndex.candidates(requested)) {
(entry.provider === preferredProvider ? preferred : rest).push(entry);
}
- const candidates: Array<{
- model: ModelsDevModel;
- provider: ModelsDevProvider;
- score: number;
- exact: boolean;
- }> = [];
+ const candidates: Array<{ model: ModelsDevModel; provider: ModelsDevProvider; score: number }> = [];
for (const { model, provider } of [...preferred, ...rest]) {
// A known endpoint must not inherit another provider's capabilities.
if (preferredProvider && provider !== preferredProvider) continue;
@@ -1430,36 +1429,19 @@ export class ModelsDevCatalog {
if (provider === preferredProvider) score += 100;
if (apiMatches(input.baseUrl, provider.api)) score += 80;
if (modelMatchesProvider(model, input.vendorKey)) score += 60;
- candidates.push({ model, provider, score, exact });
+ candidates.push({ model, provider, score });
}
candidates.sort((left, right) =>
right.score - left.score || left.model.modelId.length - right.model.modelId.length,
);
- /*
- /*
- A record the catalog publishes under exactly this id is this id's record.
- Supported aliases — a release stamp, a thinking variant, a route leaf —
- also reach a *shorter* sibling, and answering with that sibling would
- attach another deployment's limits and capabilities to the row. So exact
- candidates discard the alias-derived ones before the ambiguity test, which
- is what keeps `foo-v2-0731` on its own record while a catalog that only
- publishes `foo-v2` still answers it.
- */
- const exactCandidates = candidates.filter((candidate) => candidate.exact);
- const pool = exactCandidates.length > 0 ? exactCandidates : candidates;
- /* Within the row's own catalog provider this is an exact-provider lookup:
- the provider identity is known, so its record for the id — a direct hit
- or a supported alias — is authoritative.
-
- With no provider identity the scores prove nothing about identity, so a
- catalog answer is only usable when it is unambiguous — and only over the
- alias-derived pool, since an exact record already outranks its aliases.
- Two providers publishing the same id must not have one chosen for the
- other. */
- const resolved = pool[0]?.model;
- const result = preferredProvider
- ? resolved
- : pool.length === 1 ? resolved : undefined;
+ // 0 → unmatched; 1 → enrich; ≥2 prefer unique official/source provider
+ // agreeing with model source; else shared identical capabilities; else unmatched.
+ const official = candidates.filter(isOfficialSourceProvider);
+ const result = candidates.length === 1
+ ? candidates[0].model
+ : official.length === 1
+ ? official[0].model
+ : modelWithSharedCapabilities(candidates.map(({ model }) => model));
/* The row's own catalog provider did not publish this id. Borrowing needs a
known provider identity to anchor on: the row resolved to a catalog
provider whose own records are authoritative, so anything missing from it
@@ -1467,40 +1449,13 @@ export class ModelsDevCatalog {
dropping the model to the generic shape.
This only fills a miss the lookup already had — a record the preferred
- provider does publish stays authoritative.
-
- With no provider identity at all the scores still prove nothing about
- identity, so no single publisher's record is adopted. What the publishers
- of the *same model in another spelling* state is a different question, and
- its answer can be claimed without adopting any one deployment's claims:
- the publishers this app ships answer first, tool support follows the ones
- that state it, capabilities are under-claimed and the limits are the lower
- median. Two routes that merely share a leaf (`provider-a/foo` vs
- `gateway/foo`) never enter that set, so an id whose identity is genuinely
- unknown still resolves to nothing. */
- let borrowed = result ??
- (preferredProvider
- ? this.borrowedAcrossProviders(input)
- : unanchoredConsensus(
- borrowPool(
- candidates.filter((candidate) => sameModelSpelling(candidate.model.modelId, requested)),
- requested,
- ),
- ));
- /*
- Nothing the catalog publishes answered for the id as served. A deployment
- can put the model behind a route prefix or append a marker of its own
- (`test/mimo-v2.5`, `mimo-v2.5-pro-test`), and the model is still the one
- the catalog publishes. Reading that whole published id is the last resort,
- so a suffix the catalog uses for models of its own — `-asr`, `-tts`,
- `-voiceclone` — cannot turn an unknown id into a different model's record.
- */
- if (!borrowed) {
- for (const fallbackId of fallbackLookupIds(requested)) {
- borrowed = this.borrowedAcrossProviders(input, fallbackId);
- if (borrowed) break;
- }
- }
+ provider does publish stays authoritative. Without that anchor the scores
+ prove nothing about identity, and an unknown endpoint keeps the existing
+ behaviour: a unique unambiguous match, official disambiguation, shared
+ capabilities, or nothing. Deployment-marker / variant-suffix fallbacks
+ are intentionally not applied here (approved #1047 matching rules). */
+ const borrowed = result ??
+ (preferredProvider ? this.borrowedAcrossProviders(input) : undefined);
// Cache the result (a miss included) so a repeated miss is also O(1) and
// cannot grow the candidate index with query-dependent keys.
this.lookupMemo.set(memoKey, borrowed);
diff --git a/apps/desktop/electron/main/plugin-mcp.ts b/apps/desktop/electron/main/plugin-mcp.ts
index 66d543ea1..7a482184a 100644
--- a/apps/desktop/electron/main/plugin-mcp.ts
+++ b/apps/desktop/electron/main/plugin-mcp.ts
@@ -173,6 +173,7 @@ function createStdioTransport(
cwd: options.rootPath,
env: launch.env,
stdio: ["pipe", "pipe", "pipe"],
+ detached: process.platform !== "win32",
// Arguments stay literal. Known launchers rewrite to a PE binary; remaining
// Windows `.cmd` shims go through `cmd.exe /d /s /c` with quoted args.
shell: false,
@@ -183,14 +184,36 @@ function createStdioTransport(
let closed = false;
let buffer = "";
let lastStderr = "";
+ let forceKillTimer: ReturnType<typeof setTimeout> | undefined;
+ const signalChildTree = (signal: NodeJS.Signals = "SIGTERM") => {
+ if (process.platform !== "win32" && child.pid) {
+ try {
+ process.kill(-child.pid, signal);
+ return;
+ } catch {
+ // The process group may already be gone; fall back to the direct child.
+ }
+ }
+ child.kill(signal);
+ };
+
+ const stopChild = () => {
+ closed = true;
+ child.stdin?.destroy();
+ child.stdout?.destroy();
+ child.stderr?.destroy();
+ signalChildTree();
+ forceKillTimer ??= setTimeout(() => signalChildTree("SIGKILL"), 1_000);
+ forceKillTimer.unref?.();
+ };
child.stdout?.setEncoding("utf8");
child.stdout?.on("data", (chunk: string) => {
buffer += chunk;
if (buffer.length > MAX_STDIO_LINE_BYTES) {
buffer = "";
handlers.onClose("mcp server sent an oversized message");
- child.kill();
+ stopChild();
return;
}
let index = buffer.indexOf("\n");
@@ -240,10 +263,7 @@ function createStdioTransport(
}
child.stdin.write(`${JSON.stringify(message)}\n`);
},
- close: () => {
- closed = true;
- child.kill();
- },
+ close: stopChild,
};
}
diff --git a/apps/desktop/src/features/chat/composer/model.ts b/apps/desktop/src/features/chat/composer/model.ts
index 718110e4d..a38f71e40 100644
--- a/apps/desktop/src/features/chat/composer/model.ts
+++ b/apps/desktop/src/features/chat/composer/model.ts
@@ -127,14 +127,28 @@ export function thinkingProviderForModel(
): ProviderPublic | null | undefined {
if (!provider || !modelId) return provider;
const model = modelCatalog?.find((candidate) => sameComposerModelId(candidate.modelId, modelId));
- if (!model) return provider;
const binding = provider.models.find((candidate) =>
- sameComposerModelId(candidate.id, model.modelId),
+ sameComposerModelId(candidate.id, modelId),
);
const configuredLevels = binding
? THINKING_LEVELS.filter((level) => binding.thinkingLevels.includes(level))
: undefined;
+
+ if (!model) {
+ // No catalog match: all thinking levels selectable, default off.
+ // A binding override still takes precedence when present.
+ const supportsReasoning = configuredLevels
+ ? configuredLevels.some((level) => level !== "off")
+ : true;
+ return {
+ ...provider,
+ supportsReasoning,
+ supportedThinkingLevels:
+ configuredLevels ?? [...THINKING_LEVELS],
+ };
+ }
+
const supportsReasoning = configuredLevels
? configuredLevels.some((level) => level !== "off")
: model.reasoning === true || model.capabilities.includes("reasoning");
diff --git a/apps/desktop/src/lib/composer-models.ts b/apps/desktop/src/lib/composer-models.ts
index 8f1289ed0..44bb8bdc2 100644
--- a/apps/desktop/src/lib/composer-models.ts
+++ b/apps/desktop/src/lib/composer-models.ts
@@ -43,7 +43,7 @@ export function composerModelsForProvider(
const metadata = (discovered ?? []).find((model) =>
sameComposerModelId(model.modelId, modelId),
);
- const displayName = metadata?.displayName?.trim() || modelId;
+ const displayName = modelId;
return metadata
? { ...metadata, modelId, displayName, providerId: provider.id }
: {
@@ -56,7 +56,7 @@ export function composerModelsForProvider(
});
}
-/** The Composer uses the configured alias, then published name, then wire id. */
+/** The Composer uses the configured alias when set, otherwise the wire id. */
export function composerModelDisplayName(
provider: ConfiguredProvider | undefined,
modelId: string,
diff --git a/apps/desktop/test/composer-model-thinking-menu.test.mjs b/apps/desktop/test/composer-model-thinking-menu.test.mjs
index 53d96fa0a..022f12838 100644
--- a/apps/desktop/test/composer-model-thinking-menu.test.mjs
+++ b/apps/desktop/test/composer-model-thinking-menu.test.mjs
@@ -153,7 +153,7 @@ test("Composer uses alias labels while preserving the exact selected wire id", a
test("reasoning projection uses the selected exact catalog row and binding", async () => {
const source = await readComposerModule("model.ts");
assert.match(source, /sameComposerModelId\(candidate\.modelId, modelId\)/);
- assert.match(source, /sameComposerModelId\(candidate\.id, model\.modelId\)/);
+ assert.match(source, /sameComposerModelId\(candidate\.id, modelId\)/);
});
test("a model row spends the panel's width instead of stacking at its left edge", () => {
diff --git a/apps/desktop/test/composer-models.test.mjs b/apps/desktop/test/composer-models.test.mjs
index 757c0f495..1d55fcc41 100644
--- a/apps/desktop/test/composer-models.test.mjs
+++ b/apps/desktop/test/composer-models.test.mjs
@@ -42,8 +42,8 @@ test("Composer only lists models configured for the provider", () => {
assert.deepEqual(
models.map(({ modelId, displayName }) => ({ modelId, displayName })),
[
- { modelId: "claude-opus-4-6", displayName: "Claude Opus 4.6" },
- { modelId: "x-ai/grok-4.6", displayName: "Grok 4.6" },
+ { modelId: "claude-opus-4-6", displayName: "claude-opus-4-6" },
+ { modelId: "x-ai/grok-4.6", displayName: "x-ai/grok-4.6" },
],
);
});
@@ -78,10 +78,10 @@ test("legacy providers fall back to their default model binding", () => {
);
assert.deepEqual(models.map((item) => item.modelId), ["legacy-model"]);
- assert.equal(models[0].displayName, "Legacy model");
+ assert.equal(models[0].displayName, "legacy-model");
});
-test("a configured alias labels its row without losing the published name", () => {
+test("a configured alias labels its row while displayName shows the wire id", () => {
const provider = {
id: "deepseek",
models: [{ ...binding("deepseek-v4-pro"), alias: " pro " }],
@@ -92,10 +92,10 @@ test("a configured alias labels its row without losing the published name", () =
);
assert.equal(models[0].modelId, "deepseek-v4-pro");
- assert.equal(models[0].displayName, "DeepSeek V4 Pro");
+ assert.equal(models[0].displayName, "deepseek-v4-pro");
assert.equal(composerModelDisplayName(provider, "deepseek-v4-pro", models[0].displayName), "pro");
assert.equal(composerModelMatchesQuery(models[0], "provider", "PRO", "pro"), true);
- assert.equal(composerModelMatchesQuery(models[0], "provider", "DeepSeek V4 Pro", "pro"), true);
+ assert.equal(composerModelMatchesQuery(models[0], "provider", "DeepSeek V4 Pro", "pro"), false);
});
test("a configured alias is visible before discovery data is available", () => {
const provider = {
@@ -140,7 +140,7 @@ test("an exact binding alias wins over a broader equivalent id match", () => {
);
});
-test("a blank alias leaves the published display name alone", () => {
+test("a blank alias leaves the wire id as display name", () => {
const models = composerModelsForProvider(
{
id: "deepseek",
@@ -149,14 +149,14 @@ test("a blank alias leaves the published display name alone", () => {
[model("deepseek-v4-pro", "DeepSeek V4 Pro")],
);
- assert.equal(models[0].displayName, "DeepSeek V4 Pro");
+ assert.equal(models[0].displayName, "deepseek-v4-pro");
assert.equal(
composerModelDisplayName(
{ id: "deepseek", models: [{ ...binding("deepseek-v4-pro"), alias: " " }] },
"deepseek-v4-pro",
- "DeepSeek V4 Pro",
+ "deepseek-v4-pro",
),
- "DeepSeek V4 Pro",
+ "deepseek-v4-pro",
);
});
@@ -248,8 +248,8 @@ test("prefixed and unprefixed wire ids remain separate even with one catalog nam
{ ...model("proxy/model", "Friendly"), capabilities: ["text", "vision"] },
]);
assert.deepEqual(rows.map(({ modelId, displayName }) => [modelId, displayName]), [
- ["proxy/model", "Friendly"],
- ["model", "Friendly"],
+ ["proxy/model", "proxy/model"],
+ ["model", "model"],
]);
assert.equal(composerModelDisplayName(provider, "proxy/model", rows[0].displayName), "Short");
assert.equal(composerModelMatchesQuery(rows[0], "relay", "Short", "Short"), true);
diff --git a/apps/desktop/test/models-dev-catalog.test.mjs b/apps/desktop/test/models-dev-catalog.test.mjs
index f4e62986c..0b721f0f8 100644
--- a/apps/desktop/test/models-dev-catalog.test.mjs
+++ b/apps/desktop/test/models-dev-catalog.test.mjs
@@ -216,12 +216,12 @@ test("an unknown endpoint borrows only what every publisher of the id agrees on"
}
});
-test("an unknown endpoint can use a unique supported proxy alias", async (t) => {
+test("an unknown endpoint can use a unique exact last-segment match", async (t) => {
const catalog = await loadFixtureCatalog(t, {
alpha: { models: { "shared-model": { id: "shared-model", reasoning: true } } },
});
assert.equal(catalog.findModel({
- vendorKey: "custom", baseUrl: "https://relay.example/v1", modelId: "proxy/shared-model-thinking",
+ vendorKey: "custom", baseUrl: "https://relay.example/v1", modelId: "proxy/shared-model",
})?.providerKey, "alpha");
});
@@ -337,111 +337,170 @@ test("model IDs match provider namespaces without matching model variants", () =
assert.equal(modelIdsMatch("proxy/openai/gpt-4o", "openai/gpt-4o"), true);
assert.equal(modelIdsMatch("openai/gpt-4o", "proxy/gpt-4o"), false);
});
-test("catalog metadata IDs match exact proxy paths and supported variants", () => {
+test("catalog metadata IDs match only exact case-insensitive last segments", () => {
for (const [catalogId, request] of [
["claude-opus-4.6", "proxy/claude-opus-4.6"],
- ["claude-opus-4.6", "custom/claude-opus-4.6"],
- ["claude-opus-4.6", "relay/claude-opus-4.6"],
- ["claude-opus-4.6", "gateway-01/claude-opus-4.6"],
- ["openai/gpt-4o", "hub/openai/gpt-4o"],
- ["claude-opus-4.6", "proxy/claude-opus-4.6-thinking"],
- ["claude-opus-4.6", "claude-opus-4.6:thinking"],
- ["claude-opus-4.6", "proxy/claude-opus-4.6-agent"],
- ["claude-opus-4.6", "proxy/claude-opus-4.6-latest"],
- ["claude-opus-4.6", "proxy/claude-opus-4.6-agent-thinking"],
- ["proxy/nested/claude-opus-4.6@us-east", "claude-opus-4.6-thinking"],
- ["anthropic-claude-opus-4.6", "claude-opus-4.6@us-east"],
- ["google/gemini-pro-latest", "gemini-pro"],
+ ["openai/gpt-4o", "hub/gpt-4o"],
+ ["google/gemini-2.5-flash", "openai/gemini-2.5-flash"],
+ ["proxy/nested/claude-opus-4.6", "other/CLAUDE-OPUS-4.6"],
+ ["gateway-a/foo", "gateway-b/foo"],
]) {
assert.equal(catalogModelIdsMatch(catalogId, request), true, `${catalogId} / ${request}`);
assert.equal(catalogModelIdsMatch(request, catalogId), true, `${request} / ${catalogId}`);
}
for (const [catalogId, request] of [
- ["google/gemini-2.5-flash", "openai/gemini-2.5-flash"],
- ["claude-opus-4.6", "myproxy-claude-opus-4.6"],
- ["claude-opus-4.6", "myproxy-claude-opus-4.6-thinking"],
- ["google/gemini-2.5-flash", "gemini-2.5-flash-high"],
- ["google/gemini-2.5-flash", "gemini-2.5-flash-low"],
- ["google/gemini-2.5-flash", "gemini-2.5-flash:minimal"],
- ["claude-opus-5", "claude-opus-5-fast"],
- ["gpt-4o", "gpt-4o-mini"],
- ["gpt-4", "gpt-4o"],
- ["model", "other-model"],
- ["custom", "gemini-3.1-pro-preview-customtools"],
- ["groq/whisper-large-v3", "deepseek-v3"],
- ["vercel/bfl/flux-kontext-max", "qwen-max"],
- ["alibaba/qwen3-asr-flash", "qwen-flash"],
- ["openai/gpt-4o", "proxy/gpt-4o"],
- ["google/gemini-2.5-flash", "proxy/gemini-2.5-flash"],
- ["proxy/nested/claude-opus-4.6", "other/claude-opus-4.6"],
- ["claude-opus-4-6-max", "qwen-max"],
+ ["claude-opus-4.6", "proxy/claude-opus-4.6-thinking"],
+ ["claude-opus-4.6", "claude-opus-4.6:thinking"],
+ ["claude-opus-4.6", "proxy/claude-opus-4.6-agent"],
+ ["claude-opus-4.6", "proxy/claude-opus-4.6-latest"],
+ ["anthropic-claude-opus-4.6", "claude-opus-4.6"],
+ ["google/gemini-pro-latest", "ag/gemini-pro-agent"],
+ ["foo", "foo-think"],
+ ["foo", "foo-agent"],
+ ["foo", "foo-latest"],
+ ["foo@us-east", "foo"],
]) {
assert.equal(catalogModelIdsMatch(catalogId, request), false, `${catalogId} / ${request}`);
assert.equal(catalogModelIdsMatch(request, catalogId), false, `${request} / ${catalogId}`);
}
- assert.equal(catalogModelIdsMatch("gateway-a/foo", "gateway-b/foo"), false);
- assert.equal(catalogModelIdsMatch("foo", "foo-think"), true);
- assert.equal(catalogModelIdsMatch("foo", "foo-agent"), true);
- assert.equal(catalogModelIdsMatch("foo", "foo-latest"), true);
});
-test("catalog lookup indexes exact path leaves and known vendor variants without broad aliases", async (t) => {
- const ids = [
- "model", "custom", "groq/whisper-large-v3", "vercel/bfl/flux-kontext-max",
- "alibaba/qwen3-asr-flash", "proxy/nested/claude-opus-4.6@us-east",
- "anthropic-claude-sonnet-4", "openai.gpt-4o", "google/gemini-2.5-flash",
- ];
+test("catalog lookup uses exact last segments and rejects ambiguous matches", async (t) => {
const catalog = await loadFixtureCatalog(t, {
- gateway: { models: Object.fromEntries(ids.map((id) => [id, { id }])) },
+ gateway: { models: {
+ "model": { id: "model" },
+ "nested/unique-model": { id: "nested/unique-model", reasoning: true },
+ "google/gemini-pro-latest": { id: "google/gemini-pro-latest", reasoning: true },
+ "route-a/shared-leaf": { id: "route-a/shared-leaf", reasoning: true },
+ "route-b/shared-leaf": { id: "route-b/shared-leaf", reasoning: false },
+ "regional@us-east": { id: "regional@us-east" },
+ } },
});
- for (const [request, expected] of [
- ["other-model", undefined],
- ["gemini-3.1-pro-preview-customtools", undefined],
- ["deepseek-v3", undefined],
- ["qwen-max", undefined],
- ["qwen-flash", undefined],
- ["myproxy-claude-opus-4.6", undefined],
- ["gemini-2.5-flash-high", undefined],
- ["gemini-2.5-flash-low", undefined],
- ["claude-opus-4.6-thinking", "proxy/nested/claude-opus-4.6@us-east"],
- ["proxy/claude-opus-4.6-thinking", undefined],
- ["claude-sonnet-4-agent", "anthropic-claude-sonnet-4"],
- ["proxy/gemini-2.5-flash", undefined],
- ["gpt-4o@eu", "openai.gpt-4o"],
- ]) {
- assert.equal(catalog.findModel({ vendorKey: "custom", modelId: request })?.modelId, expected, request);
- }
- assert.equal(catalog.findModel({ vendorKey: "custom", modelId: "openai/gemini-2.5-flash" }), undefined);
+
+ assert.equal(
+ catalog.findModel({ vendorKey: "custom", modelId: "proxy/UNIQUE-MODEL" })?.modelId,
+ "nested/unique-model",
+ );
+ assert.equal(catalog.findModel({ vendorKey: "custom", modelId: "other/model" })?.modelId, "model");
+ assert.equal(catalog.findModel({ vendorKey: "custom", modelId: "proxy/shared-leaf" }), undefined);
+ assert.equal(catalog.findModel({ vendorKey: "gateway", modelId: "proxy/shared-leaf" }), undefined);
+ assert.equal(catalog.findModel({ vendorKey: "custom", modelId: "ag/gemini-pro-agent" }), undefined);
+ assert.equal(catalog.findModel({ vendorKey: "custom", modelId: "regional" }), undefined);
+ assert.equal(
+ catalog.findModel({ vendorKey: "custom", modelId: "proxy/regional@us-east" })?.modelId,
+ "regional@us-east",
+ );
});
-test("matches supported proxy path and reasoning variants in catalog lookup", async (t) => {
- const catalog = await loadFixtureCatalog(t);
- for (const modelId of [
- "proxy/claude-opus-4.6", "proxy/claude-opus-4.6-thinking",
- "proxy/claude-opus-4.6-agent", "claude-opus-4.6:thinking",
- "anthropic-claude-opus-4.6",
- ]) {
- const match = catalog.findModel({ vendorKey: "custom", modelId });
- assert.equal(match?.modelId, "claude-opus-4.6", modelId);
- assert.equal(match.reasoning, true);
- }
- for (const modelId of ["myproxy-claude-opus-4.6", "myproxy-claude-opus-4.6-thinking"]) {
- assert.equal(catalog.findModel({ vendorKey: "custom", modelId }), undefined);
+test("ambiguous leaf matches prefer one official provider", async (t) => {
+ for (const order of [["relay", "openai"], ["openai", "relay"]]) {
+ const definitions = {
+ relay: { models: { "route/shared-leaf": {
+ id: "route/shared-leaf", reasoning: false, tool_call: false,
+ limit: { context: 32_000 },
+ } } },
+ openai: { models: { "shared-leaf": {
+ id: "shared-leaf", reasoning: true, tool_call: true,
+ reasoning_options: [{ type: "effort", values: ["low", "medium", "high"] }],
+ limit: { context: 128_000 },
+ } } },
+ };
+ const catalog = await loadFixtureCatalog(t, Object.fromEntries(
+ order.map((key) => [key, definitions[key]]),
+ ));
+ const match = catalog.findModel({ vendorKey: "custom", modelId: "proxy/shared-leaf" });
+ assert.equal(match?.providerKey, "openai");
+ assert.equal(match?.reasoning, true);
+ assert.equal(match?.limit.context, 128_000);
}
});
-test("metadata lookup can share routed leaves and narrow suffix aliases without merging bindings", async (t) => {
+test("official source keys ignore a cloud publisher carrying another vendor's model", async (t) => {
const catalog = await loadFixtureCatalog(t, {
- gateway: { models: {
- "gateway-a/foo": { id: "gateway-a/foo" },
- "bar-agent": { id: "bar-agent" },
+ xai: { models: { "grok-4.6": {
+ id: "grok-4.6", reasoning: true, tool_call: true,
+ reasoning_options: [{ type: "effort", values: ["low", "medium", "high", "xhigh"] }],
+ limit: { context: 500_000 },
+ } } },
+ "google-vertex": { models: { "xai/grok-4.6": {
+ id: "xai/grok-4.6", reasoning: true, tool_call: true,
+ limit: { context: 524_288 },
+ } } },
+ relay: { models: { "x-ai/grok-4.6": {
+ id: "x-ai/grok-4.6", reasoning: false, tool_call: false,
+ } } },
+ });
+ const match = catalog.findModel({ vendorKey: "custom", modelId: "ycj/grok-4.6" });
+ assert.equal(match?.providerKey, "xai");
+ assert.equal(match?.limit.context, 500_000);
+});
+
+test("ambiguous non-official leaf matches share unanimous capabilities", async (t) => {
+ const catalog = await loadFixtureCatalog(t, {
+ relayA: { models: { "route-a/shared-leaf": {
+ id: "route-a/shared-leaf", reasoning: true, tool_call: true,
+ reasoning_options: [{ type: "effort", values: ["low", "high"] }],
+ modalities: { input: ["text", "image"], output: ["text"] },
+ limit: { context: 64_000, output: 8_192 },
+ } } },
+ relayB: { models: { "route-b/shared-leaf": {
+ id: "route-b/shared-leaf", reasoning: true, tool_call: true,
+ reasoning_options: [{ type: "effort", values: ["low", "high"] }],
+ modalities: { input: ["image", "text"], output: ["text"] },
+ limit: { context: 128_000, output: 16_384 },
+ } } },
+ });
+ const match = catalog.findModel({ vendorKey: "custom", modelId: "proxy/shared-leaf" });
+ assert.ok(match);
+ assert.equal(match.reasoning, true);
+ assert.equal(match.toolCall, true);
+ assert.deepEqual(match.thinkingLevels, ["low", "high"]);
+ assert.deepEqual(match.modalities.input.toSorted(), ["image", "text"]);
+});
+
+test("ambiguous leaf matches with conflicting capabilities remain unmatched", async (t) => {
+ const catalog = await loadFixtureCatalog(t, {
+ relayA: { models: { "route-a/shared-leaf": {
+ id: "route-a/shared-leaf", reasoning: true, tool_call: true,
+ } } },
+ relayB: { models: { "route-b/shared-leaf": {
+ id: "route-b/shared-leaf", reasoning: false, tool_call: true,
+ } } },
+ });
+ assert.equal(
+ catalog.findModel({ vendorKey: "custom", modelId: "proxy/shared-leaf" }),
+ undefined,
+ );
+});
+
+test("gemini agent routes do not collapse to gemini latest catalog entries", async (t) => {
+ const catalog = await loadFixtureCatalog(t, {
+ google: { models: {
+ "gemini-pro-latest": { id: "gemini-pro-latest", reasoning: true },
} },
});
- assert.equal(modelIdsMatch("gateway-a/foo", "gateway-b/foo"), false);
- assert.equal(modelIdsMatch("bar", "bar-agent"), false);
- assert.equal(catalog.findModel({ modelId: "gateway-b/foo" }), undefined);
- assert.equal(catalog.findModel({ modelId: "bar-thinking" })?.modelId, "bar-agent");
+ assert.equal(
+ catalog.findModel({ vendorKey: "custom", modelId: "ag/gemini-pro-agent" }),
+ undefined,
+ );
+});
+
+test("catalog lookup never collapses reasoning or release suffix variants", async (t) => {
+ const catalog = await loadFixtureCatalog(t);
+ const exact = catalog.findModel({ vendorKey: "custom", modelId: "proxy/claude-opus-4.6" });
+ assert.equal(exact?.modelId, "claude-opus-4.6");
+ assert.equal(exact.reasoning, true);
+
+ for (const modelId of [
+ "proxy/claude-opus-4.6-thinking",
+ "proxy/claude-opus-4.6-agent",
+ "proxy/claude-opus-4.6-latest",
+ "claude-opus-4.6:thinking",
+ "anthropic-claude-opus-4.6",
+ ]) {
+ assert.equal(catalog.findModel({ vendorKey: "custom", modelId }), undefined, modelId);
+ }
});
/*
@@ -764,7 +823,7 @@ test("an exact record outranks a shipped publisher's other spelling of the id",
assert.ok(info.capabilities.includes("audio"));
});
-test("borrowing stays exact-id, provider-scoped and absent for unknown ids", async (t) => {
+test("unique leaf enrichment coexists with exact-id borrowing and unknown misses", async (t) => {
const catalog = await loadFixtureCatalog(t, {
gateway: { api: "https://gateway.example/v1", models: {} },
publisherA: { models: {
@@ -773,10 +832,11 @@ test("borrowing stays exact-id, provider-scoped and absent for unknown ids", asy
} },
});
const input = { vendorKey: "gateway", baseUrl: "https://gateway.example/v1" };
- // A near-miss id is not a reason to reuse a sibling's limits.
+ // Near-miss and unknown ids do not reuse a sibling's limits.
assert.equal(catalog.findModel({ ...input, modelId: "Vendor/Known-3000" }), undefined);
- assert.equal(catalog.findModel({ ...input, modelId: "Other/Known" }), undefined);
assert.equal(catalog.findModel({ ...input, modelId: "unknown-model-xyz" }), undefined);
+ // A different route with the same unique final segment is valid enrichment.
+ assert.equal(catalog.findModel({ ...input, modelId: "Other/Known" })?.modelId, "Vendor/Known");
// Exact ids still resolve, including a case-only difference.
assert.equal(catalog.findModel({ ...input, modelId: "vendor/known" })?.limit.context, 262_144);
assert.equal(catalog.findModel({ ...input, modelId: "Vendor/Known" })?.limit.context, 262_144);
@@ -1580,7 +1640,7 @@ const customGateway = {
baseUrl: "https://gateway.example/v1",
};
-test("a custom Anthropic gateway reads Anthropic's own record and its thinking shape", async (t) => {
+test("a custom gateway enriches an ambiguous Claude leaf from the official provider", async (t) => {
const catalog = await loadFixtureCatalog(t, ambiguousClaudeFixture);
const config = catalogModelConfigFor(catalog, {
...customGateway,
@@ -1588,20 +1648,10 @@ test("a custom Anthropic gateway reads Anthropic's own record and its thinking s
modelId: "claude-opus-5-5",
});
- /*
- Anthropic publishes this id, so the record of the publisher the app ships
- answers — not a median shared with a reseller's smaller deployment of the
- same id, which would halve the window Anthropic itself states.
- */
assert.equal(config.source, "models.dev");
assert.equal(config.contextWindow, 1_000_000);
assert.equal(config.maxTokens, 128_000);
assert.equal(config.reasoning, true);
- /*
- No publisher describes this endpoint's reasoning wire shape, so the borrowed
- record states none — and Anthropic's own record is what says whether the id
- takes adaptive or budget thinking.
- */
assert.deepEqual(config.reasoningOptions, [
{ type: "effort", values: ["low", "medium", "high", "xhigh", "max"] },
]);
@@ -1615,15 +1665,18 @@ test("a custom Anthropic gateway reads Anthropic's own record and its thinking s
});
});
-test("the Anthropic thinking fallback stays off other wire APIs and non-Claude ids", async (t) => {
+test("official-provider enrichment is API-style independent while unknown ids stay generic", async (t) => {
const catalog = await loadFixtureCatalog(t, ambiguousClaudeFixture);
const completions = catalogModelConfigFor(catalog, {
...customGateway,
apiStyle: "chat_completions",
modelId: "claude-opus-5-5",
});
- assert.equal(completions.reasoningOptions, undefined);
- assert.equal(completions.thinkingLevelMap, undefined);
+ assert.equal(completions.source, "models.dev");
+ assert.equal(completions.contextWindow, 1_000_000);
+ assert.deepEqual(completions.reasoningOptions, [
+ { type: "effort", values: ["low", "medium", "high", "xhigh", "max"] },
+ ]);
// An id absent from every publisher stays generic, even on Anthropic Messages.
const unlisted = catalogModelConfigFor(catalog, {
diff --git a/apps/desktop/test/plugin-mcp.test.mjs b/apps/desktop/test/plugin-mcp.test.mjs
index 9ffc46926..18c255200 100644
--- a/apps/desktop/test/plugin-mcp.test.mjs
+++ b/apps/desktop/test/plugin-mcp.test.mjs
@@ -244,21 +244,34 @@ test("a stdio server that cannot start fails the handshake, not the process", as
assert.match(String(failure.message), /exited with code/);
});
-test("a slow server times out instead of hanging the load", async (t) => {
+test("a slow server times out instead of hanging the load", async () => {
const dir = stdioPlugin();
- writeFileSync(join(dir, "server.mjs"), "setInterval(() => {}, 1000);\n");
+ const pidFile = join(dir, "pid");
+ writeFileSync(
+ join(dir, "server.mjs"),
+ 'import { writeFileSync } from "node:fs";\nwriteFileSync(process.env.STUB_PID_FILE, String(process.pid));\nsetInterval(() => {}, 1000);\n',
+ );
const client = new McpServerClient({
pluginId: "com.example.mcp",
rootPath: dir,
server: { id: "stub", transport: "stdio", command: "node", args: ["./server.mjs"] },
- values: {},
+ values: { STUB_PID_FILE: pidFile },
connectTimeoutMs: 250,
});
- t.after(() => client.close());
await assert.rejects(client.connect(), (error) => {
assert.equal(error.code, "TIMEOUT");
return true;
});
+ const pid = Number(readFileSync(pidFile, "utf8"));
+ for (let attempt = 0; attempt < 40; attempt += 1) {
+ try {
+ process.kill(pid, 0);
+ } catch {
+ return;
+ }
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ assert.fail("timed-out stdio mcp child survived handshake cleanup");
});
/** Streamable-HTTP stub: JSON for the handshake, SSE for discovery. */
diff --git a/packages/shared/src/thinking-levels.test.ts b/packages/shared/src/thinking-levels.test.ts
index a81ebc0d9..a313ba310 100644
--- a/packages/shared/src/thinking-levels.test.ts
+++ b/packages/shared/src/thinking-levels.test.ts
@@ -54,14 +54,14 @@ describe("initialThinkingLevelForBinding", () => {
).toBe("high");
});
- it("falls back to the strongest enabled level when no default is stored", () => {
+ it("defaults to off when no default is stored", () => {
expect(
initialThinkingLevelForBinding({
thinkingLevels: ["low", "high", "max"],
defaultThinkingLevel: null,
}),
- ).toBe("max");
- expect(initialThinkingLevelForBinding(undefined, ["low", "high"])).toBe("high");
+ ).toBe("off");
+ expect(initialThinkingLevelForBinding(undefined, ["low", "high"])).toBe("off");
});
it("honors an explicit off default and empty bindings", () => {
diff --git a/packages/shared/src/thinking-levels.ts b/packages/shared/src/thinking-levels.ts
index 9336b727a..7efac537b 100644
--- a/packages/shared/src/thinking-levels.ts
+++ b/packages/shared/src/thinking-levels.ts
@@ -91,11 +91,10 @@ export function nearestSupportedThinkingLevel(
/**
* Thinking level a new draft or session starts at for a model binding.
*
- * Prefer the stored default when it is still enabled, including `omit` on a
- * reasoning binding. Otherwise clamp that default onto the enabled ladder.
- * With no stored default, fall back to the strongest enabled level so a
- * reasoning model never starts at `off` merely because Settings has not
- * picked a default yet.
+ * Prefer an explicitly stored default when it is still enabled, including
+ * `omit` on a reasoning binding. Otherwise clamp that explicit default onto
+ * the enabled ladder. With no stored default, start at `off`; available
+ * reasoning levels remain selectable but are never enabled implicitly.
*/
export function initialThinkingLevelForBinding(
binding: ThinkingLevelBindingSource | null | undefined,
@@ -105,7 +104,7 @@ export function initialThinkingLevelForBinding(
const stored = binding?.defaultThinkingLevel;
if (stored === "omit") return enablesReasoning(enabled) ? "omit" : "off";
if (stored != null) return nearestSupportedThinkingLevel(stored, enabled);
- return highestSupportedThinkingLevel(enabled);
+ return "off";
}
/** Published record a thinking-level candidate list can be derived from. */
diff --git a/packages/shared/src/types/models.ts b/packages/shared/src/types/models.ts
index 2f98f97dc..b21f1e353 100644
--- a/packages/shared/src/types/models.ts
+++ b/packages/shared/src/types/models.ts
@@ -150,22 +150,7 @@ function extractKnownVendor(id: string): string | undefined {
return undefined;
}
-function pathLeaf(id: string): string {
- const slash = id.lastIndexOf("/");
- return slash >= 0 ? id.slice(slash + 1) : id;
-}
-
-function exactPathAliasMatch(left: string, right: string): boolean {
- // Two independently routed paths cannot be identified by their leaf alone.
- if (left.includes("/") === right.includes("/")) return false;
- if (pathLeaf(left) !== pathLeaf(right)) return false;
-
- const leftVendor = extractKnownVendor(left);
- const rightVendor = extractKnownVendor(right);
- return !leftVendor || !rightVendor || leftVendor === rightVendor;
-}
-
-function normalizedMatch(left: string, right: string, allowPathLeaf = false): boolean {
+function normalizedMatch(left: string, right: string): boolean {
const leftVendor = extractKnownVendor(left);
const rightVendor = extractKnownVendor(right);
if (leftVendor && rightVendor && leftVendor !== rightVendor) return false;
@@ -179,7 +164,11 @@ function normalizedMatch(left: string, right: string, allowPathLeaf = false): bo
}
}
- return allowPathLeaf && exactPathAliasMatch(left, right);
+ return false;
+}
+function pathLeaf(id: string): string {
+ const slash = id.lastIndexOf("/");
+ return slash >= 0 ? id.slice(slash + 1) : id;
}
/** Configured-model identity: compare the complete wire ID, not catalog aliases. */
@@ -197,30 +186,20 @@ export function modelIdsMatch(candidate: string, requested: string): boolean {
return normalizedMatch(stripRegion(left), stripRegion(right));
}
-/** Broader metadata-only aliases; never use for configured binding identity. */
+/**
+ * Catalog enrichment matcher: take the **last `/`-segment** of each side,
+ * compare case-insensitively. The caller enforces uniqueness (exactly 1
+ * catalog hit ⇒ enrichment; 0 or ≥2 ⇒ no match).
+ *
+ * This deliberately does **not** strip `-thinking`, `-agent`, `-latest`,
+ * vendor-dash prefixes, or any other fuzzy suffix. The old variant-suffix
+ * and vendor-prefix logic caused cross-model false positives.
+ */
export function catalogModelIdsMatch(candidate: string, requested: string): boolean {
const left = candidate.trim().toLowerCase();
const right = requested.trim().toLowerCase();
if (!left || !right) return false;
-
- const cleanLeft = stripRegion(left);
- const cleanRight = stripRegion(right);
- // Exact id, known vendor prefix, route leaf, then thinking/agent/latest.
- if (normalizedMatch(cleanLeft, cleanRight, true)) return true;
-
- const variantLeft = stripVariantSuffix(cleanLeft);
- const variantRight = stripVariantSuffix(cleanRight);
- if (normalizedMatch(variantLeft, variantRight, true)) return true;
-
- /* Published release stamps are tried last, so a dated snapshot can never
- displace the exact id or a documented alias. A catalog that publishes both
- `foo-v2` and `foo-v2-0731` therefore still answers `foo-v2-0731` with its
- own record: the caller's exact-first ranking decides between them. */
- return normalizedMatch(
- stripReleaseSuffix(variantLeft),
- stripReleaseSuffix(variantRight),
- true,
- );
+ return pathLeaf(left) === pathLeaf(right);
}
/**