Skip to content

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

fix(settings): keep an app default when a provider is added

vastsa256a6d2ebf78
diff --git a/apps/desktop/electron/main/ipc/provider-ipc.ts b/apps/desktop/electron/main/ipc/provider-ipc.ts
index f2fc844df..155f3d61e 100644
--- a/apps/desktop/electron/main/ipc/provider-ipc.ts
+++ b/apps/desktop/electron/main/ipc/provider-ipc.ts
@@ -82,6 +82,39 @@ export function registerProviderIpc({
await modelsDevCatalog.ensureLoaded();
return { status: modelsDevCatalog.getStatus() };
});
+ /**
+ * Look one model id up in the local models.dev snapshot.
+ *
+ * A hand-typed custom id is not in any provider's model list yet, so the
+ * settings picker has no other channel for its published limits. This is a
+ * snapshot read: it loads the bundled catalog, performs no network request,
+ * and never asks the host, so a slow or offline catalog cannot block the
+ * picker. `providerId` is echoed back on the record; `vendorKey` / `baseUrl`
+ * only disambiguate which published provider a duplicate id belongs to.
+ */
+ handle(
+ IPC.invoke.providersLookupModel,
+ async (input: {
+ modelId?: string;
+ baseUrl?: string;
+ providerId?: string;
+ vendorKey?: string;
+ }) => {
+ const modelId = (input?.modelId ?? "").trim();
+ if (!modelId) return { info: null };
+ await modelsDevCatalog.ensureLoaded();
+ const model = modelsDevCatalog.findModel({
+ vendorKey: input?.vendorKey,
+ baseUrl: input?.baseUrl,
+ modelId,
+ });
+ return {
+ info: model
+ ? modelInfoFromModelsDev(model, input?.providerId ?? "")
+ : null,
+ };
+ },
+ );
handle(IPC.invoke.providersCreate, async (input: unknown) => {
if (!host) throw new Error("host unavailable");
const result = await host.call<{ provider: RuntimeProvider }>(
diff --git a/apps/desktop/src/components/settings/ModelConfigPage.tsx b/apps/desktop/src/components/settings/ModelConfigPage.tsx
index 66d8eac93..48ad9a085 100644
--- a/apps/desktop/src/components/settings/ModelConfigPage.tsx
+++ b/apps/desktop/src/components/settings/ModelConfigPage.tsx
@@ -4,7 +4,8 @@
*
* The default picker lists each configured model, while provider rows use
* `models[0]` as the provider's quick default. Editing the default provider
- * preserves `settings.defaultModelId` while that model remains configured.
+ * preserves `settings.defaultModelId` while that model remains configured, and
+ * adding a provider claims the chat or image default only while none resolves.
*/
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
@@ -37,7 +38,9 @@ import { AnchoredMenu } from "./AnchoredMenu";
import {
defaultModelOptions,
displayedDefaultModelId,
+ hasResolvedDefaultModel,
} from "./default-model";
+import { planImageGenerationDefaults } from "./image-generation-default";
import { copyProviderConfiguration, type ProviderCopyDraft } from "./provider-copy";
import { ImageGenerationModelRow } from "./ImageGenerationModelRow";
import { ProviderSetupDialog } from "./ProviderSetupDialog";
@@ -177,7 +180,9 @@ export function ModelConfigPage() {
};
/**
- * Preserve the selected app default unless it was removed from the provider.
+ * Preserve the selected app defaults unless they were removed from the
+ * provider or no longer resolve, and let a newly added provider claim a
+ * default only while none resolves.
*/
const afterSaved = async (
saved: ProviderPublic,
@@ -188,41 +193,33 @@ export function ModelConfigPage() {
try {
if (imageModelIds !== undefined) {
const current = await api.getSettings();
- const existing = imageGenerationBindings(
- current.imageGenerationModels,
- current.imageGeneration,
+ const plan = planImageGenerationDefaults(
+ current,
+ saved.id,
+ imageModelIds,
+ [...providers.filter((provider) => provider.id !== saved.id), saved],
);
- const selected = [...new Set(imageModelIds)].map((modelId) => ({
- providerId: saved.id,
- modelId,
- }));
- const nextCandidates = [
- ...existing.filter((binding) => binding.providerId !== saved.id),
- ...selected,
- ];
- const active = current.imageGeneration;
- const nextActive = active && nextCandidates.some((binding) =>
- binding.providerId === active.providerId &&
- modelIdsMatch(binding.modelId, active.modelId),
- )
- ? active
- : nextCandidates[0] ?? null;
- const nextSettings = {
- ...current,
- imageGenerationModels: nextCandidates,
- imageGeneration: nextActive,
- };
+ const nextSettings = { ...current, ...plan };
await api.setSettings(nextSettings);
useAppStore.setState({ settings: nextSettings });
showToast(t("settings.imageModelSelected"), { variant: "success" });
} else if (copyDraft) {
showToast(t("settings.providerSaved"), { variant: "success" });
} else if (!editingProvider) {
- await api.setSettings({
- ...settings,
- defaultProviderId: saved.id,
- defaultModelId: firstModelId ?? "",
- });
+ // A freshly added provider must not take over the app default: whatever
+ // the user already picked keeps running until they change it themselves.
+ const keepsCurrentDefault = hasResolvedDefaultModel(
+ providers,
+ settings.defaultProviderId,
+ settings.defaultModelId,
+ );
+ if (!keepsCurrentDefault) {
+ await api.setSettings({
+ ...settings,
+ defaultProviderId: saved.id,
+ defaultModelId: firstModelId ?? "",
+ });
+ }
showToast(t("settings.providerSaved"), { variant: "success" });
} else {
if (
diff --git a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx b/apps/desktop/src/components/settings/ModelSelectionPanes.tsx
index df86b07ac..3828c2fa5 100644
--- a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx
+++ b/apps/desktop/src/components/settings/ModelSelectionPanes.tsx
@@ -32,10 +32,17 @@ import {
MAX_OUTPUT_PRESETS,
matchPresetIndex,
} from "../../lib/model-limit-presets";
+import { api } from "../../lib/api";
import { Button, Field, HelpIcon, Input, Tooltip, TooltipButton, cx } from "../ui";
import { IconClose, IconGripVertical, IconHelp, IconPlus, IconRefresh, IconSearch } from "../icons";
import { SettingsMenuSelect } from "./SettingsMenuSelect";
import { filterChosenModels, hidesAddedBinding } from "./model-chosen-filter";
+import {
+ applyCustomModelLookup,
+ customModelLookupInput,
+ customModelSeedBinding,
+ type CustomModelLookupContext,
+} from "./model-custom-lookup";
import { describeModelsFetchError } from "./model-fetch-error";
import type { ProviderModelsState } from "./useProviderModels";
import { useModelReorder } from "./useModelReorder";
@@ -196,6 +203,12 @@ export type ModelSelectionPanesProps = {
* tool offer the checkbox at all.
*/
apiStyle?: string;
+ /**
+ * What this entry knows about where a hand-typed id belongs. The picker
+ * passes it to the model-library lookup that seeds a custom row's published
+ * limits; absent fields only widen the catalog search.
+ */
+ lookupContext?: CustomModelLookupContext;
};
/**
@@ -211,6 +224,7 @@ export function ModelSelectionPanes({
onReload,
apiStyle,
imageModelIds,
+ lookupContext,
onImageModelChange,
}: ModelSelectionPanesProps) {
const { t } = useTranslation();
@@ -326,6 +340,33 @@ export function ModelSelectionPanes({
current.map((binding) => (binding.id === id ? { ...binding, ...update } : binding)),
);
+ /**
+ * Ask the host for the model library's record of a just-added hand-typed id
+ * and upgrade the row in place.
+ *
+ * The lookup is asynchronous, so the row may have been edited, removed, or
+ * replaced by the time it answers; `applyCustomModelLookup` only replaces the
+ * untouched seed. A miss or a failed call is the generic seed it already is.
+ */
+ const enrichCustomModel = async (seed: ModelBinding) => {
+ let info: ModelInfo | null = null;
+ try {
+ const result = await api.lookupProviderModel(
+ customModelLookupInput(seed.id, lookupContext),
+ );
+ info = result?.info ?? null;
+ } catch {
+ return;
+ }
+ setModels((current) => applyCustomModelLookup(current, seed, info));
+ };
+
+ /**
+ * A hand-typed id is matched against the discovered rows first, then against
+ * the model library through the host. The row lands immediately with the
+ * generic seed, so a slow or failed lookup still leaves exactly one usable
+ * row; a published record upgrades that same row when it arrives.
+ */
const addCustomModel = () => {
const id = customModelId.trim();
if (!id) {
@@ -336,12 +377,18 @@ export function ModelSelectionPanes({
setCustomModelError(t("settings.modelAlreadyAdded"));
return;
}
- const binding = bindingForCustomModel(id);
+ const discovered = rows.find((row) => row.id.toLowerCase() === id.toLowerCase());
+ const binding = customModelSeedBinding(id, discovered?.info);
setModels((current) => [...current, binding]);
- setExpandedModelId(id);
+ // Expand the row under the id it is stored with: a discovered row keeps the
+ // service's spelling, which can differ from what the user typed.
+ setExpandedModelId(binding.id);
setCustomModelId("");
setCustomModelError("");
keepAddedModelVisible([binding]);
+ // A discovered row already carries the published record, so only the
+ // not-yet-known id needs the extra lookup.
+ if (!discovered?.info) void enrichCustomModel(binding);
};
const fetchFailed = discovery.status === "error";
diff --git a/apps/desktop/src/components/settings/ProviderSetupDialog.tsx b/apps/desktop/src/components/settings/ProviderSetupDialog.tsx
index e7a1b85a0..a2965ad3e 100644
--- a/apps/desktop/src/components/settings/ProviderSetupDialog.tsx
+++ b/apps/desktop/src/components/settings/ProviderSetupDialog.tsx
@@ -545,6 +545,11 @@ export function ProviderSetupDialog({
apiStyle={resolvedApiStyle}
imageModelIds={imageModelDraft ?? imageModelIds}
onImageModelChange={updateImageModelDraft}
+ lookupContext={{
+ baseUrl: requestBaseUrl,
+ vendorKey: namedPreset?.vendorKey ?? "custom",
+ providerId: provider?.id,
+ }}
/>
</div>
</div>
diff --git a/apps/desktop/src/components/settings/VendorAccountDialog.tsx b/apps/desktop/src/components/settings/VendorAccountDialog.tsx
index bd29d6e63..82a590000 100644
--- a/apps/desktop/src/components/settings/VendorAccountDialog.tsx
+++ b/apps/desktop/src/components/settings/VendorAccountDialog.tsx
@@ -138,6 +138,11 @@ export function VendorAccountDialog({
listTitle={t("settings.accountModels")}
busy={saving}
onReload={discovery.reload}
+ lookupContext={{
+ baseUrl: provider.baseUrl,
+ vendorKey: provider.vendorKey,
+ providerId: provider.id,
+ }}
apiStyle={provider.apiStyle ?? ""}
/>
</div>
diff --git a/apps/desktop/src/components/settings/default-model.ts b/apps/desktop/src/components/settings/default-model.ts
index b59f30b7b..f44973f4e 100644
--- a/apps/desktop/src/components/settings/default-model.ts
+++ b/apps/desktop/src/components/settings/default-model.ts
@@ -67,3 +67,23 @@ export function displayedDefaultModelId(
? settingsModelId
: defaultModelIdOf(provider);
}
+
+/**
+ * Whether the app default already names a model that still resolves.
+ *
+ * A non-empty `settings.defaultModelId` is not proof of a default: the value
+ * outlives the provider it was picked from, so once that provider is deleted
+ * or its binding list is emptied the value names nothing. Callers that would
+ * otherwise adopt a default for a freshly added provider resolve through the
+ * default provider row — the same pairing the summary line shows — and keep
+ * the current value only when a real model stands behind it.
+ */
+export function hasResolvedDefaultModel(
+ providers: readonly ProviderPublic[],
+ defaultProviderId?: string,
+ defaultModelId?: string,
+): boolean {
+ const provider = providers.find((candidate) => candidate.id === defaultProviderId);
+ if (!provider) return false;
+ return !!displayedDefaultModelId(provider, defaultModelId)?.trim();
+}
diff --git a/apps/desktop/src/components/settings/image-generation-default.ts b/apps/desktop/src/components/settings/image-generation-default.ts
new file mode 100644
index 000000000..a4371e213
--- /dev/null
+++ b/apps/desktop/src/components/settings/image-generation-default.ts
@@ -0,0 +1,73 @@
+/**
+ * Keeping the app's default image model across a provider save.
+ *
+ * `settings.imageGeneration` is the app default the Composer reads, while
+ * `settings.imageGenerationModels` only lists the candidates the picker offers.
+ * Saving a provider may extend that list, but adding one must not take over the
+ * default: the chat default's rule applies here too — the stored choice
+ * survives while it still resolves to a model a configured provider serves, and
+ * only an unresolvable one is replaced.
+ */
+import {
+ imageGenerationBindings,
+ type ImageGenerationBinding,
+ type ProviderPublic,
+} from "@pi-desktop/shared";
+import { providerOffersModel } from "./default-model";
+
+/** True when the binding still names a model a configured provider serves. */
+export function resolvesImageGenerationDefault(
+ binding: ImageGenerationBinding | null | undefined,
+ providers: readonly ProviderPublic[],
+): boolean {
+ if (!binding) return false;
+ const provider = providers.find((candidate) => candidate.id === binding.providerId);
+ return !!provider && providerOffersModel(provider, binding.modelId);
+}
+
+export type ImageGenerationDefaultDraft = {
+ imageGenerationModels?: readonly ImageGenerationBinding[] | null;
+ imageGeneration?: ImageGenerationBinding | null;
+};
+
+export type ImageGenerationDefaultPlan = {
+ imageGenerationModels: ImageGenerationBinding[];
+ imageGeneration: ImageGenerationBinding | null;
+};
+
+/**
+ * The candidate list and active default a saved provider should leave behind.
+ *
+ * The saved provider's selection replaces its own earlier candidates, while the
+ * candidates of other providers stay listed — the picker disables the ones that
+ * no longer resolve. The active default moves only when the stored choice stops
+ * resolving, and then to the first candidate that does, so a newly added
+ * provider claims the default exactly when nothing else can hold it.
+ */
+export function planImageGenerationDefaults(
+ current: ImageGenerationDefaultDraft,
+ savedProviderId: string,
+ selectedModelIds: readonly string[],
+ providers: readonly ProviderPublic[],
+): ImageGenerationDefaultPlan {
+ const existing = imageGenerationBindings(
+ current.imageGenerationModels,
+ current.imageGeneration,
+ );
+ const selected = [...new Set(selectedModelIds)].map((modelId) => ({
+ providerId: savedProviderId,
+ modelId,
+ }));
+ const imageGenerationModels = [
+ ...existing.filter((binding) => binding.providerId !== savedProviderId),
+ ...selected,
+ ];
+ const active = current.imageGeneration ?? null;
+ const fallback = imageGenerationModels.find((binding) =>
+ resolvesImageGenerationDefault(binding, providers)
+ ) ?? imageGenerationModels[0] ?? null;
+ return {
+ imageGenerationModels,
+ imageGeneration: resolvesImageGenerationDefault(active, providers) ? active : fallback,
+ };
+}
diff --git a/apps/desktop/src/components/settings/model-custom-lookup.ts b/apps/desktop/src/components/settings/model-custom-lookup.ts
new file mode 100644
index 000000000..85497df70
--- /dev/null
+++ b/apps/desktop/src/components/settings/model-custom-lookup.ts
@@ -0,0 +1,89 @@
+/**
+ * How a hand-typed model id becomes a binding, and how a late catalog answer
+ * reaches it.
+ *
+ * One typed id has three sources, in order: the rows the current discovery
+ * already returned, the local models.dev snapshot (through the host), and the
+ * generic seed. The snapshot lookup is asynchronous, so the row has to land
+ * first and be upgraded later — and only while it is still the untouched seed,
+ * or an answer that arrives after the user edited or removed the row would
+ * overwrite their action. Keeping that ordering here means it is asserted once,
+ * for the component and for the tests, instead of only existing inline.
+ */
+import {
+ bindingForCustomModel,
+ bindingForCustomModelInfo,
+ bindingFromModelInfo,
+ type ModelBinding,
+ type ModelInfo,
+} from "@pi-desktop/shared";
+
+/** What one entry can tell the host about where a typed id belongs. */
+export type CustomModelLookupContext = {
+ providerId?: string;
+ vendorKey?: string;
+ baseUrl?: string;
+};
+
+/** Lookup input for one id, carrying only the context the entry actually has. */
+export type CustomModelLookupInput = {
+ modelId: string;
+ providerId?: string;
+ vendorKey?: string;
+ baseUrl?: string;
+};
+
+/**
+ * The binding a hand-typed id starts from: the discovered row's published
+ * record when the service already returned this id, the generic seed otherwise.
+ *
+ * A row from the current discovery already passed through models.dev, so using
+ * it is both more accurate and cheaper than asking again.
+ */
+export function customModelSeedBinding(
+ id: string,
+ discovered?: ModelInfo | null,
+): ModelBinding {
+ return discovered ? bindingFromModelInfo(discovered) : bindingForCustomModel(id);
+}
+
+/** Lookup input for one id, omitting fields this entry cannot supply. */
+export function customModelLookupInput(
+ id: string,
+ context: CustomModelLookupContext = {},
+): CustomModelLookupInput {
+ const input: CustomModelLookupInput = { modelId: id };
+ if (context.providerId) input.providerId = context.providerId;
+ if (context.vendorKey) input.vendorKey = context.vendorKey;
+ if (context.baseUrl) input.baseUrl = context.baseUrl;
+ return input;
+}
+
+/**
+ * Apply a snapshot answer to the binding list.
+ *
+ * A miss (`null`) keeps the seed, so a failed or unpublished lookup is just the
+ * old behavior. A hit replaces the row the lookup was asked about, and only
+ * while that row still equals the seed: an edit, a removal, or a re-add then
+ * edit leaves the stored answer alone.
+ */
+export function applyCustomModelLookup(
+ current: ModelBinding[],
+ seed: ModelBinding,
+ info: ModelInfo | null,
+): ModelBinding[] {
+ if (!info) return current;
+ let changed = false;
+ const next = current.map((binding) => {
+ if (binding.id !== seed.id || !isUntouchedSeed(binding, seed)) return binding;
+ changed = true;
+ // The stored id stays exactly what the user typed; the catalog spelling is
+ // metadata, not the string the provider is addressed with.
+ return bindingForCustomModelInfo(seed.id, info);
+ });
+ return changed ? next : current;
+}
+
+function isUntouchedSeed(binding: ModelBinding, seed: ModelBinding): boolean {
+ return JSON.stringify(binding) === JSON.stringify(seed);
+}
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 845162960..d2a4c03fb 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -634,6 +634,21 @@ export const api = {
source: "cache" | "remote" | "catalog" | "fallback";
error?: string;
}>(IPC.invoke.providersListModels, input),
+ /**
+ * Look one hand-typed model id up in the local models.dev snapshot.
+ *
+ * The discovered list only describes ids a service already serves, so this is
+ * the only way a custom id reaches its published limits before the provider
+ * is saved. Snapshot read only: no provider network access and no host call.
+ * `info` is null when the catalog does not publish the id.
+ */
+ lookupProviderModel: (input: {
+ modelId: string;
+ baseUrl?: string;
+ providerId?: string;
+ vendorKey?: string;
+ }) =>
+ invoke<{ info: ModelInfo | null }>(IPC.invoke.providersLookupModel, input),
/** Force-refresh models.dev for the running process; release snapshots are bundled. */
refreshModelCatalog: () =>
invoke<{
diff --git a/apps/desktop/test/default-model-display.test.mjs b/apps/desktop/test/default-model-display.test.mjs
index 04fe8a842..ffa8c778a 100644
--- a/apps/desktop/test/default-model-display.test.mjs
+++ b/apps/desktop/test/default-model-display.test.mjs
@@ -4,7 +4,8 @@
* `settings.defaultModelId` is a single global value while each provider owns
* its own binding list, so the two can disagree. The summary line renders the
* default provider's name and a model id side by side, which asserts a pairing
- * — these tests pin that the pairing shown is one that actually exists.
+ * — these tests pin that the pairing shown is one that actually exists, and
+ * that adding a provider only claims the default while none resolves.
*/
import assert from "node:assert/strict";
import test from "node:test";
@@ -12,6 +13,7 @@ import {
defaultModelIdOf,
displayedDefaultModelId,
providerOffersModel,
+ hasResolvedDefaultModel,
} from "../src/components/settings/default-model.ts";
/** Minimal provider row; only the fields these resolvers read. */
@@ -94,3 +96,37 @@ test("a provider with nothing configured resolves to undefined", () => {
assert.equal(defaultModelIdOf(p), undefined);
assert.equal(displayedDefaultModelId(p, "gpt-5"), undefined);
});
+
+/**
+ * Adding a provider must not steal a default the user already runs. The guard
+ * resolves the stored value exactly the way the summary line does, so a stale
+ * id left behind by a deleted provider still lets the new provider take over.
+ */
+test("a default that still resolves is kept when another provider is added", () => {
+ const p = provider({ models: [binding("gpt-5"), binding("gpt-5-mini")] });
+ assert.equal(hasResolvedDefaultModel([p], "p1", "gpt-5-mini"), true);
+});
+
+test("the default provider's own models count as a configured default", () => {
+ // `defaultModelId` can be empty while the default provider already serves
+ // models: the summary line shows that pairing, so a second provider must not
+ // replace what the user is running.
+ const p = provider({ models: [binding("gpt-5")] });
+ assert.equal(hasResolvedDefaultModel([p], "p1", ""), true);
+ assert.equal(hasResolvedDefaultModel([p], "p1", undefined), true);
+});
+
+test("a default whose provider is gone does not block a newly added one", () => {
+ const p = provider({ models: [binding("gpt-5")] });
+ assert.equal(hasResolvedDefaultModel([p], "deleted-provider", "gpt-5"), false);
+ assert.equal(hasResolvedDefaultModel([p], undefined, "gpt-5"), false);
+ assert.equal(hasResolvedDefaultModel([p], "", "gpt-5"), false);
+});
+
+test("an empty default resolves to nothing, so the new provider claims it", () => {
+ const empty = provider({ models: [], defaultModelId: undefined });
+ assert.equal(hasResolvedDefaultModel([empty], "p1", ""), false);
+ // A stored id the default provider does not serve is not a default either:
+ // the row renders the empty state, so the next provider may fill it.
+ assert.equal(hasResolvedDefaultModel([empty], "p1", "gpt-5"), false);
+});
diff --git a/apps/desktop/test/image-generation-default.test.mjs b/apps/desktop/test/image-generation-default.test.mjs
new file mode 100644
index 000000000..6ee77d197
--- /dev/null
+++ b/apps/desktop/test/image-generation-default.test.mjs
@@ -0,0 +1,129 @@
+/**
+ * Behavioural tests for the app's default image model across a provider save.
+ *
+ * `settings.imageGeneration` is the app default the Composer reads, while
+ * `settings.imageGenerationModels` is only the candidate list the picker
+ * offers. Adding a provider extends that list, so these tests pin that the
+ * user's default survives an added provider and moves only when the stored
+ * choice stops resolving.
+ */
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+// The renderer module resolves its sibling through the bundler, not Node.
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { planImageGenerationDefaults, resolvesImageGenerationDefault } = await import(
+ "../src/components/settings/image-generation-default.ts"
+);
+
+const provider = (id, modelIds) => ({
+ id,
+ name: id,
+ enabled: true,
+ hasSecret: true,
+ hasOauth: false,
+ authKind: "api_key_and_base_url",
+ models: modelIds.map((modelId) => ({ id: modelId })),
+});
+
+const binding = (providerId, modelId) => ({ providerId, modelId });
+
+test("a saved image selection extends the candidates without taking the default", () => {
+ const plan = planImageGenerationDefaults(
+ {
+ imageGenerationModels: [binding("x", "img-x")],
+ imageGeneration: binding("x", "img-x"),
+ },
+ "y",
+ ["img-y"],
+ [provider("x", ["img-x"]), provider("y", ["img-y"])],
+ );
+ assert.deepEqual(plan.imageGenerationModels, [
+ binding("x", "img-x"),
+ binding("y", "img-y"),
+ ]);
+ assert.deepEqual(plan.imageGeneration, binding("x", "img-x"));
+});
+
+test("a legacy default stored without a candidate list is kept too", () => {
+ const plan = planImageGenerationDefaults(
+ { imageGeneration: binding("x", "img-x") },
+ "y",
+ ["img-y"],
+ [provider("x", ["img-x"]), provider("y", ["img-y"])],
+ );
+ assert.deepEqual(plan.imageGeneration, binding("x", "img-x"));
+});
+
+test("a default that no longer resolves gives way to a provider that does", () => {
+ // The image provider was deleted while its binding stayed in settings: a
+ // newly added provider with image models is what should fill that default.
+ const plan = planImageGenerationDefaults(
+ {
+ imageGenerationModels: [binding("gone", "img-gone")],
+ imageGeneration: binding("gone", "img-gone"),
+ },
+ "y",
+ ["img-y"],
+ [provider("y", ["img-y"])],
+ );
+ assert.deepEqual(plan.imageGenerationModels, [
+ binding("gone", "img-gone"),
+ binding("y", "img-y"),
+ ]);
+ assert.deepEqual(plan.imageGeneration, binding("y", "img-y"));
+});
+
+test("an unconfigured default is filled by the saved selection", () => {
+ const plan = planImageGenerationDefaults(
+ { imageGenerationModels: [], imageGeneration: null },
+ "y",
+ ["img-y", "img-y", "img-y-alt"],
+ [provider("y", ["img-y", "img-y-alt"])],
+ );
+ // A repeated pick collapses, so the picker shows one row per model.
+ assert.deepEqual(plan.imageGenerationModels, [
+ binding("y", "img-y"),
+ binding("y", "img-y-alt"),
+ ]);
+ assert.deepEqual(plan.imageGeneration, binding("y", "img-y"));
+});
+
+test("editing a provider replaces its own candidates only", () => {
+ const plan = planImageGenerationDefaults(
+ {
+ imageGenerationModels: [binding("x", "img-x"), binding("y", "img-y-old")],
+ imageGeneration: binding("x", "img-x"),
+ },
+ "y",
+ ["img-y-new"],
+ [provider("x", ["img-x"]), provider("y", ["img-y-new"])],
+ );
+ assert.deepEqual(plan.imageGenerationModels, [
+ binding("x", "img-x"),
+ binding("y", "img-y-new"),
+ ]);
+ assert.deepEqual(plan.imageGeneration, binding("x", "img-x"));
+});
+
+test("resolving follows the provider row, not the candidate list", () => {
+ assert.equal(resolvesImageGenerationDefault(null, [provider("x", ["img-x"])]), false);
+ assert.equal(
+ resolvesImageGenerationDefault(binding("x", "img-x"), [provider("x", ["img-x"])]),
+ true,
+ );
+ // Another provider serving the same id is not the configured one.
+ assert.equal(
+ resolvesImageGenerationDefault(binding("x", "img-x"), [provider("z", ["img-x"])]),
+ false,
+ );
+ // A model the provider no longer lists cannot hold the default.
+ assert.equal(
+ resolvesImageGenerationDefault(binding("x", "img-x"), [provider("x", ["other"])]),
+ false,
+ );
+ // An OAuth-style row that stores only the legacy id still resolves.
+ const legacy = { ...provider("x", []), defaultModelId: "img-x" };
+ assert.equal(resolvesImageGenerationDefault(binding("x", "img-x"), [legacy]), true);
+});
diff --git a/apps/desktop/test/model-custom-lookup.test.mjs b/apps/desktop/test/model-custom-lookup.test.mjs
new file mode 100644
index 000000000..251fdd22a
--- /dev/null
+++ b/apps/desktop/test/model-custom-lookup.test.mjs
@@ -0,0 +1,115 @@
+/**
+ * A hand-typed custom model id is seeded from the model library.
+ *
+ * Adding a custom id by hand used to give every binding the generic
+ * 128,000 / 8,192 seed and no thinking levels, even when the library already
+ * published that id. The picker now looks the id up and upgrades the row it
+ * inserted. The rule is executed here rather than grepped for, because the
+ * answer arrives asynchronously and must not overwrite an edit or a delete the
+ * user made while it was in flight.
+ */
+import assert from "node:assert/strict";
+import { registerHooks } from "node:module";
+import test from "node:test";
+
+// The workspace `node_modules` is shared with the primary checkout, whose
+// `packages/shared/dist` predates this change. Resolve the package to this
+// worktree's build, so the module under test uses the source being changed.
+const resolution = registerHooks({
+ resolve(specifier, context, nextResolve) {
+ if (specifier === "@pi-desktop/shared") {
+ return nextResolve(
+ new URL("../../../packages/shared/dist/index.js", import.meta.url).href,
+ context,
+ );
+ }
+ return nextResolve(specifier, context);
+ },
+});
+const { applyCustomModelLookup, customModelLookupInput, customModelSeedBinding } =
+ await import("../src/components/settings/model-custom-lookup.ts");
+resolution.deregister();
+
+/** A published record as the host returns it from the local snapshot. */
+const published = {
+ modelId: "claude-opus-4.6",
+ providerId: "",
+ displayName: "Claude Opus 4.6",
+ reasoning: true,
+ supportedThinkingLevels: ["low", "medium", "high"],
+ modalities: { input: ["text", "image"], output: ["text"] },
+ limit: { context: 1_000_000, output: 128_000 },
+ capabilities: ["text", "vision"],
+ source: "discovered",
+};
+
+test("a lookup hit seeds the row with the published limits and thinking levels", () => {
+ const seed = customModelSeedBinding("Claude-Opus-4.6", null);
+ // Before the answer: the generic seed.
+ assert.equal(seed.contextWindow, 128_000);
+ assert.equal(seed.maxTokens, 8_192);
+
+ const next = applyCustomModelLookup([seed], seed, published);
+ assert.equal(next.length, 1);
+ assert.equal(next[0].contextWindow, 1_000_000);
+ assert.equal(next[0].contextWindowSource, "catalog");
+ assert.equal(next[0].maxTokens, 128_000);
+ assert.deepEqual(next[0].thinkingLevels, ["low", "medium", "high"]);
+});
+
+test("the upgraded row keeps the id the user typed", () => {
+ const seed = customModelSeedBinding("Claude-Opus-4.6", null);
+ const [upgraded] = applyCustomModelLookup([seed], seed, published);
+ assert.equal(upgraded.id, "Claude-Opus-4.6");
+});
+
+test("a miss keeps the generic seed and never drops the row", () => {
+ const seed = customModelSeedBinding("not-published", null);
+ const next = applyCustomModelLookup([seed], seed, null);
+ assert.equal(next[0], seed);
+ assert.equal(next[0].contextWindow, 128_000);
+ assert.equal(next[0].maxTokens, 8_192);
+ assert.deepEqual(next[0].thinkingLevels, []);
+});
+
+test("an edit made while the lookup was in flight is not overwritten", () => {
+ const seed = customModelSeedBinding("Claude-Opus-4.6", null);
+ const edited = { ...seed, contextWindow: 256_000, contextWindowSource: "user" };
+ const next = applyCustomModelLookup([edited], seed, published);
+ assert.equal(next[0], edited);
+ assert.equal(next[0].contextWindow, 256_000);
+});
+
+test("a row removed while the lookup was in flight is not resurrected", () => {
+ const seed = customModelSeedBinding("Claude-Opus-4.6", null);
+ assert.deepEqual(applyCustomModelLookup([], seed, published), []);
+});
+
+test("a discovered row is used as-is instead of a second lookup", () => {
+ // The current discovery already went through models.dev, so its record is
+ // authoritative and its service-written id is the one to keep.
+ const binding = customModelSeedBinding("whatever-case", published);
+ assert.equal(binding.contextWindow, 1_000_000);
+ assert.equal(binding.id, published.modelId);
+});
+
+test("the lookup input carries only the context this entry has", () => {
+ assert.deepEqual(customModelLookupInput("m"), { modelId: "m" });
+ assert.deepEqual(
+ customModelLookupInput("m", {
+ providerId: "p",
+ vendorKey: "anthropic",
+ baseUrl: "https://api.anthropic.com",
+ }),
+ {
+ modelId: "m",
+ providerId: "p",
+ vendorKey: "anthropic",
+ baseUrl: "https://api.anthropic.com",
+ },
+ );
+ // An unsaved provider has no id and an untouched URL field is blank.
+ assert.deepEqual(customModelLookupInput("m", { providerId: "", baseUrl: "" }), {
+ modelId: "m",
+ });
+});
diff --git a/apps/desktop/test/provider-lookup-model-handler.test.mjs b/apps/desktop/test/provider-lookup-model-handler.test.mjs
new file mode 100644
index 000000000..d7664208d
--- /dev/null
+++ b/apps/desktop/test/provider-lookup-model-handler.test.mjs
@@ -0,0 +1,172 @@
+/**
+ * Contract test for the custom-model library lookup.
+ *
+ * A hand-typed custom id exists nowhere in any provider's list, so the settings
+ * picker reads the local models.dev snapshot through one dedicated channel.
+ * This pins the handler contract: it loads the snapshot, resolves the id,
+ * echoes the provider back on the record, answers a miss with `null`, and never
+ * touches the host or the network.
+ */
+import assert from "node:assert/strict";
+import * as fs from "node:fs";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import ts from "typescript";
+import { ErrorCodes } from "../../../packages/shared/src/errors.ts";
+import { IPC } from "../../../packages/shared/src/protocol.ts";
+import * as modelsDev from "../electron/main/models-dev-catalog.ts";
+
+/** Minimal CJS loader for the main-process module under test. */
+function load(relative, imports) {
+ const file = new URL(relative, import.meta.url);
+ const { outputText } = ts.transpileModule(fs.readFileSync(file, "utf8"), {
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
+ fileName: file.pathname,
+ });
+ const module = { exports: {} };
+ new Function("require", "exports", "module", outputText)(
+ (id) => {
+ assert.ok(Object.hasOwn(imports, id), `unexpected IPC dependency: ${id}`);
+ return imports[id];
+ },
+ module.exports,
+ module,
+ );
+ return module.exports;
+}
+
+const fixture = {
+ anthropic: {
+ name: "Anthropic",
+ api: "https://api.anthropic.com",
+ models: {
+ "claude-opus-4.6": {
+ id: "claude-opus-4.6",
+ name: "Claude Opus 4.6",
+ reasoning: true,
+ reasoning_options: [{ type: "effort", values: ["low", "medium", "high"] }],
+ modalities: { input: ["text", "image"], output: ["text"] },
+ limit: { context: 1_000_000, output: 128_000 },
+ },
+ },
+ },
+};
+
+async function fixtureCatalog(t) {
+ const dir = await mkdtemp(join(tmpdir(), "pi-lookup-model-"));
+ t.after(() => rm(dir, { recursive: true, force: true }));
+ const catalogPath = join(dir, "api.json");
+ await writeFile(catalogPath, JSON.stringify(fixture), "utf8");
+ const catalog = new modelsDev.ModelsDevCatalog({ catalogPath });
+ assert.equal(await catalog.ensureLoaded(), true);
+ return catalog;
+}
+
+/**
+ * Register the real handler with a fake catalog and a fake registrar, then
+ * expose only the lookup channel.
+ */
+function harness(realCatalog) {
+ const handlers = new Map();
+ const catalogCalls = [];
+ const hostCalls = [];
+ const modelsDevCatalog = {
+ ensureLoaded: async () => {
+ catalogCalls.push("ensureLoaded");
+ return realCatalog.ensureLoaded();
+ },
+ findModel: (input) => {
+ catalogCalls.push(["findModel", input]);
+ return realCatalog.findModel(input);
+ },
+ };
+ const { registerProviderIpc } = load("../electron/main/ipc/provider-ipc.ts", {
+ "@pi-desktop/shared": {
+ IPC,
+ ErrorCodes,
+ resolveBindingContextWindow: () => ({}),
+ },
+ "../oauth": { OAUTH_AUTH_KIND: "oauth" },
+ "../model-discovery": {
+ discoverProviderModels: async () => {
+ throw new Error("the lookup must not probe the network");
+ },
+ },
+ "@pi-desktop/agent-runtime": {},
+ "../models-dev-catalog": modelsDev,
+ "../host-process": {},
+ "../logger": { app: () => {} },
+ "./types": {},
+ });
+ registerProviderIpc({
+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },
+ getHost: () => ({
+ call: async (method) => {
+ hostCalls.push(method);
+ throw new Error("the lookup must not call the host");
+ },
+ }),
+ modelsDevCatalog,
+ vendorOAuth: {},
+ logger: { app: () => {} },
+ enrichProvider: (provider) => provider,
+ listRuntimeProviders: async () => [],
+ enrichProviderList: async (result) => result,
+ bindingForModel: () => undefined,
+ });
+ const handler = handlers.get(IPC.invoke.providersLookupModel);
+ assert.equal(typeof handler, "function", "lookup handler is not registered");
+ return { call: (input) => handler(input), catalogCalls, hostCalls };
+}
+
+test("a published id returns the snapshot record for the typed id", async (t) => {
+ const h = harness(await fixtureCatalog(t));
+ const result = await h.call({
+ modelId: "Claude-Opus-4.6",
+ providerId: "provider-1",
+ vendorKey: "anthropic",
+ });
+ assert.ok(result.info, "a published id must return its record");
+ assert.equal(result.info.modelId, "claude-opus-4.6");
+ assert.equal(result.info.providerId, "provider-1");
+ assert.equal(result.info.contextWindow, 1_000_000);
+ assert.equal(result.info.maxTokens, 128_000);
+ for (const level of ["low", "medium", "high"]) {
+ assert.ok(result.info.supportedThinkingLevels.includes(level));
+ }
+ // Snapshot read: load then resolve, in that order, and nothing else.
+ assert.deepEqual(h.catalogCalls[0], "ensureLoaded");
+ assert.equal(h.catalogCalls[1][0], "findModel");
+ assert.deepEqual(h.catalogCalls[1][1], {
+ vendorKey: "anthropic",
+ baseUrl: undefined,
+ modelId: "Claude-Opus-4.6",
+ });
+ assert.deepEqual(h.hostCalls, []);
+});
+
+test("an id the library does not publish answers null", async (t) => {
+ const h = harness(await fixtureCatalog(t));
+ const result = await h.call({ modelId: "not-in-the-library" });
+ assert.deepEqual(result, { info: null });
+ assert.equal(h.catalogCalls[0], "ensureLoaded");
+ assert.deepEqual(h.hostCalls, []);
+});
+
+test("a blank id answers null without loading or resolving", async (t) => {
+ const h = harness(await fixtureCatalog(t));
+ assert.deepEqual(await h.call({ modelId: " " }), { info: null });
+ assert.deepEqual(h.catalogCalls, []);
+ assert.deepEqual(h.hostCalls, []);
+});
+
+test("the catalog lookup never probes the provider or the host", async (t) => {
+ // The fake discovery throws and the fake host records, so any network or
+ // host path taken by the handler fails this test instead of passing silently.
+ const h = harness(await fixtureCatalog(t));
+ await h.call({ modelId: "claude-opus-4.6" });
+ await h.call({ modelId: "missing" });
+ assert.deepEqual(h.hostCalls, []);
+});
diff --git a/apps/desktop/test/provider-model-config.test.mjs b/apps/desktop/test/provider-model-config.test.mjs
index 4f22674f2..a465f1a2c 100644
--- a/apps/desktop/test/provider-model-config.test.mjs
+++ b/apps/desktop/test/provider-model-config.test.mjs
@@ -297,3 +297,40 @@ test("selected models reorder from a dedicated handle, not the copyable id", ()
assert.match(styles, /\.provider-chosen-row\.is-dragging\s*\{/);
assert.match(styles, /\.provider-chosen-row\[data-drop-placement\]::after/);
});
+
+test("adding a service only claims the app default while none resolves", () => {
+ // The add branch used to write defaultProviderId/defaultModelId
+ // unconditionally, so configuring a second service silently moved the app
+ // default away from the one the user was already running.
+ const branch = pageSource.match(
+ /\} else if \(!editingProvider\) \{([\s\S]*?)\n \} else \{/,
+ );
+ assert.ok(branch, "the add-provider branch moved");
+ const guard = branch[1].indexOf("hasResolvedDefaultModel(");
+ const write = branch[1].indexOf("api.setSettings(");
+ assert.ok(guard >= 0, "the add branch must ask whether a default already resolves");
+ assert.ok(write > guard, "the default write must sit inside that guard");
+ // Which provider wins is decided by the shared resolver, whose behaviour is
+ // pinned by default-model-display.test.mjs.
+ assert.match(pageSource, /hasResolvedDefaultModel,\n\} from "\.\/default-model"/);
+});
+
+test("a saved image selection never takes the app's image default", () => {
+ // The image default follows the same rule: the candidate list grows, the
+ // default moves only when the stored binding stops resolving. The decision
+ // itself is pinned by image-generation-default.test.mjs.
+ assert.match(pageSource, /planImageGenerationDefaults\(\n\s+current,\n\s+saved\.id,/);
+ assert.doesNotMatch(pageSource, /nextActive/);
+});
+
+test("a hand-typed id is seeded from the model library, not only from generic defaults", () => {
+ // The row is inserted immediately and upgraded in place when the snapshot
+ // answers, so a slow or offline catalog never leaves the list without it. The
+ // rule itself is pinned by model-custom-lookup.test.mjs, and the channel
+ // contract by provider-lookup-model-handler.test.mjs.
+ assert.match(pickerSource, /customModelSeedBinding\(id, discovered\?\.info\)/);
+ assert.match(pickerSource, /applyCustomModelLookup\(current, seed, info\)/);
+ assert.match(pickerSource, /api\.lookupProviderModel\(/);
+ // An id the current discovery already described needs no round trip.
+ assert.match(pickerSource, /if \(!discovered\?\.info\) void enrichCustomModel\(binding\)/);
+});
diff --git a/docs/spec/03-runtime/12-provider-config-schema.md b/docs/spec/03-runtime/12-provider-config-schema.md
index 414441e34..7f8086f30 100644
--- a/docs/spec/03-runtime/12-provider-config-schema.md
+++ b/docs/spec/03-runtime/12-provider-config-schema.md
@@ -136,6 +136,11 @@ models.dev snapshot. Unknown free-form models initially expose
`supportsReasoning=false` and `supportedThinkingLevels=["off"]`; Settings may
still persist an explicit thinking-level binding for an endpoint that supports
it. The raw secret and internal compatibility JSON remain hidden.
+A hand-typed custom model id is matched against that snapshot before its
+binding is seeded (`providers.lookupModel`, §9), so a published record supplies
+the binding's context window, max output tokens, and thinking levels even
+though the id is absent from every discovered list; an unpublished id keeps the
+generic seed.
Anthropic Messages providers may store either the service root or a URL ending
in `/v1`. Model discovery preserves that configured path and requests
@@ -432,6 +437,7 @@ change for the raw snapshot.
- `providers.delete`
- `providers.testConnection`
- `providers.listModels`
+- `providers.lookupModel`
- `providers.cacheModels` (internal Electron-main to host persistence bridge)
- `providers.refreshModels`
- `providers.upsertUserModel`
@@ -543,6 +549,26 @@ The canonical DDL lives in [04-data-storage](04-data-storage.md) (D086). Summary
modalities, output types, and capability tags. Cached/provider claims cannot
override the local catalog record.
+### `providers.lookupModel`
+- renderer IPC in: `{ modelId, baseUrl?, providerId?, vendorKey? }`
+- out: `{ info: ModelInfo | null }`
+- reads only the local models.dev snapshot: `ensureLoaded` then `findModel`,
+ with no provider network access and no host RPC. `vendorKey` and `baseUrl`
+ only disambiguate which published provider owns a duplicate id; `providerId`
+ is echoed back on the returned record for the settings surface.
+- exists because `providers.listModels` only describes a saved or reached
+ provider's catalogue: a hand-typed custom id has no other channel to its
+ published limits before the provider is saved.
+- a hit seeds the new binding exactly like a picked model
+ (`bindingFromModelInfo`): published context window, max output tokens, and
+ thinking levels, with `contextWindowSource: "catalog"`, while the stored id
+ stays exactly what the user typed (`bindingForCustomModelInfo`). A miss
+ (`null`) keeps today's behavior: the picker seeds the custom binding with the
+ generic 128,000 / 8,192 defaults and no thinking levels
+ (`bindingForCustomModel`). The row is written first and upgraded in place, so
+ a slow, failed, or unpublished lookup still leaves exactly one usable row and
+ never overwrites an edit or delete made while it was in flight.
+
### `providers.cacheModels` (internal host RPC)
- in: `{ providerId, models: DiscoveredModelInput[] }`
- behavior: transactionally upsert successful live discovery into `models` as
diff --git a/docs/spec/03-runtime/13-model-catalog-and-selection.md b/docs/spec/03-runtime/13-model-catalog-and-selection.md
index f05863ab9..9654e09be 100644
--- a/docs/spec/03-runtime/13-model-catalog-and-selection.md
+++ b/docs/spec/03-runtime/13-model-catalog-and-selection.md
@@ -98,7 +98,12 @@ default. When the edited service or account is the app's default provider,
saving also synchronizes the app-level default model to that first binding,
as the existing save flow does. The app default is unchanged when editing
another provider, and an explicitly bound session keeps its stored model
-choice. No storage schema or IPC contract changes are required.
+choice. Adding a provider is not a way to change either app default: the
+default model, and the default image model when the new service brings image
+models, move to it only while nothing resolves for the app — an empty
+selection, or one whose provider or model is gone. A default the user can
+still run stays where it is until they repoint it. No storage schema or IPC
+contract changes are required.
### Discovery precedence
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 9156ef995..ac2fcbe99 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -538,6 +538,26 @@ identify the platform validation still needed.
- **Milestone**: M2
- **Status**: Manual UI + automated protocol smoke (provider create + secret, no plaintext echo)
+#### E2E-PROVIDER-defaults-survive-an-added-provider: An added provider leaves the app defaults alone
+
+- **Preconditions**: App running; provider A saved and set as the app default model; a second provider B serving different models; one image-capable model configured on A and another on a different service.
+- **Steps**: 1) Open Settings → Model configuration and add provider B; save without touching the Default model row. 2) Confirm the Default model row still names provider A and its exact model, and that a new session starts on it. 3) Set an image model as the default image model, then add a provider that also serves image models; save. 4) Confirm the Default image model row still names the earlier binding while the picker lists the new provider's image models as candidates. 5) Delete the provider that owned a default, then add a service that serves a model and an image model; save. 6) Confirm both defaults now resolve to that newly added provider.
+- **Expected**: Saving a new provider never repoints an app default that still resolves: the model default keeps the pairing the Default model row already renders, and the image default keeps its stored binding while its candidate list grows. Only a default that no longer resolves — its provider deleted, or its model removed from the provider — is filled by the newly added provider, so settings are written only when the app would otherwise have nothing to run. The explicit make-default actions, the edit path, and the fallback to the first remaining binding are unchanged.
+- **Specs linked**: `03-runtime/13-model-catalog-and-selection.md`
+- **Acceptance**: B (model selection)
+- **Milestone**: M6
+- **Status**: Documented; covered by `apps/desktop/test/default-model-display.test.mjs`, `apps/desktop/test/image-generation-default.test.mjs`, `apps/desktop/test/provider-model-config.test.mjs`
+
+#### E2E-PROVIDER-custom-model-limits: A hand-typed custom model id takes its limits from the model library
+
+- **Preconditions**: App running; the models.dev snapshot ships with the build; a provider editor is open.
+- **Steps**: 1) Type a model id the snapshot publishes into the add-model field and add it; confirm the new row's context window, max output tokens and thinking levels match the published record instead of 128,000 / 8,192 with none. 2) Type an id the snapshot does not publish and add it; confirm the row keeps the generic 128,000 / 8,192 seed and no thinking levels. 3) Add an id while the service list is unreachable; confirm the row still appears exactly once and stays editable. 4) Add an id and edit its limits immediately, before the lookup answers; confirm the typed values survive.
+- **Expected**: `providers.lookupModel` answers a hand-typed id from the local snapshot only — no provider network request and no host call — and a hit seeds the binding the way a picked model is seeded (published context window, max output tokens, thinking levels, `contextWindowSource: "catalog"`) while the stored id stays exactly what the user typed. A miss, a failed call, or an id the current discovery already described leaves the previous behavior intact: one usable row, the generic seed, and no stalled or duplicated list.
+- **Specs linked**: `03-runtime/12-provider-config-schema.md`, `03-runtime/13-model-catalog-and-selection.md`
+- **Acceptance**: B (multi-model provider configuration)
+- **Milestone**: M2
+- **Status**: Documented; covered by `apps/desktop/test/model-custom-lookup.test.mjs` and `apps/desktop/test/provider-lookup-model-handler.test.mjs`
+
#### E2E-PROVIDER-configured-models-search: The chosen pane's search narrows the configured list
- **Preconditions**: App running; one provider saved with at least three model bindings, one of them carrying an alias and another whose catalog display name differs from its id.
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index 6908216d1..cfeb5e519 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -6556,3 +6556,42 @@ that was sitting at the bottom — including after the turn had finished.
- `contextWindow` and `maxTokens` are therefore optional on the wire, and each entry of the array is decoded on its own. An absent key, or an explicit `0`, reads as zero and is seeded with the generic default (128,000 / 8,192) by the normalisation that already existed for the explicit zero — the same value a record carrying only `defaultModelId` is materialized with, and the same value a plugin manifest that declares no limits already produces. The two paths now agree instead of one rejecting what the other accepts.
- An entry that still fails to decode costs itself, not the array: the readable entries survive in their stored order, and the failure is reported on the host log with the provider id, the entry's index and the reason, so it is locatable rather than silent. An absent `models` key, an empty array, and an array whose every entry was unreadable all still read as the legacy binding, so a provider stays selectable whatever its stored shape; only the third is reported, because an empty array is a legal state and an absent one predates bindings.
- Nothing is rewritten on disk and the write path remains explicit: `providers.update` still persists exactly the bindings the client sends. Before accepting an explicit model-array replacement, the host checks the stored value and rejects it with `MODEL_BINDINGS_DEGRADED` when the value is degraded, so a partial settings view cannot erase unreadable entries; unrelated provider fields remain updatable. See `03-runtime/12-provider-config-schema.md` §2.
+
+## 2026-09-21 — A hand-typed custom model id is seeded from the model library (D611)
+
+- Adding a custom model by id gave every binding the generic 128,000 / 8,192
+ seed and no thinking levels, even when the model library already published
+ that id, so the user had to retype limits the app could have known.
+- The settings picker now matches the typed id against models.dev through a new
+ snapshot-only renderer channel, `providers.lookupModel`, and seeds the binding
+ the way a picked model is seeded — published context window, max output
+ tokens, and thinking levels — while the stored id stays exactly what the user
+ typed. The row is written first with the generic seed and upgraded in place
+ when the answer arrives, so a slow, failed, or unpublished lookup still leaves
+ exactly one usable row, and an edit or delete made meanwhile is never
+ overwritten.
+- No provider network request, host call, schema, or persisted-data change; a
+ miss behaves exactly as before. See `03-runtime/12-provider-config-schema.md`
+ §2 and §9.
+
+## 2026-09-21 — Adding a provider never takes over an app default (D612)
+
+- The provider add flow wrote `defaultProviderId`/`defaultModelId`, and the
+ image flow wrote `imageGeneration`, whether or not the app already had one, so
+ configuring a second service silently moved the default away from the model
+ the user was running.
+- The add flow now follows the rule editing already followed: a stored default
+ survives while it still resolves, and only an unresolvable one is replaced.
+ For the model default that means the default provider row still exists and
+ still offers the model — the same resolution the settings summary renders
+ through — so an id left behind by a deleted provider is not a default and a
+ newly added provider may fill what would otherwise render as unset. The image
+ default uses the mirrored rule against its stored binding, and its candidate
+ list still accumulates the new provider's image models, so nothing vanishes
+ from the picker.
+- Settings are written only when no default resolves; the explicit "make
+ default" action, the edit path, and the fallback to the first remaining
+ binding after removing the selected model are unchanged. Behaviour is pinned
+ by `apps/desktop/test/default-model-display.test.mjs` and
+ `apps/desktop/test/image-generation-default.test.mjs`, with
+ `provider-model-config.test.mjs` asserting the add branch consults them.
diff --git a/docs/zh-CN/spec/03-runtime/12-provider-config-schema.md b/docs/zh-CN/spec/03-runtime/12-provider-config-schema.md
index f6c3fbae8..f523a44a6 100644
--- a/docs/zh-CN/spec/03-runtime/12-provider-config-schema.md
+++ b/docs/zh-CN/spec/03-runtime/12-provider-config-schema.md
@@ -149,6 +149,9 @@ models.dev 快照,之后的目录修正可以替换它;`user` 表示用户
代替模型记录。未知的自由形式模型暴露了 `supportsReasoning=false`
和 `supportedThinkingLevels=["off"]`。原始秘密和内部兼容性
JSON 保持隐藏状态。
+手输的自定义模型 id 会在写入绑定前先与该快照匹配(`providers.lookupModel`,§9):
+即使该 id 不在任何已发现的列表中,已发布的记录也会提供绑定的上下文窗口、最大输出
+token 与思考等级;未发布的 id 仍沿用通用种子值。
`authKind: "oauth"` 标记厂商账户行(ADR 0095、D237):其凭据是保存在
`secret:provider:<id>:oauth` 下的 OAuth 授权,而不是粘贴的密钥,因此该行
@@ -299,6 +302,7 @@ Copilot 的上下文相关请求标头;已保存的同名自定义 header 会
- `providers.delete`
- `providers.testConnection`
- `providers.listModels`
+- `providers.lookupModel`
- `providers.cacheModels`(内部 Electron-main 到主机持久桥)
- `providers.refreshModels`
- `providers.upsertUserModel`
@@ -395,6 +399,20 @@ Copilot 的上下文相关请求标头;已保存的同名自定义 header 会
`reasoning` 功能和 `supportedThinkingLevels`。缓存的功能标签
旧提供程序字段无法覆盖 pi 模型记录。
+### `providers.lookupModel`
+- 渲染器 IPC 入参:`{ modelId, baseUrl?, providerId?, vendorKey? }`
+- 输出:`{ info: ModelInfo | null }`
+- 只读取本地 models.dev 快照:先 `ensureLoaded` 再 `findModel`,不访问提供商网络,
+ 也不调用主机 RPC。`vendorKey` 与 `baseUrl` 仅用于在重复 id 之间消歧归属的发布提供
+ 商;`providerId` 会回显在返回记录上供设置界面使用。
+- 需要它是因为 `providers.listModels` 只描述已保存或已探测提供商的目录:手输的自定义
+ id 在提供商保存前没有别的通道取得其已发布限额。
+- 命中时按拾取模型的口径(`bindingFromModelInfo`)为这条绑定播种:已发布的上下文窗口、
+ 最大输出 token 与思考等级,并标记 `contextWindowSource: "catalog"`;存储的 id 仍是
+ 用户输入的那个(`bindingForCustomModelInfo`)。未命中(`null`)保持今天的行为:按
+ 通用 128,000 / 8,192 与空思考等级播种(`bindingForCustomModel`)。行先落下再原地升级,
+ 因此查询慢、失败或未发布时仍然只留一行可用记录,且不会覆盖期间发生的编辑或删除。
+
### `providers.cacheModels`(内部主机 RPC)
- 在:`{ providerId, models: DiscoveredModelInput[] }`
- 行为:以事务方式将成功的实时发现更新到 `models` 中
diff --git a/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md b/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md
index ad0ee8dba..1e204f516 100644
--- a/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md
+++ b/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md
@@ -44,8 +44,10 @@ AI 服务和 OAuth 厂商账户编辑器共用已选模型面板。每个已选
取消编辑器会丢弃未保存的排序。提供商的兼容字段 `defaultModelId` 仍在保存时反映
首个绑定,因此将模型移至首位会改变该提供商的默认模型。编辑的服务或账户是应用
默认提供商时,保存还会按现有流程将应用级默认模型同步为首个绑定。编辑其他提供商
-不会改变应用默认值,明确绑定模型的会话也会保留其已存储的模型选择。无需修改存储
-结构或 IPC 合约。
+不会改变应用默认值,明确绑定模型的会话也会保留其已存储的模型选择。新增提供商同样不会
+改写这两个应用默认值:默认模型,以及新服务带来图片模型时的默认画图模型,只有在应用
+当前没有可解析的选择时(未设置,或其提供商或模型已不存在)才会落到新服务上;用户仍
+能运行的默认值会一直保留,直到用户自己改。无需修改存储结构或 IPC 合约。
### 物品显示
- 模型显示名称
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index bc396d588..804eeeda3 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -245,6 +245,26 @@ task-candidate E2E 从请求工作树运行,但使用主工作区已经准备
- **里程碑**:M2
- **状态**:自动(协议烟雾:提供商创建+秘密,无明文回显)
+#### E2E-PROVIDER-defaults-survive-an-added-provider:新增提供商不改写应用默认值
+
+- **前提条件**:应用运行;提供商 A 已保存并设为应用默认模型;另有提供商 B 提供不同的模型;A 上配置了一个图片模型,另一家服务上也配置了一个。
+- **步骤**:1) 打开设置 → 模型配置,新增提供商 B,保存时不动「默认模型」行。2) 确认「默认模型」行仍是提供商 A 与其确切模型,且新建会话使用它。3) 将某个图片模型设为默认画图模型,再新增一个同样提供图片模型的服务并保存。4) 确认「默认画图模型」行仍指向原绑定,而选择器的候选里出现新提供商的图片模型。5) 删除拥有默认值的那家提供商,再新增一个既提供对话模型又提供图片模型的服务并保存。6) 确认两个默认值此时都解析到新增的服务。
+- **预期**:新增提供商保存后不会改写仍然可解析的应用默认值:默认模型保留「默认模型」行已经展示的那对提供商/模型,默认画图模型保留其存储绑定,同时候选列表继续增长。只有已无法解析的默认值(提供商被删除,或其模型已从提供商移除)才会由新增的提供商填补,因此只有在应用否则将无从运行时才会写入设置。显式的「设为默认」操作、编辑路径,以及回落到首个剩余绑定的行为都不变。
+- **链接规格**:`03-runtime/13-model-catalog-and-selection.md`
+- **接受**:B(模型选择)
+- **里程碑**:M6
+- **状态**:已文档化;由 `apps/desktop/test/default-model-display.test.mjs`、`apps/desktop/test/image-generation-default.test.mjs`、`apps/desktop/test/provider-model-config.test.mjs` 覆盖
+
+#### E2E-PROVIDER-custom-model-limits:手输的自定义模型 id 从模型库取限额
+
+- **前提条件**:应用运行;models.dev 快照随构建发布;已打开某个提供商编辑器。
+- **步骤**:1) 在「添加模型」输入框里输入模型库已发布的模型 id 并添加,确认新行的上下文长度、最大输出与思考等级与已发布记录一致,而不是 128,000 / 8,192 且无思考等级。2) 输入模型库未发布的 id 并添加,确认该行沿用通用种子 128,000 / 8,192 且无思考等级。3) 在服务模型列表不可用的状态下添加一个 id,确认该行仍然只出现一次且可编辑。4) 添加一个 id 后立刻修改其限额(此时查询尚未返回),确认手输的值被保留。
+- **预期**:`providers.lookupModel` 只从本地快照回答手输 id —— 不访问提供商网络、不调用主机 —— 命中时按「被勾选的模型」同样的口径播种绑定(已发布的上下文长度、最大输出、思考等级,`contextWindowSource: "catalog"`),而存储的 id 保持用户输入的原样。未命中、调用失败,或该 id 已被本次发现结果描述过时,行为与之前一致:一行可用,通用种子,列表既不卡住也不重复。
+- **链接规格**:`03-runtime/12-provider-config-schema.md`、`03-runtime/13-model-catalog-and-selection.md`
+- **接受**:B(多模型提供商配置)
+- **里程碑**:M2
+- **状态**:已文档化;由 `apps/desktop/test/model-custom-lookup.test.mjs` 与 `apps/desktop/test/provider-lookup-model-handler.test.mjs` 覆盖
+
#### E2E-005H:从较长的服务模型列表一次全选当前可见模型
- **前提条件**:应用已运行;添加或编辑服务(或厂商账户)对话框已打开,且该服务返回较长的模型列表,其中至少有一个模型 ID 不会匹配稍后的搜索。
diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.md
index dd2109e30..32bc46abb 100644
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@ -4649,3 +4649,31 @@ that amendment are retired by ADR 0268; the upstream work-panel lifecycle stays.
- 因此 `contextWindow` 与 `maxTokens` 在线为可选,并且数组逐条解码。缺失的键、或显式的 `0`,都读作 0 并由既有的零值归一化补上通用默认值(128,000 / 8,192)——这与只带 `defaultModelId` 的记录被物化时用的是同一个值,也与未声明限额的插件清单已经产生的值相同。两条路径从此一致,而不是一条拒绝另一条接受的东西。
- 仍然解码失败的条目只损失自己,不损失整个数组:可读条目按存储顺序保留,失败会在宿主日志里上报,带上提供商 id、条目下标与原因,因此可定位而不是静默。缺失的 `models` 键、空数组、以及所有条目都不可读的数组,都仍旧读作 legacy 绑定,使提供商无论存储形态如何都保持可选;只有第三种会被上报,因为空数组是合法状态,而缺失键则是早于绑定机制的记录。
- 不改写磁盘上的任何内容,写路径仍是显式的:`providers.update` 依旧只持久化客户端发来的绑定。接受显式模型数组替换前,host 会检查存储值;若已降级则以 `MODEL_BINDINGS_DEGRADED` 拒绝,避免设置页的部分视图擦除不可读条目;不涉及模型数组的提供商字段仍可更新。见 `03-runtime/12-provider-config-schema.md` §2。
+
+## 2026-09-21 —— 手输的自定义模型 id 从模型库播种(D611)
+
+- 通过 id 新增自定义模型时,即便模型库已经发布了该 id,每条绑定仍只得到通用的
+ 128,000 / 8,192 种子值与空思考等级,用户不得不重新输入本可以自动获得的限额。
+- 设置选择器现在通过新的只读快照渲染器通道 `providers.lookupModel` 把输入的 id 与
+ models.dev 匹配,并按拾取模型的口径播种绑定——已发布的上下文窗口、最大输出 token
+ 与思考等级——同时存储的 id 仍保持用户输入的原文。记录先以通用种子值落下,答案返回
+ 后再原地升级;因此查询慢、失败或未发布时仍然只留一行可用记录,期间的编辑或删除也
+ 不会被覆盖。
+- 不访问提供商网络、不调用主机、不改 schema、不改持久化数据;未命中时行为与之前完全
+ 一致。参见 `03-runtime/12-provider-config-schema.md` §2 与 §9。
+
+## 2026-09-21 —— 新增提供商不再抢走应用默认值(D612)
+
+- 新增提供商的流程无条件写入 `defaultProviderId`/`defaultModelId`,画图流程也无条件
+ 写入 `imageGeneration`,于是配置第二个服务会把用户正在使用的默认模型、默认画图模型
+ 悄悄换掉。
+- 新增流程改为与编辑一致的规则:已存储的默认值只要能解析就保留,只有无法解析时才被
+ 替换。模型默认值的“能解析”指默认提供商行仍存在且仍提供该模型——与设置页摘要行渲染
+ 用的是同一套解析——因此提供商被删除后残留的 id 不算默认值,新增的提供商可以填补那
+ 个本来显示为未设置的位置。画图默认值用镜像规则判断其存储绑定,候选列表仍会累积新提
+ 供商的图片模型,选择器里不会少行。
+- 只有在没有任何默认值可解析时才写设置;显式的“设为默认”操作、编辑路径,以及删除已
+ 选模型后回落到首个剩余绑定的行为都不变。行为由
+ `apps/desktop/test/default-model-display.test.mjs` 与
+ `apps/desktop/test/image-generation-default.test.mjs` 固定,
+ `provider-model-config.test.mjs` 断言新增分支会走这两个判断。
diff --git a/packages/shared/src/model-catalog.test.ts b/packages/shared/src/model-catalog.test.ts
index f31a10acb..6186b6740 100644
--- a/packages/shared/src/model-catalog.test.ts
+++ b/packages/shared/src/model-catalog.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import {
bindingForCustomModel,
+ bindingForCustomModelInfo,
bindingFromModelInfo,
bindingSupportsDocuments,
effectiveContextWindow,
@@ -141,6 +142,30 @@ describe("effective binding attachment capabilities", () => {
expect(bindingSupportsImages(custom, null)).toBe(false);
expect(bindingSupportsImages({ supportsImages: true }, null)).toBe(true);
});
+
+describe("a hand-typed id the catalog publishes", () => {
+ it("adopts the published limits and thinking levels", () => {
+ // The user typed a custom id; models.dev knows it, so the row is seeded
+ // like a picked model instead of the generic 128k / 8k seed.
+ const published: ModelInfo = {
+ ...textModel(),
+ reasoning: true,
+ supportedThinkingLevels: ["low", "high"],
+ limit: { context: 1_048_576, output: 64_000 },
+ };
+ const binding = bindingForCustomModelInfo("My-Proxy/Model", published);
+ expect(binding.contextWindow).toBe(1_048_576);
+ expect(binding.contextWindowSource).toBe("catalog");
+ expect(binding.maxTokens).toBe(64_000);
+ expect(binding.thinkingLevels).toEqual(["low", "high"]);
+ });
+
+ it("keeps the id the user typed, not the catalog spelling", () => {
+ const binding = bindingForCustomModelInfo("My-Proxy/Model", textModel());
+ expect(binding.id).toBe("My-Proxy/Model");
+ expect(bindingForCustomModelInfo(" spaced-id ", textModel()).id).toBe("spaced-id");
+ });
+});
});
describe("compact token counts", () => {
diff --git a/packages/shared/src/model-catalog.ts b/packages/shared/src/model-catalog.ts
index 5c212ecb6..913ec2bef 100644
--- a/packages/shared/src/model-catalog.ts
+++ b/packages/shared/src/model-catalog.ts
@@ -252,6 +252,21 @@ export function bindingFromModelInfo(model: ModelInfo): ModelBinding {
};
}
+/**
+ * Binding for a hand-typed id the catalog does publish.
+ *
+ * The published record seeds limits and thinking levels exactly like a picked
+ * model, but the stored id stays what the user typed: the id is the string a
+ * request is addressed with, and a catalog spelling that differs in case or
+ * separators must not silently retarget it.
+ */
+export function bindingForCustomModelInfo(
+ id: string,
+ info: ModelInfo,
+): ModelBinding {
+ return { ...bindingFromModelInfo(info), id: id.trim() };
+}
+
/** Binding for a model id the catalog does not publish. */
export function bindingForCustomModel(id: string): ModelBinding {
return {
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index 7038da6bf..ef28d1ea6 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -181,6 +181,17 @@ export const IPC = {
providersSetSecret: "pi-desktop/providers/setSecret",
providersTest: "pi-desktop/providers/testConnection",
providersListModels: "pi-desktop/providers/listModels",
+ /**
+ * Look one model id up in the local models.dev snapshot.
+ *
+ * `providersListModels` cannot answer this: it describes a saved or
+ * reached provider's catalogue, and a hand-typed custom id exists nowhere
+ * yet when the settings picker needs its published limits. This is a
+ * snapshot read — no provider network access and no host call — so the
+ * picker can seed a custom row without probing an endpoint that does not
+ * know the id.
+ */
+ providersLookupModel: "pi-desktop/providers/lookupModel",
providersRefreshModelCatalog: "pi-desktop/providers/refreshModelCatalog",
providersModelCatalogStatus: "pi-desktop/providers/modelCatalogStatus",
providersOauthVendors: "pi-desktop/providers/oauth/vendors",