Skip to content

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

feat(composer): inherit recent chat models

zszz37e367e6f1b10
diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsx
index ed2886e66..f8b81bf97 100644
--- a/apps/desktop/src/components/Composer.tsx
+++ b/apps/desktop/src/components/Composer.tsx
@@ -1,3 +1,4 @@
+import { inheritedSessionModelBinding } from "../lib/session-model";
import {
useEffect,
useLayoutEffect,
@@ -326,17 +327,15 @@ export function Composer({
: sessionPermissionMode;
const composerPermissionMode: Exclude<PermissionMode, "inherit"> =
mode === "goal" ? "auto" : effectivePermissionMode;
- const provider = providers.find(
- (candidate) =>
- candidate.id ===
- (activeSession?.providerId ??
- (!activeSession ? draftConfiguration?.providerId : undefined) ??
- settings?.defaultProviderId),
- );
- const modelId =
- activeSession?.modelId ??
- (!activeSession ? draftConfiguration?.modelId : undefined) ??
- (settings?.defaultModelId?.trim() || provider?.models?.[0]?.id || provider?.defaultModelId);
+ const recentModels = useAppStore((s) => s.recentModels);
+ const selectedModel = inheritedSessionModelBinding({
+ draft: activeSession ?? draftConfiguration,
+ settings,
+ providers,
+ recentModels,
+ });
+ const provider = providers.find(candidate => candidate.id === selectedModel.providerId);
+ const modelId = selectedModel.modelId;
const selectedModelCatalog = provider ? providerModels[provider.id] : undefined;
const catalogThinkingProvider = thinkingProviderForModel(
provider,
diff --git a/apps/desktop/src/components/settings/ModelConfigPage.tsx b/apps/desktop/src/components/settings/ModelConfigPage.tsx
index 0363beb3f..ed135d233 100644
--- a/apps/desktop/src/components/settings/ModelConfigPage.tsx
+++ b/apps/desktop/src/components/settings/ModelConfigPage.tsx
@@ -1,15 +1,11 @@
/**
- * Model configuration tab: default model, the AI service list, and the
+ * Model configuration tab: image model selection, the AI service list, and the
* models.dev enrichment snapshot status.
*
* API services, plugin-declared services and vendor subscription accounts
* share one list (D625). An account row still lives and dies through the
* vendor-account editor and `deleteOauthAccount`, never the provider CRUD.
*
- * 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, and
- * adding a provider claims the chat or image default only while none resolves.
*/
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
@@ -20,17 +16,12 @@ import {
} from "@pi-desktop/shared";
import { useAppStore } from "../../stores/app-store";
import { api } from "../../lib/api";
-import { providerDisplayName, providerSearchText } from "../../lib/provider-display";
-import { Button, Input, cx } from "../ui";
+import { Button } from "../ui";
import {
- IconCheck,
- IconChevronDown,
IconConfig,
IconPlus,
IconServer,
- IconSearch,
} from "../icons";
-import { AnchoredMenu } from "./AnchoredMenu";
import { providerServesChatModels } from "./default-model";
import { planImageGenerationDefaults } from "./image-generation-default";
import { copyProviderConfiguration, type ProviderCopyDraft } from "./provider-copy";
@@ -89,16 +80,6 @@ function chatModelOptions(providers: readonly ProviderPublic[], imageModels: rea
}
-function displayedChatModelId(
- provider: ProviderPublic,
- selected: string | undefined,
- imageModels: readonly ImageGenerationBinding[],
-) {
- const configured = chatModelOptions([provider], imageModels).map(({ modelId }) => modelId);
- // Never display a different configured model in place of the saved wire ID.
- return selected?.trim() || configured[0];
-}
-
export function ModelConfigPage() {
const { t, i18n } = useTranslation();
const providers = useAppStore((s) => s.providers);
@@ -109,8 +90,6 @@ export function ModelConfigPage() {
// null = closed, "" = add flow, provider id = edit flow.
const [copyDraft, setCopyDraft] = useState<ProviderCopyDraft | null>(null);
const [setupFor, setSetupFor] = useState<string | null>(null);
- const [pickingDefault, setPickingDefault] = useState(false);
- const [defaultModelQuery, setDefaultModelQuery] = useState("");
const [busyId, setBusyId] = useState<string | null>(null);
const [testingId, setTestingId] = useState<string | null>(null);
const [changingImageModel, setChangingImageModel] = useState(false);
@@ -150,62 +129,13 @@ export function ModelConfigPage() {
const providerReady = (provider: ProviderPublic) =>
providerServesChatModels(provider, imageGenerationCandidates);
- const readyProviders = providers.filter(providerReady);
- const defaultModelOptionsList = chatModelOptions(readyProviders, imageGenerationCandidates);
- const visibleDefaultModelOptions = useMemo(() => {
- const query = defaultModelQuery.trim().toLowerCase();
- if (!query) return defaultModelOptionsList;
- return defaultModelOptionsList.filter(({ provider, modelId }) =>
- `${providerSearchText(provider)} ${modelId}`.toLowerCase().includes(query),
- );
- }, [defaultModelOptionsList, defaultModelQuery]);
-
-
if (!settings) return null;
- const defaultProvider =
- providers.find((provider) => provider.id === settings.defaultProviderId) ?? null;
const editingProvider =
setupFor ? providers.find((provider) => provider.id === setupFor) ?? null : null;
const editingAccount = editingAccountId
? providers.find((provider) => provider.id === editingAccountId) ?? null
: null;
- const effectiveDefaultModelId = settings.defaultModelId?.trim() ||
- defaultProvider?.models?.[0]?.id || defaultProvider?.defaultModelId;
- const defaultProviderReady = defaultProvider !== null && providerReady(defaultProvider) &&
- chatModelOptions([defaultProvider], imageGenerationCandidates).some(
- ({ modelId }) => sameWireId(modelId, effectiveDefaultModelId ?? ""),
- );
-
-
- const setDefaultModel = async (provider: ProviderPublic, modelId: string) => {
- if (isImageCandidate(
- imageCandidates(
- useAppStore.getState().settings?.imageGenerationModels,
- useAppStore.getState().settings?.imageGeneration,
- ),
- provider.id,
- modelId,
- )) return;
- setBusyId(provider.id);
- try {
- await api.setSettings({
- ...settings,
- defaultProviderId: provider.id,
- defaultModelId: modelId,
- });
- await refreshProviders();
- showToast(t("settings.defaultUpdated"), { variant: "success" });
- } catch (error) {
- showToast(error instanceof Error ? error.message : String(error), {
- variant: "error",
- });
- } finally {
- setBusyId(null);
- setPickingDefault(false);
- }
- };
-
/**
* Preserve the selected app defaults unless they were removed from the
* provider or no longer resolve, and let a newly added provider claim a
@@ -427,139 +357,18 @@ export function ModelConfigPage() {
return (
<div className="settings-stack model-config-page">
- <section className="settings-card-block">
- <div className="model-config-section-head">
- <h3 className="settings-card-heading">{t("settings.defaultsTitle")}</h3>
- </div>
- <div className="settings-panel model-default-panel">
- <div className="settings-row model-default-row">
- <div className="settings-row-copy model-default-copy">
- <div className="settings-row-title model-default-label">
- {t("settings.defaultModel")}
- </div>
- {defaultProviderReady ? (
- <div className="settings-row-detail model-default-value">
- <span className="model-default-provider">
- {providerDisplayName(defaultProvider)}
- </span>
- <span className="model-default-sep" aria-hidden>
- ·
- </span>
- <span className="model-default-model font-mono">
- {displayedChatModelId(defaultProvider, effectiveDefaultModelId, imageGenerationCandidates) ||
- t("settings.noModel")}
- </span>
- </div>
- ) : (
- <div className="settings-row-detail model-default-value">
- {defaultProvider && settings.defaultModelId ? (
- <>
- <span className="model-default-provider">{providerDisplayName(defaultProvider)}</span>
- <span className="model-default-sep" aria-hidden>·</span>
- <span className="model-default-model font-mono" title={t("settings.noDefaultProvider")}>
- {settings.defaultModelId}
- </span>
- <span className="model-default-empty">{t("settings.noDefaultProvider")}</span>
- </>
- ) : (
- <span className="model-default-empty">
- {readyProviders.length === 0
- ? t("settings.defaultModelNone")
- : t("settings.noDefaultProvider")}
- </span>
- )}
- </div>
- )}
- </div>
- <AnchoredMenu
- className="model-default-anchor"
- open={pickingDefault}
- onClose={() => setPickingDefault(false)}
- menuClassName="model-default-menu"
- label={t("settings.changeDefaultModel")}
- align="end"
- trigger={(ref) => (
- <Button
- ref={ref}
- className="settings-text-action model-default-trigger"
- variant="ghost"
- disabled={readyProviders.length === 0}
- onClick={() => {
- setDefaultModelQuery("");
- setPickingDefault((current) => !current);
- }}
- aria-haspopup="listbox"
- aria-expanded={pickingDefault}
- >
- {t("settings.changeDefaultModel")}
- <IconChevronDown className="model-default-trigger-chevron" size={13} aria-hidden />
- </Button>
- )}
- >
- <div className="model-default-search">
- <IconSearch size={14} aria-hidden />
- <Input
- value={defaultModelQuery}
- onChange={(event) => setDefaultModelQuery(event.target.value)}
- placeholder={t("settings.defaultModelSearch")}
- aria-label={t("settings.defaultModelSearch")}
- autoFocus
- />
- </div>
- <div className="model-default-results" role="presentation">
- {visibleDefaultModelOptions.length === 0 ? (
- <div className="model-default-no-results">{t("settings.noModelMatches")}</div>
- ) : null}
- <ul className="model-default-list">
- {visibleDefaultModelOptions.map(({ provider, modelId }, index) => {
- const isCurrent =
- provider.id === settings.defaultProviderId &&
- sameWireId(settings.defaultModelId ?? "", modelId);
- const previous = visibleDefaultModelOptions[index - 1];
- const startsGroup = !previous || previous.provider.id !== provider.id;
- return (
- <li key={`${provider.id}:${modelId}`}>
- {startsGroup ? (
- <div
- className={cx(
- "model-default-provider-group",
- index > 0 && "has-divider",
- )}
- >
- {providerDisplayName(provider)}
- </div>
- ) : null}
- <button
- type="button"
- role="option"
- aria-selected={isCurrent}
- aria-label={`${providerDisplayName(provider)} · ${modelId}`}
- className={cx("model-default-option", isCurrent && "is-current")}
- disabled={busyId === provider.id}
- onClick={() => void setDefaultModel(provider, modelId)}
- >
- <span className="model-default-option-check" aria-hidden>
- {isCurrent ? <IconCheck size={12} /> : null}
- </span>
- <span className="model-default-option-model font-mono">{modelId}</span>
- </button>
- </li>
- );
- })}
- </ul>
- </div>
- </AnchoredMenu>
- </div>
- {imageGenerationCandidates.length > 0 ? (
+ {imageGenerationCandidates.length > 0 ? (
+ <section className="settings-card-block">
+ <div className="settings-panel model-default-panel">
<ImageGenerationModelRow
settings={settings}
providers={providers}
busy={changingImageModel}
onChange={setImageGenerationDefault}
/>
- ) : null}
- </div>
- </section>
+ </div>
+ </section>
+ ) : null}
<section className="settings-card-block">
<div className="model-config-section-head">
@@ -615,8 +424,6 @@ export function ModelConfigPage() {
) : (
<ServiceList
providers={providers}
- defaultProviderId={settings.defaultProviderId}
- isReady={providerReady}
accountFor={accountFor}
busy={
busyId !== null ||
@@ -634,12 +441,6 @@ export function ModelConfigPage() {
? setEditingAccountId(provider.id)
: setSetupFor(provider.id)
}
- onMakeDefault={(provider) =>
- void setDefaultModel(
- provider,
- chatModelOptions([provider], imageGenerationCandidates)[0]?.modelId ?? "",
- )
- }
onTest={(provider) => void testProvider(provider)}
onCopy={(provider) => {
setCopyDraft(
diff --git a/apps/desktop/src/components/settings/ServiceList.tsx b/apps/desktop/src/components/settings/ServiceList.tsx
index 25fa90067..300b3641c 100644
--- a/apps/desktop/src/components/settings/ServiceList.tsx
+++ b/apps/desktop/src/components/settings/ServiceList.tsx
@@ -8,7 +8,7 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import type { ProviderPublic } from "@pi-desktop/shared";
-import { IconCopy, IconKey, IconPencil, IconPlug, IconStar, IconTrash } from "../icons";
+import { IconCopy, IconKey, IconPencil, IconPlug, IconTrash } from "../icons";
import { useArmedDelete, type CapabilityMenuItem } from "./AgentCapabilityLayout";
import { ServiceRow } from "./ServiceRow";
import { serviceRowKind } from "./service-row-status";
@@ -17,16 +17,12 @@ import type { AccountEntry } from "./useVendorAccounts";
export type ServiceListProps = {
providers: ProviderPublic[];
- defaultProviderId: string | undefined;
- /** Whether a row can serve as the app default right now. */
- isReady: (provider: ProviderPublic) => boolean;
accountFor: (providerId: string) => AccountEntry | null;
/** A page-level write or dialog is in flight; card order is locked meanwhile. */
busy: boolean;
isRowBusy: (providerId: string) => boolean;
testingId: string | null;
onEdit: (provider: ProviderPublic) => void;
- onMakeDefault: (provider: ProviderPublic) => void;
onTest: (provider: ProviderPublic) => void;
onCopy: (provider: ProviderPublic) => void;
onToggleEnabled: (provider: ProviderPublic) => void;
@@ -37,14 +33,11 @@ export type ServiceListProps = {
export function ServiceList({
providers,
- defaultProviderId,
- isReady,
accountFor,
busy,
isRowBusy,
testingId,
onEdit,
- onMakeDefault,
onTest,
onCopy,
onToggleEnabled,
@@ -78,7 +71,7 @@ export function ServiceList({
}
};
- const menuItems = (provider: ProviderPublic, isDefault: boolean): CapabilityMenuItem[] => {
+ const menuItems = (provider: ProviderPublic): CapabilityMenuItem[] => {
const kind = serviceRowKind(provider);
const items: CapabilityMenuItem[] = [];
// A plugin owns its row's fields and lifetime; only its key is the user's.
@@ -93,17 +86,6 @@ export function ServiceList({
},
});
}
- if (!isDefault && isReady(provider)) {
- items.push({
- key: "default",
- label: t("settings.makeDefault"),
- icon: <IconStar size={14} />,
- onSelect: () => {
- closeMenu(true);
- onMakeDefault(provider);
- },
- });
- }
items.push({
key: "test",
label: t("settings.testConnection"),
@@ -161,7 +143,6 @@ export function ServiceList({
<ul className="model-provider-list" aria-busy={reorder.saving}>
{reorder.providers.map((provider) => {
const kind = serviceRowKind(provider);
- const isDefault = defaultProviderId === provider.id;
const rowBusy = reorder.saving || isRowBusy(provider.id);
const onOpen =
kind !== "plugin"
@@ -174,11 +155,10 @@ export function ServiceList({
key={provider.id}
provider={provider}
entry={accountFor(provider.id)}
- isDefault={isDefault}
busy={rowBusy}
testing={testingId === provider.id}
dragging={reorder.draggingId === provider.id}
- menuItems={menuItems(provider, isDefault)}
+ menuItems={menuItems(provider)}
menuOpen={openMenuId === provider.id}
anyMenuOpen={openMenuId !== null}
restoreMenuFocus={restoreMenuFocus}
diff --git a/apps/desktop/src/components/settings/ServiceRow.tsx b/apps/desktop/src/components/settings/ServiceRow.tsx
index ab786d18c..02f9e8433 100644
--- a/apps/desktop/src/components/settings/ServiceRow.tsx
+++ b/apps/desktop/src/components/settings/ServiceRow.tsx
@@ -28,7 +28,7 @@ const OWN_CONTROLS = "button, input, select, textarea, a, label, .model-provider
export type ServiceRowProps = {
provider: ProviderPublic;
entry: AccountEntry | null;
- isDefault: boolean;
+ isDefault?: boolean;
/** Mid-request (saving, testing, removing): the row starts nothing new. */
busy: boolean;
testing: boolean;
@@ -52,7 +52,7 @@ export type ServiceRowProps = {
export function ServiceRow({
provider,
entry,
- isDefault,
+ isDefault = false,
busy,
testing,
dragging,
diff --git a/apps/desktop/src/features/chat/composer/ComposerModelPicker.tsx b/apps/desktop/src/features/chat/composer/ComposerModelPicker.tsx
index cfb33097b..9dd589aa8 100644
--- a/apps/desktop/src/features/chat/composer/ComposerModelPicker.tsx
+++ b/apps/desktop/src/features/chat/composer/ComposerModelPicker.tsx
@@ -1,9 +1,12 @@
+import { composerModelDisplayName, sameComposerModelId } from "../../../lib/composer-models";
+import { providerDisplayName } from "../../../lib/provider-display";
import type { TFunction } from "i18next";
import type { ReactNode } from "react";
import { ComposerModelList } from "./ComposerModelList";
import { AnchoredMenu } from "../../../components/settings/AnchoredMenu";
import {
IconBot,
+ IconCheck,
IconChevronDown,
IconChevronLeft,
IconChevronRight,
@@ -52,6 +55,7 @@ export function ComposerModelPicker({
modelSearchRef,
modelListRef,
modelGroups,
+ recentEntries,
thinkingMenuLevels,
showView,
selectModel,
@@ -108,6 +112,28 @@ export function ComposerModelPicker({
{view === "root" ? (
<div className="composer-menu-root" ref={rootMenuRef}>
{rootActions}
+ {recentEntries.length > 0 ? (
+ <div role="group" aria-label={t("chat.recentModels")}>
+ <div className="composer-model-group-label">{t("chat.recentModels")}</div>
+ {recentEntries.map(({ provider, model }) => (
+ <button
+ key={`${provider.id}:${model.modelId}`}
+ type="button"
+ className="composer-menu-entry"
+ role="menuitemradio"
+ aria-checked={provider.id === selectedProviderId && sameComposerModelId(model.modelId, selectedModelId ?? "")}
+ title={`${providerDisplayName(provider)} · ${model.modelId}`}
+ onClick={() => void selectModel(provider, model.modelId)}
+ >
+ <span className="composer-menu-entry-label">{composerModelDisplayName(provider, model.modelId)}</span>
+ <span className="composer-menu-entry-value">{providerDisplayName(provider)}</span>
+ {provider.id === selectedProviderId && sameComposerModelId(model.modelId, selectedModelId ?? "") ? (
+ <IconCheck size={14} aria-hidden="true" />
+ ) : null}
+ </button>
+ ))}
+ </div>
+ ) : null}
<button
type="button"
className="composer-menu-entry"
@@ -116,7 +142,7 @@ export function ComposerModelPicker({
onClick={() => showView("model")}
>
<IconBot size={14} aria-hidden="true" />
- <span className="composer-menu-entry-label">{t("chat.model")}</span>
+ <span className="composer-menu-entry-label">{t("chat.allModels")}</span>
<span className="composer-menu-entry-value" title={modelLabel}>{modelLabel}</span>
<IconChevronRight size={14} aria-hidden="true" />
</button>
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu.ts
index 7f5b96bcf..006ef4f5a 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu.ts
@@ -1,3 +1,4 @@
+import { sameRecentModel } from "../../../../lib/recent-models";
import type {
Mode,
ProviderPublic,
@@ -54,6 +55,7 @@ export function useComposerModelMenu({
configureActiveSession,
}: UseComposerModelMenuOptions) {
const providers = useAppStore((s) => s.providers);
+ const recentModels = useAppStore((s) => s.recentModels);
const imageGeneration = useAppStore((s) => s.settings?.imageGeneration);
const imageGenerationModels = useAppStore((s) => s.settings?.imageGenerationModels);
const imageGenerationCandidates = useMemo(
@@ -140,6 +142,15 @@ export function useComposerModelMenu({
.filter((group) => group.models.length > 0),
[providers, providerModels, imageGenerationCandidates],
);
+ const recentEntries = useMemo(() => {
+ const entries = modelGroups.flatMap(group => group.models.map(model => ({ provider: group.provider, model })));
+ return (recentModels ?? []).flatMap(recent => {
+ const entry = entries.find(entry => sameRecentModel(recent, {
+ providerId: entry.provider.id, modelId: entry.model.modelId,
+ }));
+ return entry ? [entry] : [];
+ }).slice(0, 3);
+ }, [modelGroups, recentModels]);
const queryNeedle = query.trim().toLowerCase();
const filteredModelGroups = useMemo(
() =>
@@ -347,6 +358,7 @@ export function useComposerModelMenu({
modelSearchRef,
modelListRef,
modelGroups: filteredModelGroups,
+ recentEntries,
flatModels,
thinkingMenuLevels,
showView,
diff --git a/apps/desktop/src/lib/recent-models.ts b/apps/desktop/src/lib/recent-models.ts
new file mode 100644
index 000000000..73eeb5647
--- /dev/null
+++ b/apps/desktop/src/lib/recent-models.ts
@@ -0,0 +1,33 @@
+import type { SessionModelRef } from "./session-model";
+
+export type RecentModel = { providerId: string; modelId: string };
+const KEY = "pi.desktop.recentModels";
+const LIMIT = 20;
+
+export function sameRecentModel(left: RecentModel, right: RecentModel): boolean {
+ return left.providerId === right.providerId && left.modelId.toLowerCase() === right.modelId.toLowerCase();
+}
+
+export function rememberModelInList(list: readonly RecentModel[], model: SessionModelRef): RecentModel[] {
+ if (!model.providerId?.trim() || !model.modelId?.trim()) return [...list];
+ const selected = { providerId: model.providerId, modelId: model.modelId };
+ return [selected, ...list.filter(entry => !sameRecentModel(entry, selected))].slice(0, LIMIT);
+}
+
+export function loadRecentModels(): RecentModel[] {
+ try {
+ const parsed: unknown = JSON.parse(localStorage.getItem(KEY) ?? "[]");
+ if (!Array.isArray(parsed)) return [];
+ return parsed.filter((entry): entry is RecentModel =>
+ entry !== null && typeof entry === "object" &&
+ typeof entry.providerId === "string" && !!entry.providerId.trim() &&
+ typeof entry.modelId === "string" && !!entry.modelId.trim(),
+ ).reduceRight<RecentModel[]>((list, entry) => rememberModelInList(list, entry), []);
+ } catch {
+ return [];
+ }
+}
+
+export function saveRecentModels(models: readonly RecentModel[]): void {
+ localStorage.setItem(KEY, JSON.stringify(models));
+}
diff --git a/apps/desktop/src/lib/session-model.ts b/apps/desktop/src/lib/session-model.ts
index 41b71431c..6aaf49f51 100644
--- a/apps/desktop/src/lib/session-model.ts
+++ b/apps/desktop/src/lib/session-model.ts
@@ -1,4 +1,5 @@
/** Resolve the provider/model a session should keep after first selection. */
+import type { RecentModel } from "./recent-models";
export type SessionModelRef = {
providerId?: string;
@@ -9,31 +10,72 @@ export type SessionModelProvider = {
id: string;
defaultModelId?: string;
models?: Array<{ id: string }>;
+ enabled?: boolean;
+ hasSecret?: boolean;
+ authKind?: string;
};
export type SessionModelSettings = {
defaultProviderId?: string;
defaultModelId?: string;
+ imageGeneration?: SessionModelRef | null;
+ imageGenerationModels?: SessionModelRef[] | null;
};
+/** Only configured, runnable chat bindings can be inherited by a new chat. */
+export function availableRecentModels(
+ recentModels: readonly RecentModel[],
+ providers: readonly SessionModelProvider[],
+ settings?: SessionModelSettings | null,
+): RecentModel[] {
+ const images = [
+ ...(settings?.imageGenerationModels ?? []),
+ ...(settings?.imageGeneration ? [settings.imageGeneration] : []),
+ ];
+ return recentModels.filter(entry => {
+ const provider = providers.find(item => item.id === entry.providerId);
+ const ids = provider?.models?.length ? provider.models.map(model => model.id) : [provider?.defaultModelId];
+ return provider && provider.enabled !== false &&
+ (provider.authKind === undefined || provider.authKind === "none" || provider.hasSecret) &&
+ ids.some(id => id?.toLowerCase() === entry.modelId.toLowerCase()) &&
+ !images.some(image => image.providerId === entry.providerId && image.modelId?.toLowerCase() === entry.modelId.toLowerCase());
+ });
+}
+
/**
- * App default (or an explicit draft override) at the moment a session is
- * created. Later Settings default-model changes must not rewrite this pair.
+ * Snapshot the most recent available binding when a chat is created.
+ * Explicit drafts and existing session bindings keep their own selection.
*/
export function inheritedSessionModelBinding({
draft,
settings,
providers,
+ recentModels = [],
}: {
draft?: SessionModelRef | null;
settings?: SessionModelSettings | null;
providers: readonly SessionModelProvider[];
+ recentModels?: readonly RecentModel[];
}): SessionModelRef {
- const providerId = draft?.providerId ?? settings?.defaultProviderId;
+ if (draft?.providerId && draft.modelId) {
+ return { providerId: draft.providerId, modelId: draft.modelId };
+ }
+ const fallbackCandidates = providers.flatMap(provider =>
+ (provider.models?.length ? provider.models.map(model => model.id) : [provider.defaultModelId])
+ .filter((modelId): modelId is string => !!modelId)
+ .map(modelId => ({ providerId: provider.id, modelId })),
+ );
+ const legacy = settings?.defaultProviderId && settings.defaultModelId
+ ? [{ providerId: settings.defaultProviderId, modelId: settings.defaultModelId }]
+ : [];
+ const inherited = [...recentModels, ...legacy, ...fallbackCandidates].find(entry =>
+ availableRecentModels([entry], providers, settings).length > 0,
+ );
+ const providerId = draft?.providerId ?? inherited?.providerId;
const provider = providers.find((item) => item.id === providerId);
const modelId =
draft?.modelId ??
- settings?.defaultModelId ??
+ (providerId === inherited?.providerId ? inherited?.modelId : undefined) ??
provider?.defaultModelId ??
provider?.models?.[0]?.id;
return {
@@ -67,18 +109,21 @@ export function sessionNeedsModelPin(
/**
* Durable snapshot for an unpinned session: last used turn, else the current
- * app default. Callers persist this so the session stops following Settings.
+ * recent available model. Callers persist this so later selections cannot
+ * rewrite an existing chat's binding.
*/
export function pinnedSessionModelBinding({
session,
messages,
settings,
providers,
+ recentModels,
}: {
session: SessionModelRef;
messages?: readonly SessionModelRef[];
settings?: SessionModelSettings | null;
providers: readonly SessionModelProvider[];
+ recentModels?: readonly RecentModel[];
}): SessionModelRef {
const used = lastUsedSessionModel(messages ?? []);
return inheritedSessionModelBinding({
@@ -88,5 +133,6 @@ export function pinnedSessionModelBinding({
},
settings,
providers,
+ recentModels,
});
}
diff --git a/apps/desktop/src/lib/settings-search.ts b/apps/desktop/src/lib/settings-search.ts
index a8200958c..f7b5e5032 100644
--- a/apps/desktop/src/lib/settings-search.ts
+++ b/apps/desktop/src/lib/settings-search.ts
@@ -178,7 +178,6 @@ export const SETTINGS_NAV: SettingsNavEntry[] = [
keywordKeys: [
"settings.providers",
"settings.models",
- "settings.defaultModel",
"settings.apiKey",
"settings.baseUrl",
"settings.apiStyle",
diff --git a/apps/desktop/src/stores/app-state.ts b/apps/desktop/src/stores/app-state.ts
index b509f07cb..666e9f128 100644
--- a/apps/desktop/src/stores/app-state.ts
+++ b/apps/desktop/src/stores/app-state.ts
@@ -1,3 +1,4 @@
+import type { RecentModel } from "../lib/recent-models";
import type {
AgentEventEnvelope,
BrowserState,
@@ -153,6 +154,8 @@ export type AppState = {
/** Every checkpoint a session has installed, oldest first. */
sessionCompactions: Record<string, (ContextCompactionMark & { summary?: string })[]>;
providers: ProviderPublic[];
+ recentModels: RecentModel[];
+ rememberModel: (model: { providerId?: string; modelId?: string }) => void;
/** Discovered model lists per provider id (composer model menu). */
providerModels: Record<string, ModelInfo[]>;
workspace?: ProjectWorkspace | null;
diff --git a/apps/desktop/src/stores/runtime/session-coordination.ts b/apps/desktop/src/stores/runtime/session-coordination.ts
index 0e21ce840..972ed09ac 100644
--- a/apps/desktop/src/stores/runtime/session-coordination.ts
+++ b/apps/desktop/src/stores/runtime/session-coordination.ts
@@ -91,6 +91,7 @@ export function createSessionCoordination({
if (!config) break;
try {
const result = await api.configureSession(sessionId, config);
+ get().rememberModel(result.session);
if (runtime.pendingSessionConfigurations.get(sessionId) === config) {
runtime.pendingSessionConfigurations.delete(sessionId);
}
@@ -286,6 +287,7 @@ export function createSessionCoordination({
draft: draftConfig,
settings,
providers: state.providers,
+ recentModels: state.recentModels,
});
const defaultProvider = state.providers.find(
(provider) => provider.id === inherited.providerId,
diff --git a/apps/desktop/src/stores/slices/catalog-slice.ts b/apps/desktop/src/stores/slices/catalog-slice.ts
index 300d39641..ef843a28b 100644
--- a/apps/desktop/src/stores/slices/catalog-slice.ts
+++ b/apps/desktop/src/stores/slices/catalog-slice.ts
@@ -1,3 +1,4 @@
+import { rememberModelInList, saveRecentModels } from "../../lib/recent-models";
import type {
AppNotification,
SessionSummary,
@@ -28,6 +29,7 @@ export function createCatalogSlice({
withoutRecordKey,
}: CatalogSliceDependencies): Pick<
AppState,
+ | "rememberModel"
| "refreshProviders"
| "loadProviderModels"
| "refreshPlugins"
@@ -42,6 +44,15 @@ export function createCatalogSlice({
| "acknowledgeSessionOutcome"
> {
return {
+ rememberModel: (model) => {
+ const recentModels = rememberModelInList(get().recentModels, model);
+ set({ recentModels });
+ try {
+ saveRecentModels(recentModels);
+ } catch (error) {
+ console.warn("Could not persist recent model selection", error);
+ }
+ },
refreshProviders: async () => {
const generation = catalogRuntime.beginProviderRefresh();
const [providers, sessions, settings, onboarding] = await Promise.all([
diff --git a/apps/desktop/src/stores/slices/initial-state.ts b/apps/desktop/src/stores/slices/initial-state.ts
index be1c1b8c6..bbbd8655c 100644
--- a/apps/desktop/src/stores/slices/initial-state.ts
+++ b/apps/desktop/src/stores/slices/initial-state.ts
@@ -1,3 +1,4 @@
+import { loadRecentModels } from "../../lib/recent-models";
import type { AppState, AppStateData } from "../app-state";
import { projectWorkspaceFromPath } from "../../lib/sidebar-preferences";
import { loadSidebarPreferences } from "../../lib/sidebar-preferences";
@@ -18,6 +19,7 @@ function withProjectDisplayName(
export function createInitialState(): AppStateData {
return {
ready: false,
+ recentModels: loadRecentModels(),
healthOk: false,
sessions: [],
sessionMeta: initialSidebarPreferences.sessionMeta,
diff --git a/apps/desktop/src/stores/slices/queue-slice.ts b/apps/desktop/src/stores/slices/queue-slice.ts
index 956ae40fe..585172078 100644
--- a/apps/desktop/src/stores/slices/queue-slice.ts
+++ b/apps/desktop/src/stores/slices/queue-slice.ts
@@ -479,6 +479,9 @@ export function createQueueSlice({
if (submitted?.abortResolution && (await submitted.abortResolution)) {
return false;
}
+ if (current?.source !== "pi-native" && current?.source !== "remote") {
+ get().rememberModel(current ?? {});
+ }
onAccepted?.(startedIn);
return true;
} catch (error) {
diff --git a/apps/desktop/src/stores/slices/session-slice.ts b/apps/desktop/src/stores/slices/session-slice.ts
index 799fef885..37b400377 100644
--- a/apps/desktop/src/stores/slices/session-slice.ts
+++ b/apps/desktop/src/stores/slices/session-slice.ts
@@ -576,6 +576,7 @@ export function createSessionSlice({
messages: selectedMessages,
settings: get().settings,
providers: get().providers,
+ recentModels: get().recentModels,
});
if (pin.providerId && pin.modelId) {
set((state) => ({
@@ -759,6 +760,7 @@ export function createSessionSlice({
config.permissionMode ?? state.draftConfiguration?.permissionMode,
},
}));
+ get().rememberModel(config);
return;
}
if (get().pendingPlans[sessionId]?.status === "pending") return;
@@ -788,6 +790,7 @@ export function createSessionSlice({
);
runtime.pendingSessionConfigurations.delete(sessionId);
const result = await api.configureSession(sessionId, payload);
+ get().rememberModel(result.session);
set((state) => ({
sessions: state.sessions.map((session) =>
session.id === sessionId
diff --git a/apps/desktop/test/default-model-picker.test.mjs b/apps/desktop/test/default-model-picker.test.mjs
index 9d396f259..0f02cae8a 100644
--- a/apps/desktop/test/default-model-picker.test.mjs
+++ b/apps/desktop/test/default-model-picker.test.mjs
@@ -1,99 +1,17 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
-import { loadStyles } from "./helpers/styles.mjs";
-
const read = (rel) => readFile(new URL(rel, import.meta.url), "utf8");
-/**
- * The shared settings row owns the inset inside the panel frame. Keeping this
- * geometry shared prevents the default control from becoming a visually
- * separate card.
- */
-test("the default model control reuses the shared settings row geometry", async () => {
- const styles = await loadStyles();
- const source = await read("../src/components/settings/ModelConfigPage.tsx");
-
- const row = styles.match(/\.settings-row \{([^}]*)\}/);
- assert.ok(row, ".settings-row rule is missing");
- assert.match(row[1], /gap: 24px;/);
- assert.match(row[1], /padding: 14px 16px;/);
- assert.match(source, /className="settings-row model-default-row"/);
- assert.match(source, /className="settings-row-copy model-default-copy"/);
- assert.match(source, /className="settings-row-title model-default-label"/);
-});
-
-test("the default summary stays compact and keeps its change action separate", async () => {
- const styles = await loadStyles();
-
- const copy = styles.match(/\.model-default-copy \{([^}]*)\}/);
- assert.ok(copy, ".model-default-copy rule is missing");
- assert.match(copy[1], /min-width: 0;/);
-
- const row = styles.match(/\.model-default-row \{([^}]*)\}/);
- assert.ok(row, ".model-default-row rule is missing");
- assert.match(row[1], /min-width: 0;/);
-
- const anchor = styles.match(/\.model-default-anchor \{([^}]*)\}/);
- assert.ok(anchor, ".model-default-anchor rule is missing");
- assert.match(anchor[1], /flex: none;/);
-
- const source = await read("../src/components/settings/ModelConfigPage.tsx");
- assert.match(source, /model-default-value/);
- assert.match(source, /settings-text-action model-default-trigger/);
- assert.match(source, /variant="ghost"/);
- assert.doesNotMatch(source, /model-default-icon|model-default-description/);
- assert.doesNotMatch(source, /model-default-trigger-label|model-default-provider-mark/);
- assert.doesNotMatch(source, /defaultModelDescription/);
-});
-
-/**
- * The picker used to expand inside the card, so the Defaults card grew taller
- * with every configured service. It is a bounded floating menu now.
- */
-test("picking a default opens a bounded floating menu, not an inline list", async () => {
- const styles = await loadStyles();
- const source = await read("../src/components/settings/ModelConfigPage.tsx");
-
- assert.doesNotMatch(styles, /\.model-default-picker\b/);
- assert.doesNotMatch(source, /model-default-picker/);
-
- const menu = styles.match(/\.model-default-menu \{([^}]*)\}/);
- assert.ok(menu, ".model-default-menu rule is missing");
- // Fixed, because the settings panel clips its overflow.
- assert.match(menu[1], /position: fixed;/);
- assert.doesNotMatch(menu[1], /position: absolute;/);
- assert.match(menu[1], /width: min\(340px, calc\(100vw - 32px\)\);/);
- assert.match(menu[1], /max-height: min\(400px, calc\(100vh - 120px\)\);/);
- assert.match(styles, /\.model-default-results\s*\{[^}]*overflow-y: auto;/s);
- // Hidden until measured, mirroring the font picker.
- assert.match(menu[1], /visibility: hidden;/);
- assert.match(styles, /\.model-default-menu\.is-open \{[^}]*visibility: visible;/);
- /*
- z-command-palette is the design system's layer for body-portaled menus, and
- it is what the font picker uses; stacking inside the layer is DOM order, so
- the menu must not invent a higher value.
- */
- assert.match(menu[1], /z-index: 60;/);
-});
-
-test("the default picker portals out of the clipped settings panel", async () => {
- const menuSource = await read("../src/components/settings/AnchoredMenu.tsx");
- const source = await read("../src/components/settings/ModelConfigPage.tsx");
-
- assert.match(menuSource, /createPortal\(/);
- assert.match(menuSource, /document\.body/);
- // Escape and an outside press close it; a scrolled-away trigger closes it too.
- assert.match(menuSource, /event\.key !== "Escape"/);
- assert.match(menuSource, /addEventListener\("mousedown", onPointer\)/);
- assert.match(menuSource, /addEventListener\("scroll", onViewportChange, true\)/);
-
- assert.match(source, /<AnchoredMenu/);
- assert.match(source, /aria-haspopup="listbox"/);
- assert.match(source, /role="option"/);
+test("model settings expose image selection but no fixed chat default", async () => {
+ const page = await read("../src/components/settings/ModelConfigPage.tsx");
+ const list = await read("../src/components/settings/ServiceList.tsx");
+ assert.doesNotMatch(page, /"settings\.defaultModel"|changeDefaultModel|setDefaultModel|pickingDefault/);
+ assert.doesNotMatch(list, /settings\.makeDefault|onMakeDefault|defaultProviderId/);
+ assert.match(page, /<ImageGenerationModelRow/);
});
-test("the default picker keeps keyboard focus contained", async () => {
+test("shared anchored menus keep keyboard focus contained", async () => {
const menuSource = await read("../src/components/settings/AnchoredMenu.tsx");
// Opening focuses the current option, so Enter re-confirms the default
diff --git a/apps/desktop/test/helpers/composer-toolbar.mjs b/apps/desktop/test/helpers/composer-toolbar.mjs
index 3880f5736..dd6e03a4b 100644
--- a/apps/desktop/test/helpers/composer-toolbar.mjs
+++ b/apps/desktop/test/helpers/composer-toolbar.mjs
@@ -43,6 +43,7 @@ export const TOOLBAR_PROPS = {
modelListRef: { current: null },
thinkingListRef: { current: null },
modelGroups: [],
+ recentEntries: [],
thinkingMenuLevels: [],
showView: noop,
selectModel: noop,
diff --git a/apps/desktop/test/provider-display-name.test.mjs b/apps/desktop/test/provider-display-name.test.mjs
index 7ec9fc6b7..860f4989d 100644
--- a/apps/desktop/test/provider-display-name.test.mjs
+++ b/apps/desktop/test/provider-display-name.test.mjs
@@ -102,7 +102,6 @@ test("the default picker's query reaches an account by its label", () => {
test("the Settings model pickers name providers through the shared helper", async () => {
for (const rel of [
- "../src/components/settings/ModelConfigPage.tsx",
"../src/components/settings/EnhancementModelCard.tsx",
]) {
const source = await read(rel);
diff --git a/apps/desktop/test/provider-model-config.test.mjs b/apps/desktop/test/provider-model-config.test.mjs
index 9ecfcbd2b..8e27589d7 100644
--- a/apps/desktop/test/provider-model-config.test.mjs
+++ b/apps/desktop/test/provider-model-config.test.mjs
@@ -215,22 +215,10 @@ test("model ids are matched case-insensitively across picking and hand entry", (
assert.match(pickerSource, /settings\.modelAlreadyAdded/);
});
-test("default model selection saves the exact model and provider", () => {
- // The settings picker is model-level; provider rows still use their first
- // model as a convenience action.
- assert.match(pageSource, /const setDefaultModel = async \(provider: ProviderPublic, modelId: string\)/);
- assert.match(pageSource, /defaultProviderId: provider.id,[\s\S]*defaultModelId: modelId/);
- assert.match(pageSource, /onClick=\{\(\) => void setDefaultModel\(provider, modelId\)\}/);
- assert.match(pageSource, /visibleDefaultModelOptions\.map/);
- assert.match(pageSource, /provider\.id === settings\.defaultProviderId &&[\s\S]*sameWireId/);
+test("provider edits retain legacy defaults for non-chat consumers", () => {
assert.match(pageSource, /defaultModelId: firstModelId \?\? ""/);
- assert.match(
- pageSource,
- /settings\.defaultProviderId === saved\.id && firstModelId[\s\S]*defaultModelId: firstModelId/,
- );
- // The summary line must resolve a configured complete wire id.
- assert.match(pageSource, /displayedChatModelId\(/);
- assert.doesNotMatch(pageSource, /\{settings\.defaultModelId \|\|/);
+ assert.match(pageSource, /settings\.defaultProviderId === saved\.id && firstModelId/);
+ assert.doesNotMatch(pageSource, /setDefaultModel|displayedChatModelId/);
});
test("the rejected catalog-browser styles are gone from the cascade", () => {
@@ -372,7 +360,6 @@ test("settings match complete case-normalized wire ids, not proxy suffixes", ()
assert.equal(sameWireId("PROXY/model", "proxy/MODEL"), true);
assert.equal(sameWireId("proxy/model", "model"), false);
assert.match(pageSource, /isImageCandidate\(imageModels, provider\.id, id\)/);
- assert.match(pageSource, /sameWireId\(settings\.defaultModelId \?\? "", modelId\)/);
assert.match(pageSource, /!models\.some\(\(model\) => sameWireId\(model\.id, settings\.defaultModelId/);
assert.doesNotMatch(pageSource, /modelIdsMatch|isImageGenerationModel/);
assert.doesNotMatch(setupSource, /modelIdsMatch/);
@@ -392,11 +379,4 @@ test("new chat default skips an image-only first model", () => {
assert.match(pageSource, /if \(!keepsCurrentDefault && firstModelId\)/);
});
-test("stale image-valued chat default remains visible but is not marked ready", () => {
- assert.match(pageSource, /const defaultProviderReady = defaultProvider !== null && providerReady\(defaultProvider\) &&[\s\S]*?chatModelOptions\(\[defaultProvider\], imageGenerationCandidates\)\.some/);
- assert.match(pageSource, /const effectiveDefaultModelId = settings\.defaultModelId\?\.trim\(\) \|\|\s*defaultProvider\?\.models\?\.\[0\]\?\.id \|\| defaultProvider\?\.defaultModelId/);
- assert.match(pageSource, /sameWireId\(modelId, effectiveDefaultModelId \?\? ""\)/);
- assert.match(pageSource, /return selected\?\.trim\(\) \|\| configured\[0\]/);
- assert.match(pageSource, /className="model-default-model font-mono" title=\{t\("settings\.noDefaultProvider"\)\}/);
- assert.match(pageSource, /\{settings\.defaultModelId\}/);
-});
+// Chat inheritance and image exclusions are exercised by recent-models.test.mjs.
diff --git a/apps/desktop/test/recent-model-flow.test.mjs b/apps/desktop/test/recent-model-flow.test.mjs
new file mode 100644
index 000000000..3fde7a59a
--- /dev/null
+++ b/apps/desktop/test/recent-model-flow.test.mjs
@@ -0,0 +1,52 @@
+import i18n from "i18next";
+import { en } from "@pi-desktop/i18n";
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { useAppStore, materializeDraftSession } = await import("../src/stores/app-store.ts");
+const { api } = await import("../src/lib/api.ts");
+const { loadRecentModels } = await import("../src/lib/recent-models.ts");
+
+test("select model, create chat, change model and restore history through real store actions", async t => {
+ await i18n.init({ lng: "en", resources: { en: { translation: en } } });
+ const previousStorage = globalThis.localStorage;
+ const storage = new Map();
+ globalThis.localStorage = { getItem: key => storage.get(key), setItem: (key, value) => storage.set(key, value) };
+ t.after(() => { globalThis.localStorage = previousStorage; });
+ const provider = { id: "p", enabled: true, authKind: "none", models: [{ id: "a" }, { id: "b" }] };
+ useAppStore.setState({ providers: [provider], activeSessionId: null, sessions: [], recentModels: [], draftConfiguration: null,
+ settings: { defaultProviderId: "p", defaultModelId: "a", defaultMode: "agent" }, workspace: null });
+ await useAppStore.getState().configureActiveSession({ mode: "agent", providerId: "p", modelId: "b", thinkingLevel: "off" });
+ assert.deepEqual(loadRecentModels(), [{ providerId: "p", modelId: "b" }]);
+ useAppStore.setState({ draftConfiguration: null });
+ let nextId = 0;
+ t.mock.method(api, "createSession", async config => ({ session: { ...config, id: `s${++nextId}`, messages: [] } }));
+ await materializeDraftSession();
+ const first = useAppStore.getState().sessions.find(s => s.id === "s1");
+ assert.equal(first.modelId, "b");
+ t.mock.method(api, "configureSession", async (id, config) => ({ session: { ...first, ...config, id } }));
+ await useAppStore.getState().configureActiveSession({ mode: "agent", providerId: "p", modelId: "a", thinkingLevel: "off" });
+ assert.deepEqual(loadRecentModels().map(m => m.modelId), ["a", "b"]);
+ t.mock.method(api, "configureSession", async () => { throw new Error("configuration rejected"); });
+ await assert.rejects(useAppStore.getState().configureActiveSession({ mode: "agent", providerId: "p", modelId: "b", thinkingLevel: "off" }));
+ assert.equal(loadRecentModels()[0].modelId, "a");
+ useAppStore.setState({ activeSessionId: null, draftConfiguration: null, recentModels: loadRecentModels() });
+ await materializeDraftSession();
+ assert.equal(useAppStore.getState().sessions.find(s => s.id === "s2").modelId, "a");
+ assert.equal(first.modelId, "b", "original binding snapshot is immutable");
+ useAppStore.setState({ sessions: useAppStore.getState().sessions.map(session =>
+ session.id === "s2" ? { ...session, title: "Existing conversation", modelId: "b" } : session),
+ });
+ t.mock.method(api, "prompt", async () => ({}));
+ const accepted = await useAppStore.getState().sendPrompt("test existing model");
+ assert.equal(accepted, true, JSON.stringify(useAppStore.getState().messages));
+ assert.equal(loadRecentModels()[0].modelId, "b", "sending in an existing chat records its own model");
+ useAppStore.setState({ runningSessions: {}, isRunning: false, sessions: useAppStore.getState().sessions.map(session =>
+ session.id === "s2" ? { ...session, modelId: "a" } : session),
+ });
+ t.mock.method(api, "prompt", async () => { throw new Error("submission rejected"); });
+ assert.equal(await useAppStore.getState().sendPrompt("rejected"), false);
+ assert.equal(loadRecentModels()[0].modelId, "b", "rejection cannot replace the last used binding");
+
+});
diff --git a/apps/desktop/test/recent-models.test.mjs b/apps/desktop/test/recent-models.test.mjs
new file mode 100644
index 000000000..ab88aced5
--- /dev/null
+++ b/apps/desktop/test/recent-models.test.mjs
@@ -0,0 +1,67 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { loadRecentModels, rememberModelInList, saveRecentModels } from "../src/lib/recent-models.ts";
+import { availableRecentModels, inheritedSessionModelBinding, pinnedSessionModelBinding } from "../src/lib/session-model.ts";
+
+const ref = (providerId, modelId) => ({ providerId, modelId });
+const providers = [
+ { id: "a", enabled: true, authKind: "none", models: [{ id: "one" }, { id: "two" }, { id: "image" }] },
+ { id: "b", enabled: true, authKind: "api_key", hasSecret: true, models: [{ id: "one" }] },
+];
+const settings = { defaultProviderId: "a", defaultModelId: "one", imageGenerationModels: [ref("a", "image")] };
+
+test("recent selection restores after reload and deduplicates exact provider/model pairs", () => {
+ const old = globalThis.localStorage;
+ const data = new Map();
+ globalThis.localStorage = { getItem: key => data.get(key), setItem: (key, value) => data.set(key, value) };
+ try {
+ let list = [];
+ for (const model of [ref("a", "one"), ref("b", "one"), ref("a", "two"), ref("a", "ONE")]) {
+ list = rememberModelInList(list, model);
+ }
+ saveRecentModels(list);
+ const restored = loadRecentModels();
+ assert.deepEqual(restored, [ref("a", "ONE"), ref("a", "two"), ref("b", "one")]);
+ assert.deepEqual(inheritedSessionModelBinding({ providers, settings, recentModels: restored }), ref("a", "ONE"));
+ } finally { globalThis.localStorage = old; }
+});
+
+test("new chat inherits recent available model and existing chats retain their own binding", () => {
+ const recentModels = [ref("b", "one"), ref("a", "two")];
+ assert.deepEqual(inheritedSessionModelBinding({ providers, settings, recentModels }), ref("b", "one"));
+ assert.deepEqual(inheritedSessionModelBinding({ providers, settings, recentModels, draft: ref("a", "two") }), ref("a", "two"));
+ assert.deepEqual(pinnedSessionModelBinding({ providers, settings, recentModels, session: ref("a", "one") }), ref("a", "one"));
+});
+
+test("deleted, disabled, unauthenticated and image models are skipped before inheritance", () => {
+ const recentModels = [ref("missing", "one"), ref("a", "removed"), ref("a", "image"), ref("b", "one"), ref("a", "two")];
+ for (const unavailable of [{ enabled: false }, { hasSecret: false }]) {
+ const current = [providers[0], { ...providers[1], ...unavailable }];
+ assert.deepEqual(availableRecentModels(recentModels, current, settings), [ref("a", "two")]);
+ assert.deepEqual(inheritedSessionModelBinding({ providers: current, settings, recentModels }), ref("a", "two"));
+ }
+});
+
+test("first run preserves a valid legacy selection, otherwise selects a runnable chat model", () => {
+ assert.deepEqual(inheritedSessionModelBinding({ providers, settings }), ref("a", "one"));
+ assert.deepEqual(inheritedSessionModelBinding({ providers, settings: { defaultProviderId: "missing", defaultModelId: "gone" } }), ref("a", "one"));
+ assert.deepEqual(inheritedSessionModelBinding({ providers: [] }), {});
+ assert.deepEqual(inheritedSessionModelBinding({ providers, recentModels: [ref("a", "image")],
+ settings: { ...settings, imageGenerationModels: [], imageGeneration: ref("a", "image") },
+ }), ref("a", "one"));
+ assert.deepEqual(inheritedSessionModelBinding({ providers, settings, draft: { providerId: "b" } }), ref("b", "one"));
+});
+
+test("corrupt local preferences are ignored and history remains bounded", () => {
+ const old = globalThis.localStorage;
+ try {
+ globalThis.localStorage = { getItem: () => '{broken' };
+ assert.deepEqual(loadRecentModels(), []);
+ globalThis.localStorage = { getItem: () => JSON.stringify([null, {}, ref("a", "one"), ref("a", "one"), ref("", "two")]) };
+ assert.deepEqual(loadRecentModels(), [ref("a", "one")]);
+ let history = [];
+ for (let i = 0; i < 30; i++) history = rememberModelInList(history, ref("a", String(i)));
+ assert.equal(history.length, 20);
+ assert.equal(history[0].modelId, "29");
+ } finally { globalThis.localStorage = old; }
+});
diff --git a/apps/desktop/test/settings-general.test.mjs b/apps/desktop/test/settings-general.test.mjs
index 475c1f3ae..9c58f611b 100644
--- a/apps/desktop/test/settings-general.test.mjs
+++ b/apps/desktop/test/settings-general.test.mjs
@@ -286,28 +286,6 @@ test("model configuration keeps model defaults; AI owns app behavior defaults",
assert.doesNotMatch(providersSource, /EnhancementModelCard/);
});
-test("default model selector shows every configured model under its provider", () => {
- const defaultModelPicker =
- providersSource.match(
- /visibleDefaultModelOptions\.map\(\(\{ provider, modelId \}, index\) => \{[\s\S]*?<\/li>/,
- )?.[0] ?? "";
- assert.notEqual(defaultModelPicker, "");
- assert.match(defaultModelPicker, /model-default-provider-group/);
- assert.match(defaultModelPicker, /model-default-option-model font-mono">[\s\S]*?\{modelId\}/);
- assert.match(defaultModelPicker, /setDefaultModel\(provider, modelId\)/);
- assert.match(providersSource, /settings-text-action model-default-trigger/);
- assert.doesNotMatch(providersSource, /defaultModelDescription/);
- // The accessible name follows the provider heading, which is the vendor
- // account's own label when it has one (#785).
- assert.match(
- providersSource,
- /aria-label=\{`\$\{providerDisplayName\(provider\)\} · \$\{modelId\}`\}/,
- );
- assert.match(providersSource, /placeholder=\{t\("settings\.defaultModelSearch"\)\}/);
- assert.match(providersSource, /model-default-results/);
- assert.match(stylesSource, /\.model-default-results\s*\{[\s\S]*?overflow-y: auto;/);
- assert.match(stylesSource, /scrollbar-gutter: stable/);
-});
test("model configuration lists AI services and vendor accounts together", () => {
// One list (D625): nothing filters OAuth rows out, and no second section.
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 08c40f9bf..0cbeb7ac6 100644
--- a/docs/spec/03-runtime/13-model-catalog-and-selection.md
+++ b/docs/spec/03-runtime/13-model-catalog-and-selection.md
@@ -400,34 +400,32 @@ duplicate accounts from one vendor remain distinguishable; Composer model rows
show the configured wire model ID, while a configured alias remains available
as the compact selected-chip label.
-## 10. Default model policy
-
-App-level default:
-- first successfully tested provider + its default/recommended model
-- the Settings default-model picker lists every configured model under its provider; selecting an entry persists both the owning provider and that exact model ID
-- saving that provider preserves the selected app-default model while it remains configured; removing it falls back to the first remaining binding
-- the picker supports local search across provider name and model ID; its result list scrolls within the floating surface and shows an explicit empty state when no model matches
-- the picker uses concise settings-specific search copy; each result gives visual priority to the model ID and keeps the provider as secondary metadata
-- results are grouped by provider so a provider name is shown once per group rather than repeated on every model row
-- a provider is named the same way here as in the Composer menu: an OAuth row
- uses its non-secret account label when present, so two accounts of one vendor
- stay distinguishable in the group heading, in the summary line that reports
- the current default, and in each option's accessible name. Search matches the
- account label and the vendor name, so either spelling reaches the row
-- the Settings prompt-enhancement model picker reuses this menu and resolves its
- provider names the same way
-- if none configured, onboarding checklist requires provider setup before first agent run
-
-Session-level:
-- inherits app default at creation and stores that `providerId`/`modelId` pair
-- later Settings default-model changes apply only to new sessions and the
- unpersisted home draft, not to already created sessions
-- initializes thinking from the inherited model's binding default. A known
- reasoning model with no stored default falls back to its highest enabled
- level; an unmatched model with no stored default starts at `off` while its
- canonical thinking levels remain selectable in Composer. An empty or
- `off`-only binding starts at `off`
-- can override independently
+## 10. Recent chat model policy
+
+New desktop chats inherit the most recently selected or used available chat
+model. An explicit draft selection takes precedence; existing sessions retain
+their pinned provider/model pair. Selecting or submitting an existing chat does
+not change another chat's binding. Opening a chat alone does not reorder history.
+
+The renderer stores up to 20 provider/model pairs in the local UI preferences,
+newest first, deduplicated by provider ID and case-insensitive full wire model ID.
+Accepted model configuration and prompt submission update the history; failed
+configuration and rejected submissions do not. Deferred configuration updates
+history after host acceptance. This preference survives renderer reload and app
+restart and is not part of cloud configuration sync.
+
+Inheritance skips deleted, disabled, unauthenticated and image-generation
+bindings. With no usable history it uses a valid legacy app selection, otherwise
+the first available configured chat binding. Legacy settings and provider default
+fields remain readable for scheduled jobs and older consumers; no database or
+IPC migration is required. Settings has no fixed chat-default picker or service
+"Make default" action. Image-generation selection remains independent.
+
+The combined Composer model menu shows the three most recent available bindings
+first. Each row identifies the provider as well as the model or alias. All models
+opens the existing searchable, provider-grouped catalog. Discovery enriches exact
+configured IDs without adding unconfigured choices. Model and reasoning changes
+retain the existing session configuration and permission boundaries.
## 11. Capability gating
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index e1f9024ed..9aca255b2 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -3049,7 +3049,7 @@ reasoning-level control.
model therefore updates the draft Composer's available levels and binding
default thinking level immediately; the persisted session keeps the same
exact-model capability after materialization.
-- A new session whose catalog-matched default model supports reasoning starts
+- A new session whose inherited catalog-matched model supports reasoning starts
with Thinking enabled at that model's stored default thinking level, clamped
onto the enabled set. When the binding has no default, it falls back to the
highest enabled level. An unmatched model starts at `off` unless its binding
@@ -3839,31 +3839,18 @@ saves the previewed order; Escape, pointer cancellation, focus loss, unmount or
catalog changes cancel the drag. Buttons and form controls retain their actions.
There is no separate drag handle. A focused card accepts Up/Down to move one visible row. Saving blocks further
moves; a failed save shows an error and restores the accepted order. Late catalog
-responses cannot restore an earlier order. The default-model picker and Composer
-model groups follow the persisted order. Sorting changes neither the selected
+responses cannot restore an earlier order. Composer All models groups follow the persisted order. Sorting changes neither the selected
default nor provider configuration. OAuth accounts remain in their separate section.
-1. **Defaults card** — a compact settings row reusing the shared
- 14px/16px row geometry; the Default model label sits above the provider name
- and exact model ID, while a quiet Change action opens the picker without
- duplicating the current value. The floating listbox is anchored to that
- action rather than expanding the card in place: the surface portals to
- `document.body` as a fixed layer so the panel's overflow cannot clip it,
- groups model-level options by provider, marks the exact current entry, bounds
- its own height so many configured models scroll instead of stretching the
- card, flips above the trigger when there is no room below, and closes on
- Escape, an outside press, or the trigger scrolling out of view.
- A provider is named here the way the Composer model menu names it: an OAuth
- row uses its non-secret account label when present, so two accounts of one
- vendor do not collapse into identical group headings, summary lines, or
- option names; the search matches the account label and the vendor name.
- Global operating mode, command shell, and Enter-to-send live in the Settings
- AI destination
-2. **Vendor accounts** — section title + primary Add account action and one
- single-level list panel using the same row surface as AI services; one row
- per OAuth account, including duplicate vendors, with account label, Edit,
- Test connection, and Remove actions; the default model is edited in the
- account dialog and selected from Defaults
+1. **Model selection** — chat models are selected in the Composer. Its first
+ menu shows up to three recent available provider/model pairs and an All
+ models entry for the searchable catalog. New chats inherit the last usable
+ selection; existing chats keep their own binding. The fixed chat-default
+ picker and service Make default action are absent. The independent image
+ model row remains when image-generation candidates are configured.
+2. **Vendor accounts** — account labels, configured models, Test connection,
+ and Remove actions remain available through the shared service list and
+ account editor. The first binding remains the provider compatibility default.
3. **Providers head** — section title + primary Add provider action; its
button treatment matches Add account
4. **Dialogs** — both the vendor-account edit dialog and the provider dialog
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 2d6e59c8d..4cd2632df 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -16676,3 +16676,21 @@ preload, API normalization, store events, ToolRow, and Markdown renderer.
No provider credentials or paid model calls are required. The fixture ends at
work-panel file-request routing; artifact bytes are verified from the real
host-created files. The full app's file-preview viewer is covered separately.
+
+
+## Composer recent chat models
+
+- Select four distinct configured chat models across providers. Open the combined
+ model menu: exactly the latest three available pairs appear in recency order,
+ with provider labels. Select an older recent row and verify it moves first.
+- Open All models, search and choose using keyboard navigation. Verify thinking
+ defaults still follow the selected binding and manual same-model levels survive.
+- Create a new chat: it inherits the latest selection. Reload local preferences
+ and create another chat: the same binding is restored. An existing chat keeps
+ its own binding; rejected configuration does not replace the recent selection.
+- Disable/remove a provider or model and mark a model for image generation:
+ unavailable history entries are skipped for inheritance and recent menu rows.
+- Settings contains no fixed chat-default picker or Make default service action;
+ image model selection and provider configuration remain available.
+- Coverage: recent-models.test.mjs, recent-model-flow.test.mjs,
+ default-model-picker.test.mjs, and scripts/e2e-composer-model-selection.mjs.
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 4a70b14f5..85d259e98 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -529,6 +529,8 @@ export const de = {
"userMessage": "Benutzernachricht",
"assistantMessage": "Assistentennachricht",
"model": "Modell",
+ recentModels: "Zuletzt verwendet",
+ allModels: "Alle Modelle",
"searchModels": "Modelle suchen",
"noModelResults": "Keine passenden Modelle",
"modelBadgeReasoning": "Begründung",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index fd8cafe39..e232f8c62 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -541,6 +541,8 @@ export const en = {
userMessage: "User message",
assistantMessage: "Assistant message",
model: "Model",
+ recentModels: "Recently used",
+ allModels: "All models",
searchModels: "Search models",
noModelResults: "No matching models",
modelBadgeReasoning: "reasoning",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index a04226cdb..07a2c8a8f 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -529,6 +529,8 @@ export const es = {
"userMessage": "Mensaje de usuario",
"assistantMessage": "Mensaje del asistente",
"model": "Modelo",
+ recentModels: "Usados recientemente",
+ allModels: "Todos los modelos",
"searchModels": "Buscar modelos",
"noModelResults": "No hay modelos coincidentes",
"modelBadgeReasoning": "razonamiento",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index ae35a093a..cecb6b48b 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -529,6 +529,8 @@ export const fr = {
"userMessage": "Message utilisateur",
"assistantMessage": "Message de l'assistant",
"model": "Modèle",
+ recentModels: "Récemment utilisés",
+ allModels: "Tous les modèles",
"searchModels": "Rechercher des modèles",
"noModelResults": "Aucun modèle correspondant",
"modelBadgeReasoning": "raisonnement",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 2520593d2..22ef6a81b 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -538,6 +538,8 @@ export const ko = {
userMessage: "사용자 메시지",
assistantMessage: "어시스턴트 메시지",
model: "모델",
+ recentModels: "최근 사용",
+ allModels: "모든 모델",
searchModels: "모델 검색",
noModelResults: "일치하는 모델 없음",
modelBadgeReasoning: "추론",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 09e8af6e9..0aed9459c 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -527,6 +527,8 @@ export const ptBR = {
userMessage: "Mensagem do usuário",
assistantMessage: "Mensagem do assistente",
model: "Modelo",
+ recentModels: "Usados recentemente",
+ allModels: "Todos os modelos",
searchModels: "Pesquisar modelos…",
noModelResults: "Nenhum modelo encontrado",
modelBadgeReasoning: "Raciocínio",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index dc08727ed..f081c9376 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -538,6 +538,8 @@ export const tr = {
userMessage: "Kullanıcı iletisi",
assistantMessage: "Asistan iletisi",
model: "Model",
+ recentModels: "Son kullanılanlar",
+ allModels: "Tüm modeller",
searchModels: "Model ara",
noModelResults: "Eşleşen model yok",
modelBadgeReasoning: "akıl yürütme",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index a094d6213..462fba57e 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -533,6 +533,8 @@ export const zhCN = {
userMessage: "用户消息",
assistantMessage: "助手消息",
model: "模型",
+ recentModels: "最近使用",
+ allModels: "全部模型",
searchModels: "搜索模型",
noModelResults: "没有匹配的模型",
modelBadgeReasoning: "推理",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index cb78a4cd6..15b4244f3 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -533,6 +533,8 @@ export const zhTW = {
userMessage: "使用者訊息",
assistantMessage: "助手訊息",
model: "模型",
+ recentModels: "最近使用",
+ allModels: "全部模型",
searchModels: "搜尋模型",
noModelResults: "沒有匹配的模型",
modelBadgeReasoning: "推理",
diff --git a/scripts/e2e/composer-model-selection.tsx b/scripts/e2e/composer-model-selection.tsx
index d8a9fc655..cfe103994 100644
--- a/scripts/e2e/composer-model-selection.tsx
+++ b/scripts/e2e/composer-model-selection.tsx
@@ -1,9 +1,14 @@
+import { loadRecentModels } from "../../apps/desktop/src/lib/recent-models";
+import { ComposerModelPicker } from "../../apps/desktop/src/features/chat/composer/ComposerModelPicker";
+import { createInstance } from "i18next";
+import { en } from "@pi-desktop/i18n";
+const i18n = createInstance();
import { useState } from "react";
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
import type { ModelInfo, ProviderPublic, SessionThinkingLevel } from "@pi-desktop/shared";
import { useComposerModelMenu } from "../../apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu";
-import { useAppStore } from "./fixtures/composer-model-selection-store";
+import { useAppStore, rememberSelectedModel } from "./fixtures/composer-model-selection-store";
type MenuController = ReturnType<typeof useComposerModelMenu>;
@@ -27,6 +32,8 @@ const provider: ProviderPublic = {
authKind: "none",
hasSecret: false,
models: [
+ { id: "model-c", contextWindow: 32000, maxTokens: 4000, thinkingLevels: [], defaultThinkingLevel: null },
+ { id: "model-d", contextWindow: 32000, maxTokens: 4000, thinkingLevels: [], defaultThinkingLevel: null },
{ id: "model-a", contextWindow: 32_000, maxTokens: 4_000, thinkingLevels: ["low", "high"], defaultThinkingLevel: "high" },
{ id: "model-b", contextWindow: 32_000, maxTokens: 4_000, thinkingLevels: ["low", "high"], defaultThinkingLevel: "high" },
],
@@ -46,7 +53,9 @@ const models: ModelInfo[] = ["model-a", "model-b"].map((modelId) => ({
source: "user",
}));
-useAppStore.setState({ providers: [provider], providerModels: { [provider.id]: models } });
+useAppStore.setState({ providers: [provider], providerModels: { [provider.id]: models },
+ recentModels: ["model-d", "model-c", "model-b", "model-a"].map(modelId => ({ providerId: provider.id, modelId })),
+});
const host = document.createElement("div");
document.body.append(host);
@@ -67,6 +76,7 @@ function Fixture() {
controlsBlocked: false,
configureActiveSession: async (configuration) => {
writes.push(configuration);
+ rememberSelectedModel({ providerId: provider.id, modelId: configuration.modelId ?? "model-a" });
setModelId(configuration.modelId ?? "model-a");
setThinkingLevel(configuration.thinkingLevel);
},
@@ -74,6 +84,12 @@ function Fixture() {
globalThis.composerModelSelectionController = controller;
return (
<div className="composer-stack" style={{ position: "absolute", left: 120, top: 300, width: 640 }}>
+ <ComposerModelPicker
+ t={i18n.t} controller={controller} modelLabel={modelId}
+ thinkingLabel={thinkingLevel} thinkingLevel={thinkingLevel}
+ selectedProviderId={provider.id} selectedModelId={modelId}
+ controlsBlocked={false} onCloseOtherMenus={() => {}}
+ />
<span className="selected-model">{modelId}</span>
<span className="selected-thinking-level">{thinkingLevel}</span>
</div>
@@ -85,14 +101,36 @@ const settle = () => new Promise<void>((resolve) =>
);
globalThis.composerModelSelectionProbe = async () => {
+ await i18n.init({ lng: "en", resources: { en: { translation: en } }, interpolation: { escapeValue: false } });
flushSync(() => root.render(<Fixture />));
await settle();
- await globalThis.composerModelSelectionController!.selectModel(provider, "model-b");
+ document.querySelector<HTMLButtonElement>(".composer-model-thinking-chip")!.click();
await settle();
+ const recentRows = Array.from(document.querySelectorAll<HTMLButtonElement>(".composer-menu-root [role=menuitemradio]"));
+ if (recentRows.length !== 3 || !recentRows[0].textContent?.includes("model-d") || !recentRows[2].textContent?.includes("model-b")) {
+ throw new Error("The first model menu must show exactly the three most recent models in order");
+ }
+ recentRows[2].click();
+ await settle();
+ if (!document.querySelector(".composer-menu-root [role=menuitemradio]")?.textContent?.includes("model-b")) {
+ throw new Error("Selecting a recent model must move it to the front");
+ }
+
const switchedLevel = document.querySelector(".selected-thinking-level")?.textContent?.trim() ?? "";
await globalThis.composerModelSelectionController!.commitThinkingLevel("low");
await settle();
- await globalThis.composerModelSelectionController!.selectModel(provider, "model-b");
+ const allModels = document.querySelector<HTMLButtonElement>(".composer-menu-root [aria-haspopup=menu]");
+ allModels!.click();
+ await settle();
+ const search = document.querySelector<HTMLInputElement>(".composer-model-search input")!;
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(search, "model-b");
+ search.dispatchEvent(new Event("input", { bubbles: true }));
+ await settle();
+ search.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
+ await settle();
+ const restored = loadRecentModels();
+ if (restored[0]?.modelId !== "model-b") throw new Error("Recent selection must survive local preference reload");
+ useAppStore.setState({ recentModels: restored });
await settle();
return {
model: document.querySelector(".selected-model")?.textContent?.trim() ?? "",
diff --git a/scripts/e2e/fixtures/composer-model-selection-store.ts b/scripts/e2e/fixtures/composer-model-selection-store.ts
index 208c85c89..4f47ff2f6 100644
--- a/scripts/e2e/fixtures/composer-model-selection-store.ts
+++ b/scripts/e2e/fixtures/composer-model-selection-store.ts
@@ -1,8 +1,11 @@
+import { rememberModelInList, saveRecentModels } from "../../../apps/desktop/src/lib/recent-models";
+import type { RecentModel } from "../../../apps/desktop/src/lib/recent-models";
import { useSyncExternalStore } from "react";
import type { ModelInfo, ProviderPublic } from "@pi-desktop/shared";
type StoreState = {
providers: ProviderPublic[];
+ recentModels: RecentModel[];
providerModels: Record<string, ModelInfo[]>;
settings: undefined;
loadProviderModels: (providerId: string) => Promise<void>;
@@ -12,6 +15,7 @@ type StoreState = {
const listeners = new Set<() => void>();
let state: StoreState = {
providers: [],
+ recentModels: [],
providerModels: {},
settings: undefined,
loadProviderModels: async () => {},
@@ -40,4 +44,10 @@ const useAppStore = Object.assign(
},
);
+export function rememberSelectedModel(model: RecentModel) {
+ const recentModels = rememberModelInList(useAppStore.getState().recentModels, model);
+ saveRecentModels(recentModels);
+ useAppStore.setState({ recentModels });
+}
+
export { useAppStore };