Skip to content

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

feat(models): support multiple image generation models

vastsa68b4411e827b
diff --git a/apps/desktop/electron/main/runtime/session-launch.ts b/apps/desktop/electron/main/runtime/session-launch.ts
index 0e4a32609..c6dd83c0a 100644
--- a/apps/desktop/electron/main/runtime/session-launch.ts
+++ b/apps/desktop/electron/main/runtime/session-launch.ts
@@ -3,6 +3,7 @@ import {
ErrorCodes as SharedErrorCodes,
isActiveInProject,
isCommandShellCatalog,
+ imageGenerationBindings,
isImageGenerationModel,
normalizeMode,
resolveBindingContextWindow,
@@ -327,7 +328,11 @@ export function createSessionLaunchRuntime({
errorCode: ErrorCodes.MODEL_NOT_CONFIGURED,
});
}
- if (isImageGenerationModel(settings.imageGeneration, provider.id, modelId)) {
+ if (isImageGenerationModel(
+ imageGenerationBindings(settings.imageGenerationModels, settings.imageGeneration),
+ provider.id,
+ modelId,
+ )) {
throw Object.assign(new Error("The image model cannot be used for conversation; select a chat model"), {
errorCode: ErrorCodes.MODEL_NOT_CONFIGURED,
});
diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsx
index 58631f85c..c09ed9898 100644
--- a/apps/desktop/src/components/Composer.tsx
+++ b/apps/desktop/src/components/Composer.tsx
@@ -12,6 +12,7 @@ import type {
} from "@pi-desktop/shared";
import {
initialThinkingLevelForBinding,
+ imageGenerationBindings,
isImageGenerationModel,
modelIdsMatch,
normalizeLargePasteThreshold,
@@ -92,6 +93,10 @@ export function Composer({
s.activeSessionId ? s.planningStates[s.activeSessionId] : undefined,
);
const settings = useAppStore((s) => s.settings);
+ const imageGenerationCandidates = useMemo(
+ () => imageGenerationBindings(settings?.imageGenerationModels, settings?.imageGeneration),
+ [settings?.imageGenerationModels, settings?.imageGeneration],
+ );
const sessions = useAppStore((s) => s.sessions);
const activeSessionId = useAppStore((s) => s.activeSessionId);
const activeSessionSummary = sessions.find(
@@ -371,7 +376,7 @@ export function Composer({
);
const thinkingLabel = thinkingLevel;
const selectedModel = provider?.id
- ? composerModelsForProvider(provider, providerModels[provider.id]).find(
+ ? composerModelsForProvider(provider, providerModels[provider.id], imageGenerationCandidates).find(
(model) => modelIdsMatch(model.modelId, modelId ?? ""),
)
: undefined;
@@ -392,7 +397,7 @@ export function Composer({
: !!provider &&
provider.enabled &&
!!modelId &&
- !isImageGenerationModel(settings?.imageGeneration, provider.id, modelId) &&
+ !isImageGenerationModel(imageGenerationCandidates, provider.id, modelId) &&
(provider.hasSecret || provider.authKind === "none");
const enterToSend = settings?.enterToSend ?? true;
const hasDraftContent = Boolean(value.trim() || activeFileReferences.length);
diff --git a/apps/desktop/src/components/settings/ImageGenerationModelRow.tsx b/apps/desktop/src/components/settings/ImageGenerationModelRow.tsx
index 0f829985f..8104993f3 100644
--- a/apps/desktop/src/components/settings/ImageGenerationModelRow.tsx
+++ b/apps/desktop/src/components/settings/ImageGenerationModelRow.tsx
@@ -1,23 +1,61 @@
import { useTranslation } from "react-i18next";
-import type { AppSettings, ProviderPublic } from "@pi-desktop/shared";
+import {
+ imageGenerationBindings,
+ modelIdsMatch,
+ type AppSettings,
+ type ImageGenerationBinding,
+ type ProviderPublic,
+} from "@pi-desktop/shared";
+import { SettingsMenuSelect } from "./SettingsMenuSelect";
-export function ImageGenerationModelRow({ settings, providers }: {
+function imageModelOptionId(binding: ImageGenerationBinding): string {
+ return `${binding.providerId}\u0000${binding.modelId}`;
+}
+
+export function ImageGenerationModelRow({
+ settings,
+ providers,
+ busy = false,
+ onChange,
+}: {
settings: AppSettings;
providers: ProviderPublic[];
+ busy?: boolean;
+ onChange?: (binding: ImageGenerationBinding) => void;
}) {
const { t } = useTranslation();
const binding = settings.imageGeneration;
- const provider = providers.find((entry) => entry.id === binding?.providerId);
- const valid = provider?.enabled && provider.authKind !== "oauth" &&
+ const candidates = imageGenerationBindings(settings.imageGenerationModels, binding);
+ if (!binding || candidates.length === 0) return null;
+
+ const activeCandidate = candidates.find((candidate) =>
+ candidate.providerId === binding.providerId &&
+ 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);
+ provider.models.some((model) => model.id === 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);
+ return {
+ id: imageModelOptionId(candidate),
+ label: `${candidateProvider?.name ?? candidate.providerId} · ${candidate.modelId}`,
+ disabled: !available,
+ };
+ });
return (
<div className="settings-row model-default-row model-image-row">
<div className="settings-row-copy model-default-copy">
<div className="settings-row-title model-default-label">{t("settings.imageModel")}</div>
<div className="settings-row-detail model-default-value">
- {valid && binding ? (
+ {valid && provider ? (
<>
<span className="model-default-provider">{provider.name}</span>
<span className="model-default-sep" aria-hidden>·</span>
@@ -28,6 +66,19 @@ export function ImageGenerationModelRow({ settings, providers }: {
)}
</div>
</div>
+ {onChange && candidates.length > 1 ? (
+ <SettingsMenuSelect
+ className="model-image-selector"
+ label={t("settings.imageModel")}
+ value={activeCandidate ? imageModelOptionId(activeCandidate) : ""}
+ options={options}
+ busy={busy}
+ onChange={(id) => {
+ const next = candidates.find((candidate) => imageModelOptionId(candidate) === id);
+ if (next) onChange(next);
+ }}
+ />
+ ) : null}
</div>
);
}
diff --git a/apps/desktop/src/components/settings/ModelConfigPage.tsx b/apps/desktop/src/components/settings/ModelConfigPage.tsx
index 074af7699..66d8eac93 100644
--- a/apps/desktop/src/components/settings/ModelConfigPage.tsx
+++ b/apps/desktop/src/components/settings/ModelConfigPage.tsx
@@ -10,8 +10,10 @@ import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import {
OAUTH_AUTH_KIND,
+ imageGenerationBindings,
isImageGenerationModel,
modelIdsMatch,
+ type ImageGenerationBinding,
type ModelBinding,
type ProviderPublic,
} from "@pi-desktop/shared";
@@ -78,6 +80,7 @@ export function ModelConfigPage() {
const [defaultModelQuery, setDefaultModelQuery] = useState("");
const [busyId, setBusyId] = useState<string | null>(null);
const [testingId, setTestingId] = useState<string | null>(null);
+ const [changingImageModel, setChangingImageModel] = useState(false);
const [refreshingCatalog, setRefreshingCatalog] = useState(false);
const [catalogStatus, setCatalogStatus] = useState<CatalogStatus | null>(null);
// Two-step delete: the first click arms the row, the second removes it.
@@ -109,9 +112,13 @@ export function ModelConfigPage() {
})();
}, []);
+ const imageGenerationCandidates = useMemo(
+ () => imageGenerationBindings(settings?.imageGenerationModels, settings?.imageGeneration),
+ [settings?.imageGenerationModels, settings?.imageGeneration],
+ );
const providerReady = (provider: ProviderPublic) =>
provider.enabled &&
- defaultModelOptions([provider], settings?.imageGeneration).length > 0 &&
+ defaultModelOptions([provider], imageGenerationCandidates).length > 0 &&
(provider.hasSecret || provider.hasOauth || provider.authKind === "none");
const aiProviders = useMemo(
@@ -120,7 +127,7 @@ export function ModelConfigPage() {
);
const reorder = useProviderReorder(aiProviders, busyId !== null || testingId !== null || setupFor !== null);
const readyProviders = providers.filter(providerReady);
- const defaultModelOptionsList = defaultModelOptions(readyProviders, settings?.imageGeneration);
+ const defaultModelOptionsList = defaultModelOptions(readyProviders, imageGenerationCandidates);
const visibleDefaultModelOptions = useMemo(() => {
const query = defaultModelQuery.trim().toLowerCase();
if (!query) return defaultModelOptionsList;
@@ -137,12 +144,19 @@ export function ModelConfigPage() {
const editingProvider =
setupFor ? providers.find((provider) => provider.id === setupFor) ?? null : null;
const defaultProviderReady = defaultProvider !== null && providerReady(defaultProvider) &&
- !isImageGenerationModel(settings.imageGeneration, defaultProvider.id,
+ !isImageGenerationModel(imageGenerationCandidates, defaultProvider.id,
displayedDefaultModelId(defaultProvider, settings.defaultModelId));
const setDefaultModel = async (provider: ProviderPublic, modelId: string) => {
- if (isImageGenerationModel(useAppStore.getState().settings?.imageGeneration, provider.id, modelId)) return;
+ if (isImageGenerationModel(
+ imageGenerationBindings(
+ useAppStore.getState().settings?.imageGenerationModels,
+ useAppStore.getState().settings?.imageGeneration,
+ ),
+ provider.id,
+ modelId,
+ )) return;
setBusyId(provider.id);
try {
await api.setSettings({
@@ -165,13 +179,42 @@ export function ModelConfigPage() {
/**
* Preserve the selected app default unless it was removed from the provider.
*/
- const afterSaved = async (saved: ProviderPublic, models: ModelBinding[], imageModelId?: string) => {
+ const afterSaved = async (
+ saved: ProviderPublic,
+ models: ModelBinding[],
+ imageModelIds?: string[],
+ ) => {
const firstModelId = models[0]?.id;
try {
- if (imageModelId) {
- await api.setSettings({ ...(await api.getSettings()), imageGeneration: { providerId: saved.id, modelId: imageModelId } });
- useAppStore.setState({ settings: await api.getSettings() });
- showToast(t("settings.providerSaved"), { variant: "success" });
+ if (imageModelIds !== undefined) {
+ const current = await api.getSettings();
+ const existing = imageGenerationBindings(
+ current.imageGenerationModels,
+ current.imageGeneration,
+ );
+ 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,
+ };
+ 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) {
@@ -200,6 +243,28 @@ export function ModelConfigPage() {
}
};
+ const setImageGenerationDefault = async (binding: ImageGenerationBinding) => {
+ setChangingImageModel(true);
+ try {
+ const current = await api.getSettings();
+ const candidates = imageGenerationBindings(
+ current.imageGenerationModels,
+ current.imageGeneration,
+ );
+ if (!isImageGenerationModel(candidates, binding.providerId, binding.modelId)) return;
+ const nextSettings = { ...current, imageGeneration: binding };
+ await api.setSettings(nextSettings);
+ useAppStore.setState({ settings: nextSettings });
+ showToast(t("settings.imageModelSelected"), { variant: "success" });
+ } catch (error) {
+ showToast(error instanceof Error ? error.message : String(error), {
+ variant: "error",
+ });
+ } finally {
+ setChangingImageModel(false);
+ }
+ };
+
const toggleEnabled = async (provider: ProviderPublic) => {
setBusyId(provider.id);
try {
@@ -426,7 +491,14 @@ export function ModelConfigPage() {
</div>
</AnchoredMenu>
</div>
- <ImageGenerationModelRow settings={settings} providers={providers} />
+ {imageGenerationCandidates.length > 0 ? (
+ <ImageGenerationModelRow
+ settings={settings}
+ providers={providers}
+ busy={changingImageModel}
+ onChange={setImageGenerationDefault}
+ />
+ ) : null}
</div>
</section>
@@ -528,7 +600,7 @@ export function ModelConfigPage() {
variant="ghost"
disabled={rowBusy || !providerReady(provider)}
onClick={() =>
- void setDefaultModel(provider, defaultModelOptions([provider], settings.imageGeneration)[0]?.modelId ?? "")
+ void setDefaultModel(provider, defaultModelOptions([provider], imageGenerationCandidates)[0]?.modelId ?? "")
}
>
{t("settings.makeDefault")}
@@ -731,7 +803,11 @@ export function ModelConfigPage() {
provider={editingProvider}
initialDraft={copyDraft}
onClose={() => { setSetupFor(null); setCopyDraft(null); }}
- imageModelId={settings.imageGeneration?.providerId === editingProvider?.id ? settings.imageGeneration?.modelId : undefined}
+ imageModelIds={editingProvider
+ ? imageGenerationCandidates
+ .filter((binding) => binding.providerId === editingProvider.id)
+ .map((binding) => binding.modelId)
+ : undefined}
onSaved={afterSaved}
/>
) : null}
diff --git a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx b/apps/desktop/src/components/settings/ModelSelectionPanes.tsx
index 33cf11ed4..df86b07ac 100644
--- a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx
+++ b/apps/desktop/src/components/settings/ModelSelectionPanes.tsx
@@ -16,6 +16,7 @@ import {
bindingForCustomModel,
bindingFromModelInfo,
formatTokenCount,
+ modelIdsMatch,
modelMatchesFilter,
nativeWebSearchSupportedOn,
publishedThinkingLevels,
@@ -179,8 +180,8 @@ export function applyVisibleModelSelection(
}
export type ModelSelectionPanesProps = {
- imageModelId?: string;
- onImageModelChange?: (id: string) => void;
+ imageModelIds?: string[];
+ onImageModelChange?: (id: string, selected: boolean) => void;
discovery: ProviderModelsState & { canReload?: boolean };
selection: ModelSelection;
/** Heading of the discovered list: a service's models, or an account's. */
@@ -209,7 +210,7 @@ export function ModelSelectionPanes({
busy = false,
onReload,
apiStyle,
- imageModelId,
+ imageModelIds,
onImageModelChange,
}: ModelSelectionPanesProps) {
const { t } = useTranslation();
@@ -535,6 +536,9 @@ export function ModelSelectionPanes({
publishedContextWindow !== undefined;
const publishedDocuments = info ? modelMatchesFilter(info, "pdf") : false;
const expanded = expandedModelId === binding.id;
+ const imageModelSelected = imageModelIds?.some((modelId) =>
+ modelIdsMatch(modelId, binding.id),
+ ) ?? false;
const advancedId = `model-advanced-${binding.id}`;
return (
<li
@@ -602,7 +606,6 @@ export function ModelSelectionPanes({
id={advancedId}
hidden={!expanded}
>
- {onImageModelChange ? <button type="button" className="provider-chosen-advanced-toggle" disabled={busy || imageModelId === binding.id} onClick={() => onImageModelChange(binding.id)}>{t(imageModelId === binding.id ? "settings.imageModelSelected" : "settings.setImageModel")}</button> : null}
<label className="provider-chosen-field">
<span className="provider-chosen-field-label">
{t("settings.modelAlias")}
@@ -829,6 +832,30 @@ export function ModelSelectionPanes({
updateBinding(binding.id, { supportsDocuments: next })
}
/>
+ {onImageModelChange ? (
+ <label className="provider-chosen-capability">
+ <input
+ type="checkbox"
+ checked={imageModelSelected}
+ disabled={busy}
+ aria-label={t(
+ imageModelSelected
+ ? "settings.imageModelSelected"
+ : "settings.setImageModel",
+ )}
+ onChange={(event) =>
+ onImageModelChange(binding.id, event.target.checked)
+ }
+ />
+ <span>
+ {t(
+ imageModelSelected
+ ? "settings.imageModelSelected"
+ : "settings.setImageModel",
+ )}
+ </span>
+ </label>
+ ) : null}
<span className="provider-chosen-delegation">
<label className="provider-chosen-capability">
<input
diff --git a/apps/desktop/src/components/settings/ProviderSetupDialog.tsx b/apps/desktop/src/components/settings/ProviderSetupDialog.tsx
index dc1611a5d..e7a1b85a0 100644
--- a/apps/desktop/src/components/settings/ProviderSetupDialog.tsx
+++ b/apps/desktop/src/components/settings/ProviderSetupDialog.tsx
@@ -120,8 +120,8 @@ export type ProviderSetupDialogProps = {
provider?: ProviderPublic | null;
initialDraft?: ProviderCopyDraft | null;
onClose: () => void;
- imageModelId?: string;
- onSaved: (provider: ProviderPublic, models: ModelBinding[], imageModelId?: string) => void | Promise<void>;
+ imageModelIds?: string[];
+ onSaved: (provider: ProviderPublic, models: ModelBinding[], imageModelIds?: string[]) => void | Promise<void>;
};
export function ProviderSetupDialog({
@@ -129,10 +129,10 @@ export function ProviderSetupDialog({
initialDraft,
onClose,
onSaved,
- imageModelId,
+ imageModelIds,
}: ProviderSetupDialogProps) {
const { t } = useTranslation();
- const [imageModelDraft, setImageModelDraft] = useState<string | undefined>();
+ const [imageModelDraft, setImageModelDraft] = useState<string[] | undefined>();
const editing = !!provider;
const apiKeyRef = useRef<HTMLInputElement>(null);
const [service, setService] = useState(() => initialDraft
@@ -272,6 +272,9 @@ export function ProviderSetupDialog({
return;
}
const persisted = selection.bindingsToPersist;
+ const imageModelIdsToSave = imageModelDraft?.filter((imageModelId) =>
+ persisted.some((model) => model.id === imageModelId),
+ );
setSaving(true);
setError("");
try {
@@ -287,7 +290,7 @@ export function ProviderSetupDialog({
headers,
...(apiKey ? { secretValue: apiKey } : {}),
});
- await onSaved(result.provider ?? provider, persisted, persisted.some((model) => model.id === imageModelDraft) ? imageModelDraft : undefined);
+ await onSaved(result.provider ?? provider, persisted, imageModelIdsToSave);
} else {
const result = await api.createProvider({
name: providerName,
@@ -302,7 +305,7 @@ export function ProviderSetupDialog({
apiStyle: resolvedApiStyle,
headers,
});
- await onSaved(result.provider, persisted, persisted.some((model) => model.id === imageModelDraft) ? imageModelDraft : undefined);
+ await onSaved(result.provider, persisted, imageModelIdsToSave);
}
} catch (cause) {
setError(cause instanceof Error ? cause.message : String(cause));
@@ -311,6 +314,14 @@ export function ProviderSetupDialog({
}
};
+ const updateImageModelDraft = (id: string, selected: boolean) => {
+ setImageModelDraft((current) => {
+ const next = current ?? imageModelIds ?? [];
+ if (selected) return next.includes(id) ? next : [...next, id];
+ return next.filter((entry) => entry !== id);
+ });
+ };
+
const canSave =
!saving &&
!requiresApiStyleChoice &&
@@ -532,8 +543,8 @@ export function ProviderSetupDialog({
busy={saving}
onReload={discovery.reload}
apiStyle={resolvedApiStyle}
- imageModelId={imageModelDraft ?? imageModelId}
- onImageModelChange={setImageModelDraft}
+ imageModelIds={imageModelDraft ?? imageModelIds}
+ onImageModelChange={updateImageModelDraft}
/>
</div>
</div>
diff --git a/apps/desktop/src/components/settings/default-model.ts b/apps/desktop/src/components/settings/default-model.ts
index dc69df8f7..b59f30b7b 100644
--- a/apps/desktop/src/components/settings/default-model.ts
+++ b/apps/desktop/src/components/settings/default-model.ts
@@ -7,7 +7,7 @@
* is not configured, so these helpers keep the two notions apart: what a
* provider itself offers, and what is safe to display for it.
*/
-import { isImageGenerationModel, modelIdsMatch, type ImageGenerationBinding, type ProviderPublic } from "@pi-desktop/shared";
+import { isImageGenerationModel, modelIdsMatch, type ImageGenerationBindings, type ProviderPublic } from "@pi-desktop/shared";
export type DefaultModelOption = {
provider: ProviderPublic;
@@ -17,7 +17,7 @@ export type DefaultModelOption = {
/** Expand runnable providers into the model choices they actually configure. */
export function defaultModelOptions(
providers: readonly ProviderPublic[],
- imageGeneration?: ImageGenerationBinding | null,
+ imageGeneration?: ImageGenerationBindings | null,
): DefaultModelOption[] {
return providers.flatMap((provider) => {
const modelIds = (provider.models ?? [])
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu.ts
index 61d62fc2a..a9b07cd72 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu.ts
@@ -6,6 +6,7 @@ import type {
} from "@pi-desktop/shared";
import {
initialThinkingLevelForBinding,
+ imageGenerationBindings,
isImageGenerationModel,
modelIdsMatch,
} from "@pi-desktop/shared";
@@ -46,6 +47,11 @@ export function useComposerModelMenu({
}: UseComposerModelMenuOptions) {
const providers = useAppStore((s) => s.providers);
const imageGeneration = useAppStore((s) => s.settings?.imageGeneration);
+ const imageGenerationModels = useAppStore((s) => s.settings?.imageGenerationModels);
+ const imageGenerationCandidates = useMemo(
+ () => imageGenerationBindings(imageGenerationModels, imageGeneration),
+ [imageGenerationModels, imageGeneration],
+ );
const providerModels = useAppStore((s) => s.providerModels);
const loadProviderModels = useAppStore((s) => s.loadProviderModels);
const configureActiveSession = useAppStore((s) => s.configureActiveSession);
@@ -117,7 +123,7 @@ export function useComposerModelMenu({
const models = composerModelsForProvider(
candidate,
providerModels[candidate.id],
- imageGeneration,
+ imageGenerationCandidates,
);
return {
provider: candidate,
@@ -127,7 +133,7 @@ export function useComposerModelMenu({
};
})
.filter((group) => group.models.length > 0),
- [providers, providerModels, imageGeneration],
+ [providers, providerModels, imageGenerationCandidates],
);
const queryNeedle = query.trim().toLowerCase();
const filteredModelGroups = useMemo(
@@ -250,7 +256,14 @@ export function useComposerModelMenu({
const selectModel = async (candidate: ProviderPublic, nextModelId: string) => {
thinkingQueueRef.current?.invalidate();
await thinkingQueueRef.current?.idle();
- if (isImageGenerationModel(useAppStore.getState().settings?.imageGeneration, candidate.id, nextModelId)) return;
+ if (isImageGenerationModel(
+ imageGenerationBindings(
+ useAppStore.getState().settings?.imageGenerationModels,
+ useAppStore.getState().settings?.imageGeneration,
+ ),
+ candidate.id,
+ nextModelId,
+ )) return;
try {
const nextModelProvider = thinkingProviderForModel(
candidate,
diff --git a/apps/desktop/src/lib/composer-models.ts b/apps/desktop/src/lib/composer-models.ts
index 2707859f0..448cec029 100644
--- a/apps/desktop/src/lib/composer-models.ts
+++ b/apps/desktop/src/lib/composer-models.ts
@@ -1,7 +1,7 @@
import {
bindingSupportsImages,
isImageGenerationModel,
- type ImageGenerationBinding,
+ type ImageGenerationBindings,
modelIdsMatch,
modelMatchesFilter,
type ModelBinding,
@@ -53,7 +53,7 @@ function configuredModelIds(provider: ConfiguredProvider): string[] {
export function composerModelsForProvider(
provider: ConfiguredProvider,
discovered: readonly ModelInfo[] | undefined,
- imageGeneration?: ImageGenerationBinding | null,
+ imageGeneration?: ImageGenerationBindings | null,
): ModelInfo[] {
return configuredModelIds(provider).filter((modelId) =>
!isImageGenerationModel(imageGeneration, provider.id, modelId),
diff --git a/apps/desktop/test/model-advanced-capabilities.test.mjs b/apps/desktop/test/model-advanced-capabilities.test.mjs
index c8349943d..c41c39378 100644
--- a/apps/desktop/test/model-advanced-capabilities.test.mjs
+++ b/apps/desktop/test/model-advanced-capabilities.test.mjs
@@ -12,6 +12,10 @@ const pickerSource = await readFile(
new URL("../src/components/settings/ModelSelectionPanes.tsx", import.meta.url),
"utf8",
);
+const imageModelRowSource = await readFile(
+ new URL("../src/components/settings/ImageGenerationModelRow.tsx", import.meta.url),
+ "utf8",
+);
const composerSource = await readComposerSource();
const capabilitiesSource = await readFile(
new URL(
@@ -74,6 +78,22 @@ test("the capability row carries no explanatory copy or extra controls", () => {
assert.doesNotMatch(styles, /provider-chosen-capability-(reset|state|hint)/);
});
+
+test("image generation selection is an attachment capability and hides when unset", () => {
+ assert.match(
+ pickerSource,
+ /className="provider-chosen-capability-rows">[\s\S]*?settings\.setImageModel/,
+ );
+ assert.doesNotMatch(
+ pickerSource,
+ /className="provider-chosen-advanced-toggle"[^\n]*settings\.setImageModel/,
+ );
+ assert.match(pickerSource, /imageModelIds\?\.some\([\s\S]*?modelIdsMatch/);
+ assert.match(pickerSource, /onImageModelChange\(binding\.id, event\.target\.checked\)/);
+ assert.match(imageModelRowSource, /imageGenerationBindings\(settings\.imageGenerationModels, binding\)/);
+ assert.match(imageModelRowSource, /if \(!binding \|\| candidates\.length === 0\) return null;/);
+});
+
test("the Composer model rows use the provider binding for vision badges", () => {
assert.match(composerSource, /composerModelBadges\(model, group\.provider\)/);
});
diff --git a/apps/desktop/test/native-pi-sessions.test.mjs b/apps/desktop/test/native-pi-sessions.test.mjs
index ec355f1cd..25a92c0df 100644
--- a/apps/desktop/test/native-pi-sessions.test.mjs
+++ b/apps/desktop/test/native-pi-sessions.test.mjs
@@ -46,7 +46,7 @@ test("native compact and session-addressed queue endpoints reject before host or
// Real slices/IPC with synthetic state; no Electron process or native home.
const { register } = await import("node:module");
register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
-const { IPC, isImageGenerationModel } = await import("@pi-desktop/shared");
+const { IPC, isImageGenerationModel, imageGenerationBindings } = await import("@pi-desktop/shared");
const { registerAgentIpc } = await import("../electron/main/ipc/agent-ipc.ts");
const { searchSessionsAcrossSources } = await import("../electron/main/services/session-search.ts");
const { createEventsSlice } = await import("../src/stores/slices/events-slice.ts");
@@ -157,9 +157,9 @@ test("native prompt only dispatches sidecar and cannot create a host queue entry
test("native model readiness never depends on a Desktop provider but read-only fails closed", () => {
const expression = composer.match(/const modelReady = ([\s\S]*?);/)[1];
- const evaluateReady = new Function("isImageGenerationModel", "settings", "nativeSession", "activeSessionSummary", "provider", "modelId", `return ${expression}`);
+ const evaluateReady = new Function("isImageGenerationModel", "imageGenerationCandidates", "settings", "nativeSession", "activeSessionSummary", "provider", "modelId", `return ${expression}`);
const ready = (nativeSession, activeSessionSummary, provider, modelId, settings) =>
- evaluateReady(isImageGenerationModel, settings, nativeSession, activeSessionSummary, provider, modelId);
+ evaluateReady(isImageGenerationModel, imageGenerationBindings(settings?.imageGenerationModels, settings?.imageGeneration), settings, nativeSession, activeSessionSummary, provider, modelId);
assert.equal(ready(true, { capabilities: { canPrompt: true } }, undefined, undefined), true);
assert.equal(ready(true, { capabilities: { canPrompt: false } }, { enabled: true, hasSecret: true }, "model"), false);
assert.equal(ready(true, {}, undefined, undefined), false);
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index a58381c16..02bbf7b9b 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -702,6 +702,37 @@ fn validate_settings_value(value: &Value) -> Result<(), JsonRpcError> {
}
}
}
+ if let Some(candidates) = object.get("imageGenerationModels").filter(|v| !v.is_null()) {
+ let Some(candidates) = candidates.as_array() else {
+ return Err(rpc_err(
+ 1002,
+ "imageGenerationModels must be an array",
+ "INVALID_PARAMS",
+ ));
+ };
+ if candidates.len() > 128 {
+ return Err(rpc_err(
+ 1002,
+ "imageGenerationModels contains too many models",
+ "INVALID_PARAMS",
+ ));
+ }
+ for binding in candidates {
+ for (key, max) in [("providerId", 128), ("modelId", 256)] {
+ if !binding
+ .get(key)
+ .and_then(Value::as_str)
+ .is_some_and(|s| !s.trim().is_empty() && s.len() <= max)
+ {
+ return Err(rpc_err(
+ 1002,
+ "invalid image generation candidate",
+ "INVALID_PARAMS",
+ ));
+ }
+ }
+ }
+ }
if let Some(template_value) = object.get("promptEnhancementUserTemplate") {
if let Some(message) =
prompt_enhancement_template_error("promptEnhancementUserTemplate", template_value)
@@ -8634,6 +8665,12 @@ mod image_generation_settings_tests {
json!({}),
json!({"imageGeneration": null}),
json!({"imageGeneration": {"providerId": "p", "modelId": "image"}}),
+ json!({"imageGenerationModels": null}),
+ json!({"imageGenerationModels": []}),
+ json!({"imageGenerationModels": [
+ {"providerId": "p", "modelId": "image-one"},
+ {"providerId": "q", "modelId": "image-two"}
+ ]}),
] {
assert!(validate_settings_value(&value).is_ok());
}
@@ -8644,5 +8681,12 @@ mod image_generation_settings_tests {
] {
assert!(validate_settings_value(&json!({"imageGeneration": value})).is_err());
}
+ for value in [
+ json!(false),
+ json!({}),
+ json!([{"providerId": "p", "modelId": " "}]),
+ ] {
+ assert!(validate_settings_value(&json!({"imageGenerationModels": value})).is_err());
+ }
}
}
diff --git a/docs/spec/03-runtime/21-image-generation.md b/docs/spec/03-runtime/21-image-generation.md
index 09896f474..cea75dcb0 100644
--- a/docs/spec/03-runtime/21-image-generation.md
+++ b/docs/spec/03-runtime/21-image-generation.md
@@ -1,26 +1,11 @@
# Image generation and editing
-The desktop exposes one optional `AppSettings.imageGeneration` binding with
-`providerId` and `modelId`. `null` clears it; absent means unconfigured. Host-core
-validates and persists it through the existing settings store. No schema bump
-is needed. The binding is independent of the conversation default and references
-an existing enabled API-key or no-auth provider and one of its configured models.
+The desktop exposes `AppSettings.imageGeneration` as the current default image-generation binding and `AppSettings.imageGenerationModels` as the optional list of models marked for image generation. The legacy single binding remains supported: when the list is absent, it is treated as the only candidate. A null or empty current binding means no default; host-core validates and persists both fields through the existing settings store. No schema bump is needed. Each candidate is independent of the conversation default and references an existing enabled API-key or no-auth provider and one of its configured models.
## Configuration
-Model Advanced offers **Set as image model**. A draft selection only takes effect
-when the provider form saves; Cancel leaves settings unchanged. Saving a provider
-as an image model does not replace the default conversation model. Below the
-default model row in the same defaults panel, **Image generation model** is a
-read-only summary with the same provider/model typography and a 12px row gap.
-It has no Change or Clear actions; replacement uses the provider's Advanced
-settings. Missing, disabled, credential-less or removed bindings display only
-**Currently unavailable**. OAuth accounts are not eligible; there is no fallback.
-The selected provider/model pair is excluded from the default conversation picker,
-provider quick-default action, and Composer model menu. Other providers with the
-same model ID remain independent. Existing conversation bindings and history are
-preserved; a conversation still pinned to the image binding must select a chat
-model before sending. Runtime launch also rejects that binding before inference.
+Model Advanced exposes **Set as image model** alongside the image and document attachment capabilities in the model capability group, not as a separate control row. The checkbox is multi-select: saving a provider persists every checked model in `imageGenerationModels`; Cancel leaves settings unchanged. Saving candidates does not replace the default conversation model. Below the default model row in the same defaults panel, **Image generation model** shows the current default and offers a menu to choose one from all marked candidates. When no candidate is configured, the summary row is hidden. An existing candidate that is missing, disabled, credential-less or removed displays only **Currently unavailable**. OAuth accounts are not eligible; there is no fallback.
+All marked provider/model pairs are excluded from the default conversation picker, provider quick-default action, and Composer model menu. Other providers with the same model ID remain independent. Existing conversation bindings and history are preserved; a conversation still pinned to any image candidate must select a chat model before sending. Runtime launch rejects every marked image model before inference.
## Agent contract
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 7359c94bd..b46be35f7 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -12,21 +12,26 @@
- **Preconditions:** Isolated desktop profile and workspace, built image feature,
local chat and OpenAI Images HTTP fixtures; no live provider credentials.
-- **Steps:** Open Models settings; verify the conversation and image defaults
- share a compact panel. Submit a two-image request through the composer, then
- edit the first output through a follow-up message. Collapse tool details.
- Clear the binding and follow the visible configuration action back to Models.
-- **Expected:** A 12px default-row gap, decoded image previews outside collapsed
- process details, multipart source upload for editing, preserved originals,
- and no image HTTP request while unconfigured.
-- **Settings interactions:** The image summary has no Change/Clear buttons and
- matches the default model's provider/model text styles. Select another
- provider's image model in Advanced and save; the summary changes while the
- chat default stays unchanged. Missing/disabled bindings show only Currently
- unavailable. Covered in `scripts/e2e-image-generation-ui.mjs`.
-- **Conversation selection:** The selected image provider/model is absent from
+- **Steps:** Open Models settings with no image model configured; verify the image
+ summary row is absent. Open a provider's Advanced model settings and verify
+ **Set as image model** is grouped with the image/document attachment
+ capabilities and can be checked for multiple models. Save, use the image
+ summary menu to choose one marked model as the default, then submit a
+ two-image request through the composer and edit the first output through a
+ follow-up message. Collapse tool details.
+- **Expected:** After saving, the image summary appears with a 12px default-row
+ gap and lists all marked candidates, the selected default is changeable
+ without changing the chat default, decoded image previews stay outside
+ collapsed process details, multipart source upload is used for editing,
+ originals are preserved, and no image HTTP request occurs while unconfigured.
+- **Settings interactions:** The unconfigured state renders no image summary.
+ Mark candidates in the attachment capability group, save, and select one
+ from the summary menu. An existing missing/disabled candidate shows only
+ Currently unavailable. Covered in `scripts/e2e-image-generation-ui.mjs`.
+- **Conversation selection:** Every marked image provider/model is absent from
default and Composer candidates. Other providers retain same-ID models. An
- existing session pinned to the image binding is rejected before inference.
+ existing session pinned to any marked image binding is rejected before
+ inference.
- **Transport contracts:** Real stdio reverse RPC retains a thrown local image
error's stable code in the production ParentHostProxy. Local HTTP tests check
single/multiple binary multipart fields and boundaries, DALL-E `b64_json`
diff --git a/docs/zh-CN/spec/03-runtime/21-image-generation.md b/docs/zh-CN/spec/03-runtime/21-image-generation.md
index 791c021c3..eb740a64e 100644
--- a/docs/zh-CN/spec/03-runtime/21-image-generation.md
+++ b/docs/zh-CN/spec/03-runtime/21-image-generation.md
@@ -2,13 +2,12 @@
> **翻译说明:** 本页对应 [英文源规格](/spec/03-runtime/21-image-generation)。代码、协议字段和标识符保持原文;如有歧义,以英文版本为准。
-桌面通过可选的 `AppSettings.imageGeneration` 绑定唯一生图模型,包含 `providerId` 和 `modelId`。`null` 清除绑定,缺省表示未配置。host-core 使用现有设置存储校验并持久化,无需数据库版本升级。绑定独立于默认对话模型,引用已启用的 API-key 或免认证服务商及其已配置模型。
+桌面通过 `AppSettings.imageGeneration` 保存当前默认生图绑定,并通过可选的 `AppSettings.imageGenerationModels` 保存已标记的生图模型列表。缺省候选列表时兼容旧数据,把单绑定视为唯一候选;`providerId` 和 `modelId` 仍是每个绑定的字段。host-core 使用现有设置存储校验并持久化,无需数据库版本升级。每个候选独立于默认对话模型,引用已启用的 API-key 或免认证服务商及其已配置模型。
## 配置
-模型高级设置提供“设为生图模型”。只有保存服务商表单后选择才生效,取消不改变设置;保存不会替换默认对话模型。默认模型下方同一面板中的生图模型行只展示摘要,服务商和模型字号与默认模型一致,两行间距为 12px。摘要不提供更改或清除操作;替换通过服务商高级设置完成。绑定缺失、服务商停用、缺少凭据或模型移除时仅显示“暂不可用”。OAuth 账户不适用,也不会自动回退。
-
-所选服务商与模型组合从默认对话模型选择器、服务商快速设为默认操作和 Composer 模型菜单中排除。其他服务商的同名模型独立保留。已有会话绑定和历史不改写;仍绑定生图模型的会话必须选择对话模型才能发送,运行时也会在推理前拒绝该绑定。
+模型高级设置将“设为生图模型”与图片、文档附件能力放在同一能力组中,不再单独占一行;复选框支持多选,保存服务商表单后把所有勾选模型写入 `imageGenerationModels`,取消不会改变设置。保存候选不会替换默认对话模型。默认模型下方同一面板中的“生图模型”显示当前默认,并提供菜单从所有已标记候选中选择一个。没有候选时隐藏摘要行;已存在但服务商停用、缺少凭据或模型移除的候选仅显示“暂不可用”。OAuth 账户不适用,也不会自动回退。
+所有已标记的服务商/模型组合都会从默认对话模型选择器、服务商快速设为默认操作和 Composer 模型菜单中排除。其他服务商的同名模型独立保留。已有会话绑定和历史不改写;仍绑定任一生图候选的会话必须选择对话模型才能发送,运行时也会在推理前拒绝所有已标记生图模型。
## Agent 合约
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 d47163dc0..3ce58a402 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
@@ -8271,21 +8271,26 @@ the latest destination. These assertions measure work counts, not device FPS.
- **Preconditions:** Isolated desktop profile and workspace, built image feature,
local chat and OpenAI Images HTTP fixtures; no live provider credentials.
-- **Steps:** Open Models settings; verify the conversation and image defaults
- share a compact panel. Submit a two-image request through the composer, then
- edit the first output through a follow-up message. Collapse tool details.
- Clear the binding and follow the visible configuration action back to Models.
-- **Expected:** A 12px default-row gap, decoded image previews outside collapsed
- process details, multipart source upload for editing, preserved originals,
- and no image HTTP request while unconfigured.
-- **Settings interactions:** The image summary has no Change/Clear buttons and
- matches the default model's provider/model text styles. Select another
- provider's image model in Advanced and save; the summary changes while the
- chat default stays unchanged. Missing/disabled bindings show only Currently
- unavailable. Covered in `scripts/e2e-image-generation-ui.mjs`.
-- **Conversation selection:** The selected image provider/model is absent from
+- **Steps:** Open Models settings with no image model configured; verify the image
+ summary row is absent. Open a provider's Advanced model settings and verify
+ **Set as image model** is grouped with the image/document attachment
+ capabilities and can be checked for multiple models. Save, use the image
+ summary menu to choose one marked model as the default, then submit a
+ two-image request through the composer and edit the first output through a
+ follow-up message. Collapse tool details.
+- **Expected:** After saving, the image summary appears with a 12px default-row
+ gap and lists all marked candidates, the selected default is changeable
+ without changing the chat default, decoded image previews stay outside
+ collapsed process details, multipart source upload is used for editing,
+ originals are preserved, and no image HTTP request occurs while unconfigured.
+- **Settings interactions:** The unconfigured state renders no image summary.
+ Mark candidates in the attachment capability group, save, and select one
+ from the summary menu. An existing missing/disabled candidate shows only
+ Currently unavailable. Covered in `scripts/e2e-image-generation-ui.mjs`.
+- **Conversation selection:** Every marked image provider/model is absent from
default and Composer candidates. Other providers retain same-ID models. An
- existing session pinned to the image binding is rejected before inference.
+ existing session pinned to any marked image binding is rejected before
+ inference.
- **Transport contracts:** Real stdio reverse RPC retains a thrown local image
error's stable code in the production ParentHostProxy. Local HTTP tests check
single/multiple binary multipart fields and boundaries, DALL-E `b64_json`
diff --git a/packages/shared/src/image-generation.ts b/packages/shared/src/image-generation.ts
index 8d184bc1f..ad26cab3f 100644
--- a/packages/shared/src/image-generation.ts
+++ b/packages/shared/src/image-generation.ts
@@ -2,13 +2,44 @@ import { modelIdsMatch } from "./types/models.js";
/** A single host-owned binding, independent of the default conversation model. */
export type ImageGenerationBinding = { providerId: string; modelId: string };
+export type ImageGenerationBindings =
+ | ImageGenerationBinding
+ | readonly ImageGenerationBinding[];
+
+function sameImageGenerationBinding(
+ left: ImageGenerationBinding,
+ right: ImageGenerationBinding,
+): boolean {
+ return left.providerId === right.providerId && modelIdsMatch(left.modelId, right.modelId);
+}
+
+/** Resolve the multi-select candidates, with legacy single-binding fallback. */
+export function imageGenerationBindings(
+ candidates: readonly ImageGenerationBinding[] | null | undefined,
+ active: ImageGenerationBinding | null | undefined,
+): ImageGenerationBinding[] {
+ const source = candidates === undefined ? (active ? [active] : []) : candidates ?? [];
+ const result: ImageGenerationBinding[] = [];
+ for (const candidate of source) {
+ if (!result.some((entry) => sameImageGenerationBinding(entry, candidate))) {
+ result.push(candidate);
+ }
+ }
+ if (active && !result.some((entry) => sameImageGenerationBinding(entry, active))) {
+ result.push(active);
+ }
+ return result;
+}
+
export function isImageGenerationModel(
- binding: ImageGenerationBinding | null | undefined,
+ binding: ImageGenerationBindings | null | undefined,
providerId: string | undefined,
modelId: string | undefined,
): boolean {
- return !!binding && binding.providerId === providerId && !!modelId &&
- modelIdsMatch(binding.modelId, modelId);
+ const bindings = Array.isArray(binding) ? binding : binding ? [binding] : [];
+ return !!providerId && !!modelId && bindings.some((entry) =>
+ entry.providerId === providerId && modelIdsMatch(entry.modelId, modelId),
+ );
}
export const MAX_GENERATED_IMAGES = 10;
export const IMAGE_GENERATION_TIMEOUT_MS = 180_000;
@@ -41,6 +72,23 @@ export function parseImageGenerationBinding(value: unknown): ImageGenerationBind
return { providerId: field("providerId", 128), modelId: field("modelId", 256) };
}
+export const MAX_IMAGE_GENERATION_MODELS = 128;
+
+export function parseImageGenerationBindings(
+ value: unknown,
+): ImageGenerationBinding[] | null {
+ if (value == null) return null;
+ if (!Array.isArray(value)) invalid("imageGenerationModels must be an array");
+ if (value.length > MAX_IMAGE_GENERATION_MODELS) {
+ invalid(`imageGenerationModels must contain at most ${MAX_IMAGE_GENERATION_MODELS} models`);
+ }
+ return value.map((entry) => {
+ const binding = parseImageGenerationBinding(entry);
+ if (!binding) invalid("imageGenerationModels contains an invalid binding");
+ return binding;
+ });
+}
+
/** Expand variants into individually accountable requests; never silently truncate. */
export function imageGenerationItems(value: unknown): ImageGenerationItem[] {
if (!value || typeof value !== "object" || Array.isArray(value)) invalid("items are required");
diff --git a/packages/shared/src/types/settings.ts b/packages/shared/src/types/settings.ts
index f65060c47..538e77050 100644
--- a/packages/shared/src/types/settings.ts
+++ b/packages/shared/src/types/settings.ts
@@ -23,6 +23,8 @@ export type CloseBehavior = "ask" | "tray" | "quit";
export type AppSettings = {
imageGeneration?: import("../image-generation.js").ImageGenerationBinding | null;
+ /** All models marked for image generation; absent falls back to imageGeneration. */
+ imageGenerationModels?: import("../image-generation.js").ImageGenerationBinding[] | null;
defaultProviderId?: string;
defaultModelId?: string;
/** Host speech bindings. Absent means voice actions stay disabled. */
diff --git a/scripts/e2e/image-generation-ui.tsx b/scripts/e2e/image-generation-ui.tsx
index 419aad4e4..0bc2f1776 100644
--- a/scripts/e2e/image-generation-ui.tsx
+++ b/scripts/e2e/image-generation-ui.tsx
@@ -106,16 +106,19 @@ globalThis.imageGenerationProbe = async () => {
[...document.querySelectorAll<HTMLButtonElement>("button")].find(
(element) => element.textContent?.trim() === text,
);
+ const imageModelToggle = (label: string) =>
+ [...document.querySelectorAll<HTMLInputElement>(
+ ".provider-chosen-capability input[type=\"checkbox\"]",
+ )].find((element) => element.getAttribute("aria-label") === label);
try {
for (const locale of ["en", "zh-CN"]) {
await i18n.changeLanguage(locale);
render();
const defaultRow = container.querySelector<HTMLElement>(".model-default-row")!;
- const imageRow = [...container.querySelectorAll<HTMLElement>(".settings-row")].find(
+ const initialImageRow = [...container.querySelectorAll<HTMLElement>(".settings-row")].find(
(element) => element.textContent?.includes(i18n.t("settings.imageModel")),
- )!;
- const gap = imageRow.getBoundingClientRect().top - defaultRow.getBoundingClientRect().bottom;
- assert(gap >= 11 && gap <= 13, `model defaults should be adjacent rows, got ${gap}px`);
+ );
+ assert(!initialImageRow, "unconfigured image model row should be hidden");
const edit =
container.querySelector<HTMLButtonElement>(
'button[aria-label="' + i18n.t("settings.editProvider") + '"]',
@@ -126,10 +129,10 @@ globalThis.imageGenerationProbe = async () => {
// Enter from the real model settings page, not the advanced pane alone.
click(edit);
await until(
- () => !!button(i18n.t("settings.setImageModel")),
- "advanced image-model action missing",
+ () => !!imageModelToggle(i18n.t("settings.setImageModel")),
+ "advanced image-model capability missing",
);
- click(button(i18n.t("settings.setImageModel")));
+ click(imageModelToggle(i18n.t("settings.setImageModel")));
assert(!settings.imageGeneration, "draft selection persisted before Save");
click(button(i18n.t("settings.cancel")));
assert(!settings.imageGeneration, "cancel changed binding");
@@ -138,26 +141,50 @@ globalThis.imageGenerationProbe = async () => {
'button[aria-label="' + i18n.t("settings.editProvider") + '"]',
),
);
- await until(() => !!button(i18n.t("settings.setImageModel")), "second edit did not mount");
- click(button(i18n.t("settings.setImageModel")));
+ await until(
+ () => !!imageModelToggle(i18n.t("settings.setImageModel")),
+ "second edit did not mount",
+ );
+ click(imageModelToggle(i18n.t("settings.setImageModel")));
+ click(imageModelToggle(i18n.t("settings.setImageModel")));
click(button(i18n.t("settings.saveProvider")));
await until(
() =>
settings.imageGeneration?.modelId === "image-one" &&
+ settings.imageGenerationModels?.length === 2 &&
!document.querySelector(".provider-setup"),
- "saved image model missing",
+ "saved image model candidates missing",
);
+ const imageRow = [...container.querySelectorAll<HTMLElement>(".settings-row")].find(
+ (element) => element.textContent?.includes(i18n.t("settings.imageModel")),
+ )!;
+ assert(imageRow, "saved image model summary missing");
+ const gap = imageRow.getBoundingClientRect().top - defaultRow.getBoundingClientRect().bottom;
+ assert(gap >= 11 && gap <= 13, `model defaults should be adjacent rows, got ${gap}px`);
assert(settings.defaultModelId === "chat-model", "image model changed default chat model");
click(container.querySelector<HTMLButtonElement>(".model-default-trigger"));
await until(() => !!document.querySelector(".model-default-list"), "default picker missing");
assert(!document.querySelector('[aria-label="Images · image-one"]'), "image binding leaked into chat defaults");
- assert(document.querySelector('[aria-label="Images · image-two"]'), "other configured chat model disappeared");
assert(document.querySelector('[aria-label="Images B · image-one"]'), "same model on another provider disappeared");
+ assert(!document.querySelector('[aria-label="Images · image-two"]'), "second image binding leaked into chat defaults");
click(container.querySelector<HTMLButtonElement>(".model-default-trigger"));
const row = [...container.querySelectorAll<HTMLElement>(".settings-row")].find((element) =>
element.textContent?.includes(i18n.t("settings.imageModel")),
)!;
- assert(row.querySelectorAll("button").length === 0, "image summary still offers change or clear");
+ assert(row.querySelector('button[aria-haspopup="listbox"]'), "image summary selector missing");
+ click(row.querySelector<HTMLButtonElement>('button[aria-haspopup="listbox"]'));
+ await until(
+ () => !!document.querySelector('[role="option"]'),
+ "image model candidate picker missing",
+ );
+ const secondImageOption = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(
+ (element) => element.textContent?.includes("image-two"),
+ );
+ click(secondImageOption);
+ await until(
+ () => settings.imageGeneration?.modelId === "image-two",
+ "image default model did not switch",
+ );
const textStyle = (element: Element | null) => {
assert(element, "missing model text");
const style = getComputedStyle(element!);
@@ -167,10 +194,29 @@ globalThis.imageGenerationProbe = async () => {
assert(textStyle(row.querySelector(".model-default-model")) === textStyle(defaultRow.querySelector(".model-default-model")), "model typography differs from default model");
const alternateRow = [...container.querySelectorAll<HTMLElement>(".model-provider-row")].find((element) => element.textContent?.includes("Images B"));
click(alternateRow?.querySelector<HTMLButtonElement>('button[aria-label="' + i18n.t("settings.editProvider") + '"]'));
- await until(() => !!button(i18n.t("settings.setImageModel")), "alternate provider edit missing");
- click(button(i18n.t("settings.setImageModel")));
+ await until(
+ () => !!imageModelToggle(i18n.t("settings.setImageModel")),
+ "alternate provider edit missing",
+ );
+ click(imageModelToggle(i18n.t("settings.setImageModel")));
click(button(i18n.t("settings.saveProvider")));
- await until(() => settings.imageGeneration?.providerId === "q" && !document.querySelector(".provider-setup"), "advanced provider switch did not persist");
+ await until(
+ () =>
+ settings.imageGeneration?.modelId === "image-two" &&
+ settings.imageGenerationModels?.length === 3 &&
+ !document.querySelector(".provider-setup"),
+ "additional image model candidate did not persist",
+ );
+ click(row.querySelector<HTMLButtonElement>('button[aria-haspopup="listbox"]'));
+ await until(() => !!document.querySelector('[role="option"]'), "image candidate picker did not reopen");
+ const alternateImageOption = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(
+ (element) => element.textContent?.includes("Images B") && element.textContent?.includes("image-one"),
+ );
+ click(alternateImageOption);
+ await until(
+ () => settings.imageGeneration?.providerId === "q",
+ "image default provider did not switch",
+ );
assert(settings.defaultProviderId === "chat" && settings.defaultModelId === "chat-model", "image switch changed chat default");
assert(row.textContent?.includes("Images B"), "new provider name missing");
for (const invalid of [
@@ -184,7 +230,10 @@ globalThis.imageGenerationProbe = async () => {
}
settings = { ...settings, imageGeneration: null };
flushSync(() => useAppStore.setState({ settings, providers }));
- assert(row.querySelector('[role="status"]')?.textContent === i18n.t("settings.imageModelUnavailable"), "unset state missing");
+ const unsetImageRow = [...container.querySelectorAll<HTMLElement>(".settings-row")].find(
+ (element) => element.textContent?.includes(i18n.t("settings.imageModel")),
+ );
+ assert(!unsetImageRow, "unset image model row should be hidden");
}
const message = {
@@ -237,6 +286,7 @@ globalThis.imageGenerationProbe = async () => {
"advanced-save-cancel",
"advanced-provider-switch",
"read-only-summary-typography",
+ "unconfigured-summary-hidden",
"unavailable-summary",
"chat-default-preserved",
"image-excluded-from-chat-defaults",