Skip to content

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

fix(settings): resolve defaults only through runnable providers

vastsa745d8887b58e
diff --git a/apps/desktop/src/components/settings/ImageGenerationModelRow.tsx b/apps/desktop/src/components/settings/ImageGenerationModelRow.tsx
index 8104993f3..ef1070881 100644
--- a/apps/desktop/src/components/settings/ImageGenerationModelRow.tsx
+++ b/apps/desktop/src/components/settings/ImageGenerationModelRow.tsx
@@ -7,6 +7,7 @@ import {
type ProviderPublic,
} from "@pi-desktop/shared";
import { SettingsMenuSelect } from "./SettingsMenuSelect";
+import { imageGenerationBindingAvailable } from "./image-generation-default";
function imageModelOptionId(binding: ImageGenerationBinding): string {
return `${binding.providerId}\u0000${binding.modelId}`;
@@ -33,16 +34,15 @@ export function ImageGenerationModelRow({
modelIdsMatch(candidate.modelId, binding.modelId),
);
const provider = providers.find((entry) => entry.id === binding.providerId);
- const valid = !!provider?.enabled && provider.authKind !== "oauth" &&
- !!provider.baseUrl && (provider.hasSecret || provider.authKind === "none") &&
- provider.models.some((model) => model.id === binding.modelId);
+ // The same availability rule that decides whether this binding may stay the
+ // app default, so the row can never claim a pairing the runtime rejects.
+ const valid = imageGenerationBindingAvailable(provider, binding.modelId);
const options = candidates.map((candidate) => {
const candidateProvider = providers.find((entry) => entry.id === candidate.providerId);
- const available = candidateProvider?.enabled &&
- candidateProvider.authKind !== "oauth" &&
- !!candidateProvider.baseUrl &&
- (candidateProvider.hasSecret || candidateProvider.authKind === "none") &&
- candidateProvider.models.some((model) => model.id === candidate.modelId);
+ const available = imageGenerationBindingAvailable(
+ candidateProvider,
+ candidate.modelId,
+ );
return {
id: imageModelOptionId(candidate),
label: `${candidateProvider?.name ?? candidate.providerId} · ${candidate.modelId}`,
diff --git a/apps/desktop/src/components/settings/ModelConfigPage.tsx b/apps/desktop/src/components/settings/ModelConfigPage.tsx
index 48ad9a085..f5d80f474 100644
--- a/apps/desktop/src/components/settings/ModelConfigPage.tsx
+++ b/apps/desktop/src/components/settings/ModelConfigPage.tsx
@@ -38,7 +38,8 @@ import { AnchoredMenu } from "./AnchoredMenu";
import {
defaultModelOptions,
displayedDefaultModelId,
- hasResolvedDefaultModel,
+ keepsAppDefaultModel,
+ providerServesChatModels,
} from "./default-model";
import { planImageGenerationDefaults } from "./image-generation-default";
import { copyProviderConfiguration, type ProviderCopyDraft } from "./provider-copy";
@@ -119,10 +120,10 @@ export function ModelConfigPage() {
() => imageGenerationBindings(settings?.imageGenerationModels, settings?.imageGeneration),
[settings?.imageGenerationModels, settings?.imageGeneration],
);
+ // One readiness rule for the picker, the provider rows and the add-provider
+ // guard: both call `providerServesChatModels`.
const providerReady = (provider: ProviderPublic) =>
- provider.enabled &&
- defaultModelOptions([provider], imageGenerationCandidates).length > 0 &&
- (provider.hasSecret || provider.hasOauth || provider.authKind === "none");
+ providerServesChatModels(provider, imageGenerationCandidates);
const aiProviders = useMemo(
() => providers.filter((provider) => provider.authKind !== OAUTH_AUTH_KIND),
@@ -207,11 +208,13 @@ export function ModelConfigPage() {
showToast(t("settings.providerSaved"), { variant: "success" });
} else if (!editingProvider) {
// 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(
+ // the user already picked keeps running — as long as that default's own
+ // provider is still runnable — until they change it themselves.
+ const keepsCurrentDefault = keepsAppDefaultModel(
providers,
settings.defaultProviderId,
settings.defaultModelId,
+ imageGenerationCandidates,
);
if (!keepsCurrentDefault) {
await api.setSettings({
diff --git a/apps/desktop/src/components/settings/default-model.ts b/apps/desktop/src/components/settings/default-model.ts
index f44973f4e..025225895 100644
--- a/apps/desktop/src/components/settings/default-model.ts
+++ b/apps/desktop/src/components/settings/default-model.ts
@@ -87,3 +87,41 @@ export function hasResolvedDefaultModel(
if (!provider) return false;
return !!displayedDefaultModelId(provider, defaultModelId)?.trim();
}
+
+/**
+ * Whether the provider can run a chat default right now: enabled, credentialed
+ * (API key, vendor login or none needed) and actually configuring at least one
+ * non-image model.
+ *
+ * `defaultModelOptions` is the same expansion the default picker lists, so a
+ * provider the picker would not offer cannot hold a default either.
+ */
+export function providerServesChatModels(
+ provider: ProviderPublic,
+ imageGeneration?: ImageGenerationBindings | null,
+): boolean {
+ return provider.enabled &&
+ (provider.hasSecret || !!provider.hasOauth || provider.authKind === "none") &&
+ defaultModelOptions([provider], imageGeneration).length > 0;
+}
+
+/**
+ * Whether adding a provider must leave the app's chat default alone.
+ *
+ * `hasResolvedDefaultModel` alone only asks whether the default provider still
+ * *names* a model, which a disabled or credential-less row does as well: every
+ * session it launches then fails with `PROVIDER_SECRET_MISSING` while the
+ * provider the user just configured is never used. The default therefore counts
+ * as kept only while its provider is runnable — the same readiness the picker
+ * and the provider rows demand.
+ */
+export function keepsAppDefaultModel(
+ providers: readonly ProviderPublic[],
+ defaultProviderId?: string,
+ defaultModelId?: string,
+ imageGeneration?: ImageGenerationBindings | null,
+): boolean {
+ const provider = providers.find((candidate) => candidate.id === defaultProviderId);
+ if (!provider || !providerServesChatModels(provider, imageGeneration)) return false;
+ return hasResolvedDefaultModel(providers, defaultProviderId, defaultModelId);
+}
diff --git a/apps/desktop/src/components/settings/image-generation-default.ts b/apps/desktop/src/components/settings/image-generation-default.ts
index a4371e213..13f91ffe7 100644
--- a/apps/desktop/src/components/settings/image-generation-default.ts
+++ b/apps/desktop/src/components/settings/image-generation-default.ts
@@ -5,24 +5,54 @@
* `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.
+ * survives while a configured provider can actually run it, and only an
+ * unrunnable one is replaced.
+ *
+ * "Can run it" is one rule everywhere: this file, the picker row
+ * (`ImageGenerationModelRow.tsx`) and the runtime
+ * (`electron/main/services/image-generation-service.ts`) all require an
+ * enabled, non-OAuth provider with a base URL, a usable credential and a
+ * configured model exactly matching the binding. A binding that only looks
+ * present — disabled provider, missing key, OAuth-only row, or a model id the
+ * provider does not configure — fails at send time, so it must never be kept as
+ * the default either.
*/
import {
+ MAX_IMAGE_GENERATION_MODELS,
imageGenerationBindings,
+ modelIdsMatch,
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. */
+/**
+ * True when `provider` can actually run `modelId` for image generation now.
+ *
+ * The single source of truth for image availability: stricter than
+ * `providerOffersModel`, which answers "does this row *name* the model" for the
+ * display pairing and ignores whether the row is enabled or credentialed.
+ */
+export function imageGenerationBindingAvailable(
+ provider: ProviderPublic | undefined,
+ modelId: string,
+): boolean {
+ if (!provider || !provider.enabled) return false;
+ return (
+ provider.authKind !== "oauth" &&
+ !!provider.baseUrl &&
+ (provider.hasSecret || provider.authKind === "none") &&
+ provider.models.some((model) => model.id === modelId)
+ );
+}
+
+/** True when the binding can be run by the enabled provider it names. */
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);
+ return imageGenerationBindingAvailable(provider, binding.modelId);
}
export type ImageGenerationDefaultDraft = {
@@ -35,14 +65,41 @@ export type ImageGenerationDefaultPlan = {
imageGeneration: ImageGenerationBinding | null;
};
+/**
+ * Trim the candidate list to the host's cap without dropping the active
+ * binding: the settings channel rejects a longer list outright, and losing the
+ * default's own row would leave the picker unable to show what runs.
+ */
+function cappedImageGenerationCandidates(
+ candidates: readonly ImageGenerationBinding[],
+ active: ImageGenerationBinding | null,
+): ImageGenerationBinding[] {
+ if (candidates.length <= MAX_IMAGE_GENERATION_MODELS) return [...candidates];
+ const activeIndex = active
+ ? candidates.findIndex((candidate) =>
+ candidate.providerId === active.providerId &&
+ modelIdsMatch(candidate.modelId, active.modelId),
+ )
+ : -1;
+ if (activeIndex < MAX_IMAGE_GENERATION_MODELS - 1) {
+ return candidates.slice(0, MAX_IMAGE_GENERATION_MODELS);
+ }
+ const head = candidates
+ .filter((_, index) => index !== activeIndex)
+ .slice(0, MAX_IMAGE_GENERATION_MODELS - 1);
+ return [...head, candidates[activeIndex]];
+}
+
/**
* 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.
+ * candidates of other providers stay listed — minus the rows whose provider no
+ * longer exists, which nothing can pick or run. The active default moves only
+ * when the stored choice stops being runnable, and then to the first candidate
+ * that is, so a newly added provider claims the default exactly when nothing
+ * else can hold it. When nothing can, the default stays empty rather than
+ * naming a binding that would fail on the next request.
*/
export function planImageGenerationDefaults(
current: ImageGenerationDefaultDraft,
@@ -58,14 +115,17 @@ export function planImageGenerationDefaults(
providerId: savedProviderId,
modelId,
}));
- const imageGenerationModels = [
- ...existing.filter((binding) => binding.providerId !== savedProviderId),
- ...selected,
- ];
const active = current.imageGeneration ?? null;
+ const imageGenerationModels = cappedImageGenerationCandidates(
+ [...existing.filter((binding) => binding.providerId !== savedProviderId), ...selected]
+ .filter((binding) =>
+ providers.some((provider) => provider.id === binding.providerId),
+ ),
+ active,
+ );
const fallback = imageGenerationModels.find((binding) =>
resolvesImageGenerationDefault(binding, providers)
- ) ?? imageGenerationModels[0] ?? null;
+ ) ?? null;
return {
imageGenerationModels,
imageGeneration: resolvesImageGenerationDefault(active, providers) ? active : fallback,
diff --git a/apps/desktop/test/default-model-display.test.mjs b/apps/desktop/test/default-model-display.test.mjs
index ffa8c778a..6d7848364 100644
--- a/apps/desktop/test/default-model-display.test.mjs
+++ b/apps/desktop/test/default-model-display.test.mjs
@@ -12,7 +12,9 @@ import test from "node:test";
import {
defaultModelIdOf,
displayedDefaultModelId,
+ keepsAppDefaultModel,
providerOffersModel,
+ providerServesChatModels,
hasResolvedDefaultModel,
} from "../src/components/settings/default-model.ts";
@@ -130,3 +132,110 @@ test("an empty default resolves to nothing, so the new provider claims it", () =
// the row renders the empty state, so the next provider may fill it.
assert.equal(hasResolvedDefaultModel([empty], "p1", "gpt-5"), false);
});
+
+/**
+ * Which provider owns the app default after a new one is added.
+ *
+ * `hasResolvedDefaultModel` only asks whether the default provider still
+ * *names* a model — a disabled or credential-less row does — so on its own it
+ * keeps a default whose every launch dies with `PROVIDER_SECRET_MISSING` while
+ * the provider the user just configured is never used. `keepsAppDefaultModel`
+ * adds the readiness the picker already demands. The branch below mirrors the
+ * add-provider branch of `ModelConfigPage.afterSaved`.
+ */
+const addProvider = (providers, settings, saved) => {
+ const firstModelId = saved.models[0]?.id;
+ if (!keepsAppDefaultModel(
+ providers,
+ settings.defaultProviderId,
+ settings.defaultModelId,
+ settings.imageGenerationModels,
+ )) {
+ return { ...settings, defaultProviderId: saved.id, defaultModelId: firstModelId ?? "" };
+ }
+ return settings;
+};
+test("a runnable default provider keeps the app default when one is added", () => {
+ const current = provider({ models: [binding("gpt-5"), binding("gpt-5-mini")] });
+ const added = provider({ id: "p2", name: "Provider Two", models: [binding("llama-4")] });
+ const settings = { defaultProviderId: "p1", defaultModelId: "gpt-5-mini" };
+ assert.equal(keepsAppDefaultModel([current], "p1", "gpt-5-mini"), true);
+ assert.deepEqual(addProvider([current], settings, added), {
+ defaultProviderId: "p1",
+ defaultModelId: "gpt-5-mini",
+ });
+});
+test("a default provider without a usable key lets the new provider take over", () => {
+ // The real user path: the key was removed (or never entered) while
+ // `defaultProviderId` kept pointing at the row, so the next session failed.
+ const starved = provider({
+ models: [binding("gpt-5"), binding("gpt-5-mini")],
+ hasSecret: false,
+ hasOauth: false,
+ });
+ const added = provider({ id: "p2", name: "Provider Two", models: [binding("llama-4")] });
+ const settings = { defaultProviderId: "p1", defaultModelId: "gpt-5-mini" };
+ // The old guard asked only this and answered yes, which was the regression.
+ assert.equal(hasResolvedDefaultModel([starved], "p1", "gpt-5-mini"), true);
+ assert.equal(keepsAppDefaultModel([starved], "p1", "gpt-5-mini"), false);
+ assert.deepEqual(addProvider([starved], settings, added), {
+ defaultProviderId: "p2",
+ defaultModelId: "llama-4",
+ });
+});
+
+test("a disabled default provider lets the new provider take over", () => {
+ const off = provider({ models: [binding("gpt-5")], enabled: false });
+ const added = provider({ id: "p2", name: "Provider Two", models: [binding("llama-4")] });
+ assert.equal(keepsAppDefaultModel([off], "p1", "gpt-5"), false);
+ assert.equal(
+ addProvider([off], { defaultProviderId: "p1", defaultModelId: "gpt-5" }, added)
+ .defaultProviderId,
+ "p2",
+ );
+});
+
+test("a default provider with nothing left to run lets the new provider take over", () => {
+ // Either no chat model at all, or only the image model the default picker
+ // excludes: both leave the default provider unable to run anything.
+ const bare = provider({ models: [], defaultModelId: undefined });
+ const imageOnly = provider({ models: [binding("gpt-image-1")] });
+ const added = provider({ id: "p2", name: "Provider Two", models: [binding("llama-4")] });
+ assert.equal(providerServesChatModels(bare), false);
+ assert.equal(keepsAppDefaultModel([bare], "p1", ""), false);
+ assert.equal(
+ keepsAppDefaultModel([imageOnly], "p1", "gpt-image-1", {
+ providerId: "p1",
+ modelId: "gpt-image-1",
+ }),
+ false,
+ );
+ assert.equal(
+ addProvider([bare], { defaultProviderId: "p1", defaultModelId: "" }, added)
+ .defaultProviderId,
+ "p2",
+ );
+});
+
+test("a vendor-login default provider still holds the default", () => {
+ // OAuth is a valid chat credential even though image generation refuses it,
+ // so the add guard must not turn this into a stolen default.
+ const vendor = provider({
+ models: [binding("claude-opus-4.6")],
+ authKind: "oauth",
+ hasSecret: true,
+ hasOauth: true,
+ });
+ assert.equal(providerServesChatModels(vendor), true);
+ assert.equal(keepsAppDefaultModel([vendor], "p1", "claude-opus-4.6"), true);
+});
+
+test("a default provider that is gone still lets the new provider take over", () => {
+ const added = provider({ id: "p2", name: "Provider Two", models: [binding("llama-4")] });
+ assert.equal(keepsAppDefaultModel([added], "deleted-provider", "gpt-5"), false);
+ assert.equal(
+ addProvider([added], { defaultProviderId: "deleted-provider", defaultModelId: "gpt-5" }, added)
+ .defaultProviderId,
+ "p2",
+ );
+});
diff --git a/apps/desktop/test/image-generation-default.test.mjs b/apps/desktop/test/image-generation-default.test.mjs
index 6ee77d197..c607ca004 100644
--- a/apps/desktop/test/image-generation-default.test.mjs
+++ b/apps/desktop/test/image-generation-default.test.mjs
@@ -5,7 +5,13 @@
* `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.
+ * choice stops being *runnable*.
+ *
+ * "Runnable" is the strict rule the picker row and the runtime apply: enabled
+ * provider, non-OAuth, base URL, a usable credential and one of the provider's
+ * configured models matched exactly. `providerOffersModel` is deliberately
+ * looser — it answers whether a row *names* a model for the summary line — so
+ * the assertions here must not accept it as proof that a default can run.
*/
import assert from "node:assert/strict";
import { register } from "node:module";
@@ -13,18 +19,24 @@ 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 {
+ imageGenerationBindingAvailable,
+ planImageGenerationDefaults,
+ resolvesImageGenerationDefault,
+} = await import("../src/components/settings/image-generation-default.ts");
+const { MAX_IMAGE_GENERATION_MODELS } = await import("@pi-desktop/shared");
-const provider = (id, modelIds) => ({
+/** A runnable image provider row; `over` overrides any field. */
+const provider = (id, modelIds, over = {}) => ({
id,
name: id,
enabled: true,
hasSecret: true,
hasOauth: false,
authKind: "api_key_and_base_url",
+ baseUrl: "https://example.test/v1",
models: modelIds.map((modelId) => ({ id: modelId })),
+ ...over,
});
const binding = (providerId, modelId) => ({ providerId, modelId });
@@ -59,6 +71,8 @@ test("a legacy default stored without a candidate list is kept too", () => {
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.
+ // The dead binding is dropped from the candidates as well — nothing can pick
+ // a provider row that is gone, and the host would keep it forever.
const plan = planImageGenerationDefaults(
{
imageGenerationModels: [binding("gone", "img-gone")],
@@ -68,10 +82,7 @@ test("a default that no longer resolves gives way to a provider that does", () =
["img-y"],
[provider("y", ["img-y"])],
);
- assert.deepEqual(plan.imageGenerationModels, [
- binding("gone", "img-gone"),
- binding("y", "img-y"),
- ]);
+ assert.deepEqual(plan.imageGenerationModels, [binding("y", "img-y")]);
assert.deepEqual(plan.imageGeneration, binding("y", "img-y"));
});
@@ -107,12 +118,16 @@ test("editing a provider replaces its own candidates only", () => {
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,
- );
+/**
+ * Availability, not naming. The default is kept only while the provider can
+ * actually run the model, so every state that would fail on the next request is
+ * treated as unresolvable.
+ */
+test("resolving requires a runnable provider row", () => {
+ const providers = [provider("x", ["img-x"])];
+ assert.equal(resolvesImageGenerationDefault(null, providers), false);
+ assert.equal(resolvesImageGenerationDefault(undefined, providers), false);
+ assert.equal(resolvesImageGenerationDefault(binding("x", "img-x"), providers), true);
// Another provider serving the same id is not the configured one.
assert.equal(
resolvesImageGenerationDefault(binding("x", "img-x"), [provider("z", ["img-x"])]),
@@ -123,7 +138,157 @@ test("resolving follows the provider row, not the candidate list", () => {
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);
+ // Covered in default-model-display.test.mjs: `providerOffersModel` accepts
+ // all of these, which is exactly why the default must not use it.
+ assert.equal(
+ resolvesImageGenerationDefault(binding("x", "img-x"), [
+ provider("x", ["img-x"], { enabled: false }),
+ ]),
+ false,
+ "a disabled provider cannot run the stored default",
+ );
+ assert.equal(
+ resolvesImageGenerationDefault(binding("x", "img-x"), [
+ provider("x", ["img-x"], { hasSecret: false, hasOauth: false }),
+ ]),
+ false,
+ "a provider without a stored key cannot run the stored default",
+ );
+ // A legacy OAuth-style row storing only `defaultModelId` used to count as
+ // resolving. It names a model without configuring one, and the runtime
+ // requires `provider.models` to contain it, so it must not keep the default.
+ const legacyOnly = { ...provider("x", []), defaultModelId: "img-x" };
+ assert.equal(imageGenerationBindingAvailable(legacyOnly, "img-x"), false);
+ assert.equal(
+ resolvesImageGenerationDefault(binding("x", "img-x"), [legacyOnly]),
+ false,
+ "a row with no configured model cannot run anything",
+ );
+ assert.equal(
+ resolvesImageGenerationDefault(binding("x", "img-x"), [
+ provider("x", ["img-x"], { authKind: "oauth", hasOauth: true, hasSecret: true }),
+ ]),
+ false,
+ "image generation has no OAuth path",
+ );
+ assert.equal(
+ resolvesImageGenerationDefault(binding("x", "img-x"), [
+ provider("x", ["img-x"], { baseUrl: undefined }),
+ ]),
+ false,
+ "an unaddressed provider cannot run the stored default",
+ );
+ // A no-auth row needs no key at all.
+ assert.equal(
+ resolvesImageGenerationDefault(binding("x", "img-x"), [
+ provider("x", ["img-x"], { authKind: "none", hasSecret: false }),
+ ]),
+ true,
+ );
+ // Exact equality, like the runtime: a vendor-prefixed spelling is a different
+ // binding, and the prefix-tolerant chat matcher must not leak in here.
+ assert.equal(
+ resolvesImageGenerationDefault(binding("x", "img-x"), [
+ provider("x", ["openai/img-x"]),
+ ]),
+ false,
+ );
+});
+
+test("the fallback is the first runnable candidate, never just the first one", () => {
+ const plan = planImageGenerationDefaults(
+ {
+ imageGenerationModels: [binding("x", "img-x"), binding("y", "img-y")],
+ imageGeneration: binding("x", "img-x"),
+ },
+ "z",
+ ["img-z"],
+ [
+ provider("x", ["img-x"], { hasSecret: false }), // listed, not runnable
+ provider("y", ["img-y"]),
+ provider("z", ["img-z"]),
+ ],
+ );
+ assert.deepEqual(plan.imageGenerationModels, [
+ binding("x", "img-x"),
+ binding("y", "img-y"),
+ binding("z", "img-z"),
+ ]);
+ // The old behaviour kept x/img-x: the row existed, so the picker showed a
+ // pairing the runtime then refused to run.
+ assert.deepEqual(plan.imageGeneration, binding("y", "img-y"));
+});
+
+test("nothing runnable leaves the default empty instead of a dead binding", () => {
+ const plan = planImageGenerationDefaults(
+ {
+ imageGenerationModels: [binding("x", "img-x")],
+ imageGeneration: binding("x", "img-x"),
+ },
+ "y",
+ ["img-y"],
+ [
+ provider("x", ["img-x"], { enabled: false }),
+ provider("y", ["img-y"], { authKind: "oauth", hasOauth: true }),
+ ],
+ );
+ assert.equal(plan.imageGeneration, null);
+});
+
+test("candidates of a removed provider are dropped, the runnable ones stay", () => {
+ const plan = planImageGenerationDefaults(
+ {
+ imageGenerationModels: [
+ binding("gone", "img-gone"),
+ binding("x", "img-x"),
+ ],
+ imageGeneration: binding("x", "img-x"),
+ },
+ "x",
+ ["img-x"],
+ [provider("x", ["img-x"])],
+ );
+ assert.deepEqual(plan.imageGenerationModels, [binding("x", "img-x")]);
+ assert.deepEqual(plan.imageGeneration, binding("x", "img-x"));
+});
+
+test("a long candidate list is capped like the host and keeps the active binding", () => {
+ // The settings channel rejects more than MAX_IMAGE_GENERATION_MODELS rows, so
+ // the plan has to trim the tail itself instead of saving a list the host
+ // refuses — the same cap the parser enforces.
+ const many = Array.from({ length: MAX_IMAGE_GENERATION_MODELS + 2 }, (_, index) => ({
+ binding: binding(`p${index}`, `img-${index}`),
+ provider: provider(`p${index}`, [`img-${index}`]),
+ }));
+ const providers = many.map((entry) => entry.provider);
+ const candidates = many.map((entry) => entry.binding);
+
+ const capped = planImageGenerationDefaults(
+ { imageGenerationModels: candidates, imageGeneration: null },
+ "p0",
+ ["img-0"],
+ providers,
+ );
+ assert.equal(capped.imageGenerationModels.length, MAX_IMAGE_GENERATION_MODELS);
+ // The saved provider's rows move to the tail, so the first runnable
+ // candidate is the one the cap kept at the head.
+ assert.deepEqual(capped.imageGeneration, capped.imageGenerationModels[0]);
+
+ // An active binding that sits past the cut must survive the trim, otherwise
+ // the default points at a candidate the picker can no longer show.
+ const active = candidates[candidates.length - 1];
+ const kept = planImageGenerationDefaults(
+ { imageGenerationModels: candidates, imageGeneration: active },
+ "p0",
+ ["img-0"],
+ providers,
+ );
+ assert.equal(kept.imageGenerationModels.length, MAX_IMAGE_GENERATION_MODELS);
+ assert.deepEqual(kept.imageGeneration, active);
+ assert.ok(
+ kept.imageGenerationModels.some((entry) =>
+ entry.providerId === active.providerId && entry.modelId === active.modelId
+ ),
+ "the active binding must stay in the capped candidate list",
+ );
});
diff --git a/apps/desktop/test/provider-model-config.test.mjs b/apps/desktop/test/provider-model-config.test.mjs
index a465f1a2c..8aae8f2b4 100644
--- a/apps/desktop/test/provider-model-config.test.mjs
+++ b/apps/desktop/test/provider-model-config.test.mjs
@@ -306,13 +306,18 @@ test("adding a service only claims the app default while none resolves", () => {
/\} else if \(!editingProvider\) \{([\s\S]*?)\n \} else \{/,
);
assert.ok(branch, "the add-provider branch moved");
- const guard = branch[1].indexOf("hasResolvedDefaultModel(");
+ const guard = branch[1].indexOf("keepsAppDefaultModel(");
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"/);
+ // pinned by default-model-display.test.mjs. That resolver also requires the
+ // default provider to be runnable (enabled, credentialed, a chat model
+ // configured), so a keyless default row cannot block the new provider.
+ assert.match(pageSource, /keepsAppDefaultModel,[\s\S]{0,80}\} from "\.\/default-model"/);
+ // Provider readiness is one rule for the picker and the add guard.
+ assert.match(pageSource, /const providerReady = \(provider: ProviderPublic\) =>\n\s+providerServesChatModels\(provider, imageGenerationCandidates\)/);
+ assert.doesNotMatch(pageSource, /provider\.hasOauth \|\|/);
});
test("a saved image selection never takes the app's image default", () => {
diff --git a/apps/desktop/test/settings-general.test.mjs b/apps/desktop/test/settings-general.test.mjs
index 5aec0407d..fdb0ca687 100644
--- a/apps/desktop/test/settings-general.test.mjs
+++ b/apps/desktop/test/settings-general.test.mjs
@@ -18,6 +18,10 @@ const providersSource = await readFile(
new URL("../src/components/settings/ModelConfigPage.tsx", import.meta.url),
"utf8",
);
+const defaultModelSource = await readFile(
+ new URL("../src/components/settings/default-model.ts", import.meta.url),
+ "utf8",
+);
const scheduledSource = await readFile(
new URL("../src/pages/ScheduledPage.tsx", import.meta.url),
"utf8",
@@ -263,9 +267,13 @@ test("default model selector shows every configured model under its provider", (
test("model configuration separates AI services from independently removable vendor accounts", () => {
assert.match(providersSource, /authKind !== OAUTH_AUTH_KIND/);
+ // Readiness (a key, an OAuth account, or a no-auth provider) now lives in the
+ // shared helper, so the page must delegate to it instead of re-inlining the
+ // rule next to a second copy that can drift from the picker.
+ assert.match(providersSource, /providerServesChatModels\(/);
assert.match(
- providersSource,
- /provider\.hasSecret \|\| provider\.hasOauth \|\| provider\.authKind === "none"/,
+ defaultModelSource,
+ /provider\.hasSecret \|\| !!provider\.hasOauth \|\| provider\.authKind === "none"/,
);
assert.doesNotMatch(providersSource, /provider-config-hero/);
assert.doesNotMatch(providersSource, /settings-section-subtitle/);