Skip to content

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

refactor(settings): extract service catalog, fetch-error message, vendor-accounts hook

vastsa6fbaa610f06d
diff --git a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx b/apps/desktop/src/components/settings/ModelSelectionPanes.tsx
index 3828c2fa5..3cfb24627 100644
--- a/apps/desktop/src/components/settings/ModelSelectionPanes.tsx
+++ b/apps/desktop/src/components/settings/ModelSelectionPanes.tsx
@@ -43,7 +43,7 @@ import {
customModelSeedBinding,
type CustomModelLookupContext,
} from "./model-custom-lookup";
-import { describeModelsFetchError } from "./model-fetch-error";
+import { ModelsFetchErrorMessage } from "./ModelsFetchErrorMessage";
import type { ProviderModelsState } from "./useProviderModels";
import { useModelReorder } from "./useModelReorder";
@@ -996,58 +996,6 @@ export function ModelSelectionPanes({
);
}
-function ModelsFetchErrorMessage({
- error,
- variant,
-}: {
- error?: string;
- variant: "banner" | "placeholder";
-}) {
- const { t } = useTranslation();
- const view = describeModelsFetchError(error);
- let summary = t("settings.modelsFetchFailed");
- switch (view.kind) {
- case "unauthorized":
- summary = t("errors.PROVIDER_UNAUTHORIZED");
- break;
- case "notFound":
- summary = t("settings.modelsFetchNotFound");
- break;
- case "rateLimited":
- summary = t("errors.PROVIDER_RATE_LIMITED");
- break;
- case "timeout":
- summary = t("errors.TIMEOUT");
- break;
- case "network":
- summary = t("errors.NETWORK_ERROR");
- break;
- case "invalidResponse":
- summary = t("settings.modelsFetchInvalidResponse");
- break;
- case "http":
- summary = t("settings.modelsFetchFailedStatus", {
- status: view.summaryParams?.status ?? 0,
- });
- break;
- }
- const className =
- variant === "placeholder"
- ? "provider-models-placeholder is-error"
- : "provider-models-note is-error";
- return (
- <div className={className} role="alert">
- <span className="provider-models-error-summary">{summary}</span>
- {view.detail ? (
- <span className="provider-models-error-detail">{view.detail}</span>
- ) : null}
- {variant === "placeholder" ? (
- <span className="provider-models-error-hint">{t("settings.modelsFetchHint")}</span>
- ) : null}
- </div>
- );
-}
-
type CapabilityToggleProps = {
label: string;
/** What models.dev publishes for this model. */
diff --git a/apps/desktop/src/components/settings/ModelsFetchErrorMessage.tsx b/apps/desktop/src/components/settings/ModelsFetchErrorMessage.tsx
new file mode 100644
index 000000000..5cf2598f5
--- /dev/null
+++ b/apps/desktop/src/components/settings/ModelsFetchErrorMessage.tsx
@@ -0,0 +1,61 @@
+/**
+ * The classified copy for a failed model-list probe (`model-fetch-error.ts`).
+ *
+ * The picker renders it in the empty pane or above a stale list; the service
+ * form reuses it under the key, so every surface says the same thing for the
+ * same failure.
+ */
+import { useTranslation } from "react-i18next";
+import { describeModelsFetchError } from "./model-fetch-error";
+
+export function ModelsFetchErrorMessage({
+ error,
+ variant,
+}: {
+ error?: string;
+ variant: "banner" | "placeholder";
+}) {
+ const { t } = useTranslation();
+ const view = describeModelsFetchError(error);
+ let summary = t("settings.modelsFetchFailed");
+ switch (view.kind) {
+ case "unauthorized":
+ summary = t("errors.PROVIDER_UNAUTHORIZED");
+ break;
+ case "notFound":
+ summary = t("settings.modelsFetchNotFound");
+ break;
+ case "rateLimited":
+ summary = t("errors.PROVIDER_RATE_LIMITED");
+ break;
+ case "timeout":
+ summary = t("errors.TIMEOUT");
+ break;
+ case "network":
+ summary = t("errors.NETWORK_ERROR");
+ break;
+ case "invalidResponse":
+ summary = t("settings.modelsFetchInvalidResponse");
+ break;
+ case "http":
+ summary = t("settings.modelsFetchFailedStatus", {
+ status: view.summaryParams?.status ?? 0,
+ });
+ break;
+ }
+ const className =
+ variant === "placeholder"
+ ? "provider-models-placeholder is-error"
+ : "provider-models-note is-error";
+ return (
+ <div className={className} role="alert">
+ <span className="provider-models-error-summary">{summary}</span>
+ {view.detail ? (
+ <span className="provider-models-error-detail">{view.detail}</span>
+ ) : null}
+ {variant === "placeholder" ? (
+ <span className="provider-models-error-hint">{t("settings.modelsFetchHint")}</span>
+ ) : null}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/components/settings/ServicePicker.tsx b/apps/desktop/src/components/settings/ServicePicker.tsx
index 57541d3a6..e72bdb464 100644
--- a/apps/desktop/src/components/settings/ServicePicker.tsx
+++ b/apps/desktop/src/components/settings/ServicePicker.tsx
@@ -7,26 +7,18 @@
*/
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
-import { NAMED_ENDPOINT_PRESETS } from "@pi-desktop/shared";
import { cx, Input } from "../ui";
import { IconCheck, IconChevronDown, IconSearch } from "../icons";
import { AnchoredMenu } from "./AnchoredMenu";
+import {
+ CUSTOM_SERVICE,
+ customServiceOption,
+ filterServiceOptions,
+ namedServiceOptions,
+ type ServiceOption,
+} from "./service-catalog";
-export const CUSTOM_SERVICE = "custom";
-
-type ServiceOption = {
- id: string;
- label: string;
- haystack: string;
-};
-
-function hostOf(url: string): string {
- try {
- return new URL(url).host;
- } catch {
- return url;
- }
-}
+export { CUSTOM_SERVICE };
export type ServicePickerProps = {
value: string;
@@ -48,31 +40,12 @@ export function ServicePicker({
const [restoreFocus, setRestoreFocus] = useState(true);
const optionRefs = useRef(new Map<string, HTMLButtonElement>());
- const customLabel = t("settings.presetCustomEndpoint");
- const options = useMemo<ServiceOption[]>(() => {
- const custom: ServiceOption = {
- id: CUSTOM_SERVICE,
- label: customLabel,
- haystack: `${customLabel} custom endpoint`.toLowerCase(),
- };
- const named = NAMED_ENDPOINT_PRESETS.map((preset) => {
- const label = t(preset.labelKey);
- const aliases = preset.aliases?.join(" ") ?? "";
- return {
- id: preset.id,
- label,
- haystack:
- `${label} ${preset.name} ${preset.id} ${preset.vendorKey} ${aliases} ${preset.baseUrl} ${hostOf(preset.baseUrl)}`.toLowerCase(),
- };
- });
- return [custom, ...named];
- }, [customLabel, t]);
+ const options = useMemo<ServiceOption[]>(
+ () => [customServiceOption(t), ...namedServiceOptions(t)],
+ [t],
+ );
- const visible = useMemo(() => {
- const needle = query.trim().toLowerCase();
- if (!needle) return options;
- return options.filter((option) => option.haystack.includes(needle));
- }, [options, query]);
+ const visible = useMemo(() => filterServiceOptions(options, query), [options, query]);
const visibleIds = useMemo(() => visible.map((option) => option.id), [visible]);
diff --git a/apps/desktop/src/components/settings/VendorAccountsSection.tsx b/apps/desktop/src/components/settings/VendorAccountsSection.tsx
index 1227f9f79..586fec609 100644
--- a/apps/desktop/src/components/settings/VendorAccountsSection.tsx
+++ b/apps/desktop/src/components/settings/VendorAccountsSection.tsx
@@ -4,15 +4,10 @@
* each account row owns exactly one OAuth provider row and can be removed on
* its own.
*/
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useState } from "react";
import { useTranslation } from "react-i18next";
-import type { OAuthAccount, OAuthVendor, ProviderPublic } from "@pi-desktop/shared";
import { useAppStore } from "../../stores/app-store";
import { api } from "../../lib/api";
-import {
- beginOAuthLogin,
- type OAuthLoginSession,
-} from "../../lib/oauth-login-session";
import { Badge, Button, TooltipButton, cx } from "../ui";
import { IconKey, IconPencil, IconPlug, IconTrash } from "../icons";
import { OAuthLoginDialog } from "./OAuthLoginDialog";
@@ -21,140 +16,37 @@ import {
type VendorAccountForm,
} from "./VendorAccountDialog";
import { VendorPickerDialog } from "./VendorPickerDialog";
-
-/** A login in flight, together with the dialog reporting on it. */
-type ActiveLogin = { vendor: OAuthVendor; session: OAuthLoginSession };
-
-type AccountEntry = {
- vendor: OAuthVendor;
- account: OAuthAccount;
- ordinal: number;
- totalForVendor: number;
-};
-
-function providerIsReady(provider: ProviderPublic, excludedId?: string): boolean {
- return (
- provider.id !== excludedId &&
- provider.enabled &&
- !!provider.defaultModelId &&
- (provider.hasSecret || provider.hasOauth || provider.authKind === "none")
- );
-}
+import { useVendorAccounts, type AccountEntry } from "./useVendorAccounts";
export function VendorAccountsSection() {
const { t } = useTranslation();
const providers = useAppStore((s) => s.providers);
- const settings = useAppStore((s) => s.settings);
- const refreshProviders = useAppStore((s) => s.refreshProviders);
const showToast = useAppStore((s) => s.showToast);
+ const {
+ vendors,
+ accounts,
+ login,
+ busyAccountId,
+ savingAccount,
+ startLogin,
+ finishLogin,
+ closeLogin,
+ removeAccount,
+ saveAccount,
+ } = useVendorAccounts();
- const [vendors, setVendors] = useState<OAuthVendor[] | null>(null);
- const [busyAccount, setBusyAccount] = useState<string | null>(null);
const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);
const [picking, setPicking] = useState(false);
- const [login, setLogin] = useState<ActiveLogin | null>(null);
const [editingAccount, setEditingAccount] = useState<AccountEntry | null>(null);
- const [savingAccount, setSavingAccount] = useState(false);
const [testingAccount, setTestingAccount] = useState<string | null>(null);
- const loadVendors = useCallback(async () => {
- try {
- const result = await api.listOauthVendors();
- setVendors(result.vendors);
- } catch {
- // A runtime without OAuth flows registered simply has no accounts to
- // offer; the section stays hidden rather than showing an error.
- setVendors([]);
- }
- }, []);
-
- useEffect(() => {
- void loadVendors();
- }, [loadVendors]);
-
- // Closing the dialog — done, cancelled, or the whole page going away — stops
- // the renderer listening. Cancelling the attempt itself is the dialog's job.
- useEffect(() => () => login?.session.dispose(), [login]);
-
- const accounts = useMemo<AccountEntry[]>(() => {
- if (!vendors) return [];
- return vendors.flatMap((vendor) => {
- const totalForVendor = vendor.accounts.length;
- return vendor.accounts.map((account, index) => ({
- vendor,
- account,
- ordinal: index + 1,
- totalForVendor,
- }));
- });
- }, [vendors]);
-
- const removeAccount = async (entry: AccountEntry) => {
- const { account, vendor } = entry;
- setConfirmDeleteId(null);
- setBusyAccount(account.providerId);
- try {
- await api.deleteOauthAccount(account.providerId);
-
- // A deleted account cannot remain the global default. Pick the first
- // still-ready service, including an API provider, so the model picker
- // does not point at a deleted row after refresh.
- if (settings?.defaultProviderId === account.providerId) {
- const next = providers.find((provider) =>
- providerIsReady(provider, account.providerId),
- );
- const nextSettings = {
- ...settings,
- defaultProviderId: next?.id ?? "",
- defaultModelId: next?.defaultModelId ?? "",
- };
- await api.setSettings(nextSettings);
- useAppStore.setState({ settings: nextSettings });
- }
- await Promise.all([loadVendors(), refreshProviders()]);
- showToast(t("settings.vendorAccountRemoved", { vendor: vendor.name }), {
- variant: "success",
- });
- } catch (error) {
- showToast(error instanceof Error ? error.message : String(error), {
- variant: "error",
- });
- } finally {
- setBusyAccount(null);
- }
- };
-
- const saveAccount = async (form: VendorAccountForm) => {
+ const saveEditingAccount = async (form: VendorAccountForm) => {
const entry = editingAccount;
const provider = entry
? providers.find((candidate) => candidate.id === entry.account.providerId)
: null;
- if (!entry || !provider || !form.name.trim() || !form.modelId.trim()) return;
- setSavingAccount(true);
- try {
- await api.updateProvider({
- id: provider.id,
- oauthAccountLabel: form.name.trim(),
- defaultModelId: form.modelId.trim(),
- models: form.models,
- headers: form.headers,
- });
- if (settings?.defaultProviderId === provider.id) {
- await api.setSettings({
- ...settings,
- defaultModelId: form.modelId.trim(),
- });
- }
- await Promise.all([loadVendors(), refreshProviders()]);
- setEditingAccount(null);
- showToast(t("settings.vendorAccountUpdated"), { variant: "success" });
- } catch (error) {
- showToast(error instanceof Error ? error.message : String(error), {
- variant: "error",
- });
- } finally {
- setSavingAccount(false);
- }
+ if (!entry || !provider) return;
+ if (await saveAccount(provider, form)) setEditingAccount(null);
};
const testAccount = async (entry: AccountEntry) => {
@@ -187,22 +79,6 @@ export function VendorAccountsSection() {
}
};
- const onLoginDone = useCallback(
- (accountLabel?: string) => {
- const vendorName = login?.vendor.name ?? "";
- setLogin(null);
- void loadVendors();
- void refreshProviders();
- showToast(
- accountLabel
- ? t("settings.vendorSignedInAs", { account: accountLabel })
- : t("settings.vendorSignedIn", { vendor: vendorName }),
- { variant: "success" },
- );
- },
- [login, loadVendors, refreshProviders, showToast, t],
- );
-
// Nothing to offer until the runtime reports at least one OAuth vendor.
if (!vendors || vendors.length === 0) return null;
@@ -251,7 +127,7 @@ export function VendorAccountsSection() {
? ` · ${t("settings.vendorAccountNumber", { number: entry.ordinal })}`
: "";
const confirming = confirmDeleteId === account.providerId;
- const busy = busyAccount === account.providerId;
+ const busy = busyAccountId === account.providerId;
const testing = testingAccount === account.providerId;
const rowBusy = busy || testing;
return (
@@ -317,7 +193,10 @@ export function VendorAccountsSection() {
className="provider-delete-confirm"
disabled={rowBusy}
onBlur={() => setConfirmDeleteId(null)}
- onClick={() => void removeAccount(entry)}
+ onClick={() => {
+ setConfirmDeleteId(null);
+ void removeAccount(entry);
+ }}
>
{t("settings.deleteConfirm")}
</button>
@@ -348,10 +227,7 @@ export function VendorAccountsSection() {
setPicking(false);
// Started here, not in the dialog: a click happens once, where
// StrictMode would run a mount effect twice and open two browsers.
- setLogin({
- vendor,
- session: beginOAuthLogin({ api, vendorId: vendor.vendorId }),
- });
+ startLogin(vendor);
}}
onClose={() => setPicking(false)}
/>
@@ -367,7 +243,7 @@ export function VendorAccountsSection() {
}
saving={savingAccount}
onClose={() => setEditingAccount(null)}
- onSave={(form) => void saveAccount(form)}
+ onSave={(form) => void saveEditingAccount(form)}
/>
) : null}
@@ -375,11 +251,8 @@ export function VendorAccountsSection() {
<OAuthLoginDialog
vendor={login.vendor}
session={login.session}
- onDone={onLoginDone}
- onClose={() => {
- setLogin(null);
- void loadVendors();
- }}
+ onDone={finishLogin}
+ onClose={closeLogin}
/>
) : null}
</section>
diff --git a/apps/desktop/src/components/settings/service-catalog.ts b/apps/desktop/src/components/settings/service-catalog.ts
new file mode 100644
index 000000000..f853b1a5c
--- /dev/null
+++ b/apps/desktop/src/components/settings/service-catalog.ts
@@ -0,0 +1,67 @@
+/**
+ * The services a new AI service row can start from, and the search over them.
+ *
+ * Filtering never talks to the host. The haystack covers the localized label,
+ * the preset's canonical name, id, vendor key, aliases, base URL and host, so
+ * "kimi", "moonshot" and "api.moonshot.cn" all land on the same entry.
+ */
+import { NAMED_ENDPOINT_PRESETS, type NamedEndpointPreset } from "@pi-desktop/shared";
+
+export const CUSTOM_SERVICE = "custom";
+
+type Translate = (key: string) => string;
+
+export type ServiceOption = {
+ id: string;
+ label: string;
+ /** Endpoint host shown under the label; empty for the custom endpoint. */
+ host: string;
+ haystack: string;
+};
+
+export function hostOf(url: string): string {
+ try {
+ return new URL(url).host;
+ } catch {
+ return url;
+ }
+}
+
+function presetOption(preset: NamedEndpointPreset, translate: Translate): ServiceOption {
+ const label = translate(preset.labelKey);
+ const host = hostOf(preset.baseUrl);
+ const aliases = preset.aliases?.join(" ") ?? "";
+ return {
+ id: preset.id,
+ label,
+ host,
+ haystack:
+ `${label} ${preset.name} ${preset.id} ${preset.vendorKey} ${aliases} ${preset.baseUrl} ${host}`.toLowerCase(),
+ };
+}
+
+/** Every named endpoint preset, in the order the shared table lists them. */
+export function namedServiceOptions(translate: Translate): ServiceOption[] {
+ return NAMED_ENDPOINT_PRESETS.map((preset) => presetOption(preset, translate));
+}
+
+/** Any OpenAI- or Anthropic-compatible address the presets do not cover. */
+export function customServiceOption(translate: Translate): ServiceOption {
+ const label = translate("settings.presetCustomEndpoint");
+ return {
+ id: CUSTOM_SERVICE,
+ label,
+ host: "",
+ haystack: `${label} custom endpoint`.toLowerCase(),
+ };
+}
+
+/** Case-insensitive substring match; an empty query keeps every option. */
+export function filterServiceOptions<T extends { haystack: string }>(
+ options: readonly T[],
+ query: string,
+): T[] {
+ const needle = query.trim().toLowerCase();
+ if (!needle) return [...options];
+ return options.filter((option) => option.haystack.includes(needle));
+}
diff --git a/apps/desktop/src/components/settings/useVendorAccounts.ts b/apps/desktop/src/components/settings/useVendorAccounts.ts
new file mode 100644
index 000000000..78cbaa43f
--- /dev/null
+++ b/apps/desktop/src/components/settings/useVendorAccounts.ts
@@ -0,0 +1,197 @@
+/**
+ * Vendor (OAuth) accounts for the model settings page (ADR 0098).
+ *
+ * Owns what an account row needs beyond its provider row: the vendor list the
+ * runtime reports, the login attempt in flight, and the two writes that must
+ * keep the app default consistent — removing an account and saving its edits.
+ * Rendering stays with the caller.
+ */
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type { OAuthAccount, OAuthVendor, ProviderPublic } from "@pi-desktop/shared";
+import { useAppStore } from "../../stores/app-store";
+import { api } from "../../lib/api";
+import {
+ beginOAuthLogin,
+ type OAuthLoginSession,
+} from "../../lib/oauth-login-session";
+import type { VendorAccountForm } from "./VendorAccountDialog";
+
+/** A login in flight, together with the dialog reporting on it. */
+export type ActiveLogin = { vendor: OAuthVendor; session: OAuthLoginSession };
+
+export type AccountEntry = {
+ vendor: OAuthVendor;
+ account: OAuthAccount;
+ /** 1-based position among this vendor's accounts. */
+ ordinal: number;
+ totalForVendor: number;
+};
+
+function providerIsReady(provider: ProviderPublic, excludedId?: string): boolean {
+ return (
+ provider.id !== excludedId &&
+ provider.enabled &&
+ !!provider.defaultModelId &&
+ (provider.hasSecret || provider.hasOauth || provider.authKind === "none")
+ );
+}
+
+export function useVendorAccounts() {
+ const { t } = useTranslation();
+ const providers = useAppStore((s) => s.providers);
+ const settings = useAppStore((s) => s.settings);
+ const refreshProviders = useAppStore((s) => s.refreshProviders);
+ const showToast = useAppStore((s) => s.showToast);
+
+ const [vendors, setVendors] = useState<OAuthVendor[] | null>(null);
+ const [login, setLogin] = useState<ActiveLogin | null>(null);
+ const [busyAccountId, setBusyAccountId] = useState<string | null>(null);
+ const [savingAccount, setSavingAccount] = useState(false);
+
+ const loadVendors = useCallback(async () => {
+ try {
+ const result = await api.listOauthVendors();
+ setVendors(result.vendors);
+ } catch {
+ // A runtime without OAuth flows registered simply has no accounts to
+ // offer; the accounts stay hidden rather than showing an error.
+ setVendors([]);
+ }
+ }, []);
+
+ useEffect(() => {
+ void loadVendors();
+ }, [loadVendors]);
+
+ // Closing the dialog — done, cancelled, or the whole page going away — stops
+ // the renderer listening. Cancelling the attempt itself is the dialog's job.
+ useEffect(() => () => login?.session.dispose(), [login]);
+
+ const accounts = useMemo<AccountEntry[]>(() => {
+ if (!vendors) return [];
+ return vendors.flatMap((vendor) => {
+ const totalForVendor = vendor.accounts.length;
+ return vendor.accounts.map((account, index) => ({
+ vendor,
+ account,
+ ordinal: index + 1,
+ totalForVendor,
+ }));
+ });
+ }, [vendors]);
+
+ /**
+ * Started from the caller's click handler, never from an effect: a click
+ * happens once, where StrictMode would run a mount effect twice and open two
+ * browsers.
+ */
+ const startLogin = (vendor: OAuthVendor) => {
+ setLogin({
+ vendor,
+ session: beginOAuthLogin({ api, vendorId: vendor.vendorId }),
+ });
+ };
+
+ const finishLogin = useCallback(
+ (accountLabel?: string) => {
+ const vendorName = login?.vendor.name ?? "";
+ setLogin(null);
+ void loadVendors();
+ void refreshProviders();
+ showToast(
+ accountLabel
+ ? t("settings.vendorSignedInAs", { account: accountLabel })
+ : t("settings.vendorSignedIn", { vendor: vendorName }),
+ { variant: "success" },
+ );
+ },
+ [login, loadVendors, refreshProviders, showToast, t],
+ );
+
+ const closeLogin = () => {
+ setLogin(null);
+ void loadVendors();
+ };
+
+ const removeAccount = async (entry: AccountEntry) => {
+ const { account, vendor } = entry;
+ setBusyAccountId(account.providerId);
+ try {
+ await api.deleteOauthAccount(account.providerId);
+
+ // A deleted account cannot remain the global default. Pick the first
+ // still-ready service, including an API provider, so the model picker
+ // does not point at a deleted row after refresh.
+ if (settings?.defaultProviderId === account.providerId) {
+ const next = providers.find((provider) =>
+ providerIsReady(provider, account.providerId),
+ );
+ const nextSettings = {
+ ...settings,
+ defaultProviderId: next?.id ?? "",
+ defaultModelId: next?.defaultModelId ?? "",
+ };
+ await api.setSettings(nextSettings);
+ useAppStore.setState({ settings: nextSettings });
+ }
+ await Promise.all([loadVendors(), refreshProviders()]);
+ showToast(t("settings.vendorAccountRemoved", { vendor: vendor.name }), {
+ variant: "success",
+ });
+ } catch (error) {
+ showToast(error instanceof Error ? error.message : String(error), {
+ variant: "error",
+ });
+ } finally {
+ setBusyAccountId(null);
+ }
+ };
+
+ /** Resolves true once the account is saved, so the caller can close its editor. */
+ const saveAccount = async (
+ provider: ProviderPublic,
+ form: VendorAccountForm,
+ ): Promise<boolean> => {
+ if (!form.name.trim() || !form.modelId.trim()) return false;
+ setSavingAccount(true);
+ try {
+ await api.updateProvider({
+ id: provider.id,
+ oauthAccountLabel: form.name.trim(),
+ defaultModelId: form.modelId.trim(),
+ models: form.models,
+ headers: form.headers,
+ });
+ if (settings?.defaultProviderId === provider.id) {
+ await api.setSettings({
+ ...settings,
+ defaultModelId: form.modelId.trim(),
+ });
+ }
+ await Promise.all([loadVendors(), refreshProviders()]);
+ showToast(t("settings.vendorAccountUpdated"), { variant: "success" });
+ return true;
+ } catch (error) {
+ showToast(error instanceof Error ? error.message : String(error), {
+ variant: "error",
+ });
+ return false;
+ } finally {
+ setSavingAccount(false);
+ }
+ };
+
+ return {
+ vendors,
+ accounts,
+ login,
+ busyAccountId,
+ savingAccount,
+ startLogin,
+ finishLogin,
+ closeLogin,
+ removeAccount,
+ saveAccount,
+ };
+}
diff --git a/apps/desktop/test/provider-form-layout.test.mjs b/apps/desktop/test/provider-form-layout.test.mjs
index bdc2230da..3de94f9bf 100644
--- a/apps/desktop/test/provider-form-layout.test.mjs
+++ b/apps/desktop/test/provider-form-layout.test.mjs
@@ -19,6 +19,7 @@ const headerEditorSource = await read("../src/components/settings/ProviderHeader
const vendorDialogSource = await read("../src/components/settings/VendorAccountDialog.tsx");
// The panes themselves live in the picker both dialogs render (D269).
const pickerSource = await read("../src/components/settings/ModelSelectionPanes.tsx");
+const fetchErrorSource = await read("../src/components/settings/ModelsFetchErrorMessage.tsx");
const styles = await loadStyles();
/** Declaration block for exactly one selector, so matches cannot span rules. */
@@ -114,7 +115,7 @@ test("custom Name and Base URL sit on one row without helper copy", () => {
});
test("a failed model list uses a classified error, not a raw dump plus empty copy", () => {
- assert.match(pickerSource, /describeModelsFetchError/);
+ assert.match(fetchErrorSource, /describeModelsFetchError/);
assert.match(pickerSource, /ModelsFetchErrorMessage/);
assert.match(pickerSource, /variant="placeholder"/);
assert.match(pickerSource, /variant="banner"/);
diff --git a/apps/desktop/test/provider-model-config.test.mjs b/apps/desktop/test/provider-model-config.test.mjs
index 8aae8f2b4..5e52d3bbe 100644
--- a/apps/desktop/test/provider-model-config.test.mjs
+++ b/apps/desktop/test/provider-model-config.test.mjs
@@ -20,7 +20,7 @@ const pageSource = await read("../src/components/settings/ModelConfigPage.tsx");
const vendorDialogSource = await read("../src/components/settings/VendorAccountDialog.tsx");
const pickerSource = await read("../src/components/settings/ModelSelectionPanes.tsx");
const filterSource = await read("../src/components/settings/model-chosen-filter.ts");
-const vendorAccountsSource = await read("../src/components/settings/VendorAccountsSection.tsx");
+const vendorAccountsSource = await read("../src/components/settings/useVendorAccounts.ts");
const apiSource = await read("../src/lib/api.ts");
const catalogContractSource = await read("../../../packages/shared/src/model-catalog.ts");
const styles = await loadStyles();
diff --git a/apps/desktop/test/service-catalog.test.mjs b/apps/desktop/test/service-catalog.test.mjs
new file mode 100644
index 000000000..f206e98f2
--- /dev/null
+++ b/apps/desktop/test/service-catalog.test.mjs
@@ -0,0 +1,71 @@
+/**
+ * Behavior of the service search the add dialog offers (D311): every named
+ * preset is listed once, and a query matches the localized label, canonical
+ * name, id, vendor key, aliases, base URL or host — never an IPC round trip.
+ */
+import assert from "node:assert/strict";
+import test from "node:test";
+import { NAMED_ENDPOINT_PRESETS } from "@pi-desktop/shared";
+import {
+ CUSTOM_SERVICE,
+ customServiceOption,
+ filterServiceOptions,
+ hostOf,
+ namedServiceOptions,
+} from "../src/components/settings/service-catalog.ts";
+
+// Stands in for i18next with two localized labels, so a label-only match is
+// distinguishable from a match on the canonical English name.
+const labels = {
+ "settings.presetMoonshotCn": "月之暗面",
+ "settings.presetCustomEndpoint": "自定义端点",
+};
+const translate = (key) => labels[key] ?? key;
+const options = [customServiceOption(translate), ...namedServiceOptions(translate)];
+const ids = (query) => filterServiceOptions(options, query).map((option) => option.id);
+
+test("every named preset is offered once, in the shared table's order", () => {
+ assert.deepEqual(
+ namedServiceOptions(translate).map((option) => option.id),
+ NAMED_ENDPOINT_PRESETS.map((preset) => preset.id),
+ );
+ const openai = namedServiceOptions(translate).find((option) => option.id === "openai");
+ assert.equal(openai?.host, "api.openai.com");
+});
+
+test("an empty or blank query keeps every option", () => {
+ assert.deepEqual(ids(""), options.map((option) => option.id));
+ assert.deepEqual(ids(" "), options.map((option) => option.id));
+});
+
+test("a query matches the localized label, canonical name and aliases", () => {
+ assert.deepEqual(ids("月之暗面"), ["moonshotai-cn"]);
+ assert.ok(ids("Moonshot").includes("moonshotai-cn"));
+ assert.ok(ids("gemini").includes("google"));
+ assert.ok(ids("dashscope").includes("alibaba-cn"));
+ assert.ok(ids("KIMI").includes("kimi-for-coding"));
+});
+
+test("a query matches the vendor key and the endpoint host", () => {
+ // `opencode-go` appears only as the vendor key; the id uses an underscore.
+ assert.deepEqual(ids("opencode-go"), ["opencode_go"]);
+ assert.deepEqual(ids("api.moonshot.cn"), ["moonshotai-cn"]);
+ assert.deepEqual(ids("open.bigmodel.cn"), ["zhipuai", "zhipuai-coding-plan"]);
+});
+
+test("the custom endpoint is searchable by its label and by 'custom'", () => {
+ const custom = customServiceOption(translate);
+ assert.equal(custom.id, CUSTOM_SERVICE);
+ assert.equal(custom.host, "");
+ assert.deepEqual(ids("自定义"), [CUSTOM_SERVICE]);
+ assert.deepEqual(ids("custom endpoint"), [CUSTOM_SERVICE]);
+});
+
+test("an unmatched query yields no options", () => {
+ assert.deepEqual(ids("no-such-service-anywhere"), []);
+});
+
+test("hostOf keeps unparseable input as-is", () => {
+ assert.equal(hostOf("https://api.openai.com/v1"), "api.openai.com");
+ assert.equal(hostOf("not a url"), "not a url");
+});
diff --git a/apps/desktop/test/service-picker.test.mjs b/apps/desktop/test/service-picker.test.mjs
index 14aafe882..81cca9d3e 100644
--- a/apps/desktop/test/service-picker.test.mjs
+++ b/apps/desktop/test/service-picker.test.mjs
@@ -7,6 +7,7 @@ const read = (rel) => readFile(new URL(rel, import.meta.url), "utf8");
const setupSource = await read("../src/components/settings/ProviderSetupDialog.tsx");
const pickerSource = await read("../src/components/settings/ServicePicker.tsx");
+const catalogSource = await read("../src/components/settings/service-catalog.ts");
const hookSource = await read("../src/components/settings/useProviderModels.ts");
const menuSource = await read("../src/components/settings/AnchoredMenu.tsx");
const styles = await loadStyles();
@@ -17,11 +18,11 @@ test("the service control is a searchable anchored menu, not a native select", (
assert.doesNotMatch(setupSource, /<optgroup/);
assert.match(pickerSource, /<AnchoredMenu/);
assert.match(pickerSource, /settings\.searchService/);
- assert.match(pickerSource, /haystack\.includes\(needle\)/);
- assert.match(pickerSource, /preset\.aliases/);
- assert.match(pickerSource, /hostOf\(preset\.baseUrl\)/);
+ // Matching itself is covered behaviorally in service-catalog.test.mjs.
+ assert.match(pickerSource, /filterServiceOptions\(options, query\)/);
// Filtering stays in the renderer; a keystroke must not IPC.
assert.doesNotMatch(pickerSource, /api\./);
+ assert.doesNotMatch(catalogSource, /\bapi\.\w+\(/);
});
test("the service menu portals above the dialog overlay and hides until measured", () => {
@@ -40,17 +41,12 @@ test("the service menu portals above the dialog overlay and hides until measured
});
test("the service list is a flat vendor menu with custom first", () => {
- assert.match(pickerSource, /id: CUSTOM_SERVICE/);
- assert.match(pickerSource, /NAMED_ENDPOINT_PRESETS\.map/);
+ assert.match(pickerSource, /\[customServiceOption\(t\), \.\.\.namedServiceOptions\(t\)\]/);
assert.match(pickerSource, /settings\.noServiceMatches/);
assert.match(pickerSource, /role="option"/);
assert.doesNotMatch(pickerSource, /presetGroupInternational|presetGroupChina/);
assert.doesNotMatch(pickerSource, /NAMED_PRESET_GROUPS/);
- assert.ok(
- pickerSource.indexOf("id: CUSTOM_SERVICE") <
- pickerSource.indexOf("NAMED_ENDPOINT_PRESETS.map"),
- "custom should be listed before named vendors",
- );
+ assert.doesNotMatch(catalogSource, /NAMED_PRESET_GROUPS/);
});
test("named add-path discovery waits for a key and does not flash loading", () => {
diff --git a/apps/desktop/test/settings-general.test.mjs b/apps/desktop/test/settings-general.test.mjs
index 18c8eb216..a63750974 100644
--- a/apps/desktop/test/settings-general.test.mjs
+++ b/apps/desktop/test/settings-general.test.mjs
@@ -38,6 +38,11 @@ const vendorAccountsSource = await readFile(
new URL("../src/components/settings/VendorAccountsSection.tsx", import.meta.url),
"utf8",
);
+// Account lifecycle (remove with default repair, save) lives in the hook.
+const vendorAccountsHookSource = await readFile(
+ new URL("../src/components/settings/useVendorAccounts.ts", import.meta.url),
+ "utf8",
+);
const vendorAccountDialogSource = await readFile(
new URL("../src/components/settings/VendorAccountDialog.tsx", import.meta.url),
"utf8",
@@ -283,11 +288,11 @@ test("model configuration separates AI services from independently removable ven
);
assert.doesNotMatch(providersSource, /provider-config-hero/);
assert.doesNotMatch(providersSource, /settings-section-subtitle/);
- assert.match(vendorAccountsSource, /api\.deleteOauthAccount\(account\.providerId\)/);
- assert.match(vendorAccountsSource, /api\.updateProvider\(/);
- assert.match(vendorAccountsSource, /oauthAccountLabel: form\.name\.trim\(\)/);
- assert.match(vendorAccountsSource, /defaultModelId: form\.modelId\.trim\(\)/);
- assert.match(vendorAccountsSource, /models: form\.models/);
+ assert.match(vendorAccountsHookSource, /api\.deleteOauthAccount\(account\.providerId\)/);
+ assert.match(vendorAccountsHookSource, /api\.updateProvider\(/);
+ assert.match(vendorAccountsHookSource, /oauthAccountLabel: form\.name\.trim\(\)/);
+ assert.match(vendorAccountsHookSource, /defaultModelId: form\.modelId\.trim\(\)/);
+ assert.match(vendorAccountsHookSource, /models: form\.models/);
assert.match(vendorAccountsSource, /api\.testProvider\(provider\.id\)/);
assert.match(vendorAccountsSource, /VendorAccountDialog/);
assert.match(
@@ -305,9 +310,9 @@ test("model configuration separates AI services from independently removable ven
assert.match(vendorAccountDialogSource, /useProviderModels/);
assert.match(vendorAccountDialogSource, /<ModelSelectionPanes/);
assert.match(vendorAccountDialogSource, /modelId: persisted\[0\]\.id/);
- assert.match(vendorAccountsSource, /providerIsReady/);
- assert.match(vendorAccountsSource, /defaultProviderId: next\?\.id \?\? ""/);
- assert.match(vendorAccountsSource, /useAppStore\.setState\(\{ settings: nextSettings \}\)/);
+ assert.match(vendorAccountsHookSource, /providerIsReady/);
+ assert.match(vendorAccountsHookSource, /defaultProviderId: next\?\.id \?\? ""/);
+ assert.match(vendorAccountsHookSource, /useAppStore\.setState\(\{ settings: nextSettings \}\)/);
assert.match(vendorPickerSource, /existing accounts do not disable a vendor/);
assert.match(vendorPickerSource, /vendors\.map/);
});