From da5f06fa40f06efc38432be1b48e328df90e0504 Mon Sep 17 00:00:00 2001 From: Ivan Malison Date: Sat, 1 Aug 2026 17:09:59 -0700 Subject: [PATCH 001/203] Add UI and CLI for creating provider accounts Multiple profiles extending the same provider have been supported in config.json for a while, but the only way to create one was editing the file by hand. The daemon already accepted full profile writes over set_daemon_config, so this is client surface only. App: the provider row actions menu gains "Add account" for built-in providers, opening a form for label, provider id, description, and environment variables. The glossary reserves "profile" for HostProfile, so the UI says account. CLI: paseo provider add/rm, with client-side validation mirroring ProviderOverridesSchema so errors name the offending flag instead of arriving from the daemon. provider ls gains a SOURCE column. Co-Authored-By: Claude Opus 5 --- docs/custom-providers.md | 6 + .../browser/provider-account-create.spec.ts | 95 +++++ .../app/e2e/browser/provider-removal.spec.ts | 9 +- packages/app/e2e/support/helpers/settings.ts | 38 ++ .../src/components/provider-account-sheet.tsx | 369 ++++++++++++++++++ packages/app/src/i18n/resources/ar.ts | 33 ++ packages/app/src/i18n/resources/en.ts | 33 ++ packages/app/src/i18n/resources/es.ts | 33 ++ packages/app/src/i18n/resources/fr.ts | 34 ++ packages/app/src/i18n/resources/ja.ts | 33 ++ packages/app/src/i18n/resources/pt-BR.ts | 33 ++ packages/app/src/i18n/resources/ru.ts | 33 ++ packages/app/src/i18n/resources/zh-CN.ts | 33 ++ .../provider-account-form-model.test.ts | 167 ++++++++ .../provider-account-form-model.ts | 305 +++++++++++++++ .../use-provider-account-form-model.ts | 21 + .../screens/settings/providers-section.tsx | 114 +++++- .../cli/src/commands/provider/add.test.ts | 81 ++++ packages/cli/src/commands/provider/add.ts | 175 +++++++++ packages/cli/src/commands/provider/index.ts | 40 +- packages/cli/src/commands/provider/ls.ts | 4 + packages/cli/src/commands/provider/rm.ts | 65 +++ packages/cli/src/commands/provider/shared.ts | 13 + packages/cli/tests/15-provider.test.ts | 82 +++- 24 files changed, 1833 insertions(+), 16 deletions(-) create mode 100644 packages/app/e2e/browser/provider-account-create.spec.ts create mode 100644 packages/app/src/components/provider-account-sheet.tsx create mode 100644 packages/app/src/provider-accounts/provider-account-form-model.test.ts create mode 100644 packages/app/src/provider-accounts/provider-account-form-model.ts create mode 100644 packages/app/src/provider-accounts/use-provider-account-form-model.ts create mode 100644 packages/cli/src/commands/provider/add.test.ts create mode 100644 packages/cli/src/commands/provider/add.ts create mode 100644 packages/cli/src/commands/provider/rm.ts create mode 100644 packages/cli/src/commands/provider/shared.ts diff --git a/docs/custom-providers.md b/docs/custom-providers.md index 1f872b9d1be..f8b5b0a3427 100644 --- a/docs/custom-providers.md +++ b/docs/custom-providers.md @@ -261,6 +261,12 @@ You can create multiple entries that extend the same built-in provider. Each get "Profile" here means a provider alias, and it is not an **Agent profile** — that is a named bundle of provider, model, mode, thinking option and features, stored under `daemon.agentProfiles`. See [glossary.md](glossary.md) for all four senses of the word. +Three ways to create one, all writing the same `config.json` entry: + +- **App** — Settings > Providers, the actions menu on a built-in provider row > Add account. +- **CLI** — `paseo provider add claude-work --extends claude --label "Claude (Work)" --env ANTHROPIC_API_KEY=sk-ant-...`, and `paseo provider rm claude-work` to delete it. +- **By hand** — edit `config.json` as below. + Example: two different Anthropic accounts as separate profiles: ```json diff --git a/packages/app/e2e/browser/provider-account-create.spec.ts b/packages/app/e2e/browser/provider-account-create.spec.ts new file mode 100644 index 00000000000..6f9de4948c0 --- /dev/null +++ b/packages/app/e2e/browser/provider-account-create.spec.ts @@ -0,0 +1,95 @@ +import { expect, test } from "../support/fixtures"; +import { gotoAppShell, openSettings } from "../support/helpers/app"; +import { connectDaemonClient } from "../support/helpers/daemon-client-loader"; +import { getServerId } from "../support/helpers/server-id"; +import { + expectProviderInstalledInSettings, + fillProviderAccountForm, + openProviderAccountForm, + openSettingsHost, + openSettingsHostSection, + submitProviderAccountForm, +} from "../support/helpers/settings"; + +const BASE_PROVIDER_ID = "claude"; +const ACCOUNT = { + id: "claude-work", + label: "Claude (Work)", +} as const; + +interface ProviderAccountDaemonClient { + connect(): Promise; + close(): Promise; + patchDaemonConfig(config: { removeProviders?: string[] }): Promise; + getDaemonConfig(): Promise<{ + config: { + providers?: Record< + string, + { extends?: string; label?: string; description?: string; env?: Record } + >; + }; + }>; +} + +test.describe("provider accounts", () => { + test("creates a second account for a builtin provider", async ({ page }) => { + test.setTimeout(120_000); + const client = await connectDaemonClient({ + clientIdPrefix: "provider-account-e2e", + }); + + try { + await client.patchDaemonConfig({ removeProviders: [ACCOUNT.id] }).catch(() => undefined); + + await gotoAppShell(page); + await openSettings(page); + await openSettingsHost(page, getServerId()); + await openSettingsHostSection(page, getServerId(), "providers"); + + await openProviderAccountForm(page, BASE_PROVIDER_ID); + + // The id is derived from the label until it is edited by hand. + await page.getByTestId("provider-account-label-input").fill(ACCOUNT.label); + await expect(page.getByTestId("provider-account-id-input")).toHaveValue(ACCOUNT.id); + + // A reserved id is rejected inline. + await page.getByTestId("provider-account-id-input").fill(BASE_PROVIDER_ID); + await expect(page.getByTestId("provider-account-id-error")).toBeVisible(); + await page.getByTestId("provider-account-id-input").fill(ACCOUNT.id); + await expect(page.getByTestId("provider-account-id-error")).toHaveCount(0); + + await fillProviderAccountForm(page, { + label: ACCOUNT.label, + providerId: ACCOUNT.id, + description: "Work account", + env: [{ key: "ANTHROPIC_API_KEY", value: "sk-e2e-test" }], + }); + await submitProviderAccountForm(page); + + await expect(page.getByTestId("provider-account-sheet")).toHaveCount(0); + await expectProviderInstalledInSettings(page, ACCOUNT.label); + + await expect + .poll(async () => { + const { config } = await client.getDaemonConfig(); + const entry = config.providers?.[ACCOUNT.id]; + if (!entry) return null; + return { + extends: entry.extends, + label: entry.label, + description: entry.description, + env: entry.env, + }; + }) + .toEqual({ + extends: BASE_PROVIDER_ID, + label: ACCOUNT.label, + description: "Work account", + env: { ANTHROPIC_API_KEY: "sk-e2e-test" }, + }); + } finally { + await client.patchDaemonConfig({ removeProviders: [ACCOUNT.id] }).catch(() => undefined); + await client.close().catch(() => undefined); + } + }); +}); diff --git a/packages/app/e2e/browser/provider-removal.spec.ts b/packages/app/e2e/browser/provider-removal.spec.ts index 7e17a1fbe01..8505a606f25 100644 --- a/packages/app/e2e/browser/provider-removal.spec.ts +++ b/packages/app/e2e/browser/provider-removal.spec.ts @@ -71,7 +71,14 @@ test.describe("provider removal", () => { await openSettingsHost(page, getServerId()); await openSettingsHostSection(page, getServerId(), "providers"); - await expect(page.getByTestId("provider-actions-claude")).toHaveCount(0); + // Builtin providers get an actions menu for adding accounts, but they can + // never be removed. + await page.getByTestId("provider-actions-claude").click(); + await expect(page.getByTestId("provider-add-account-claude")).toBeVisible(); + await expect(page.getByTestId("provider-remove-claude")).toHaveCount(0); + await page.keyboard.press("Escape"); + await expect(page.getByTestId("provider-add-account-claude")).toHaveCount(0); + await openAddProviderArea(page); await installAcpCatalogProvider(page, CUSTOM_PROVIDER.name); await expectProviderInstalledInSettings(page, CUSTOM_PROVIDER.name); diff --git a/packages/app/e2e/support/helpers/settings.ts b/packages/app/e2e/support/helpers/settings.ts index ecfa2a4b094..caf6242b19b 100644 --- a/packages/app/e2e/support/helpers/settings.ts +++ b/packages/app/e2e/support/helpers/settings.ts @@ -373,6 +373,44 @@ export async function installAcpCatalogProvider(page: Page, providerName: string await page.getByRole("button", { name: "Add", exact: true }).click(); } +export interface ProviderAccountFormInput { + label: string; + providerId?: string; + description?: string; + env?: { key: string; value: string }[]; +} + +export async function openProviderAccountForm(page: Page, providerId: string): Promise { + await page.getByTestId(`provider-actions-${providerId}`).click(); + await page.getByTestId(`provider-add-account-${providerId}`).click(); + await expect(page.getByTestId("provider-account-sheet")).toBeVisible(); +} + +export async function fillProviderAccountForm( + page: Page, + input: ProviderAccountFormInput, +): Promise { + await page.getByTestId("provider-account-label-input").fill(input.label); + if (input.providerId !== undefined) { + await page.getByTestId("provider-account-id-input").fill(input.providerId); + } + if (input.description !== undefined) { + await page.getByTestId("provider-account-description-input").fill(input.description); + } + const env = input.env ?? []; + for (const [index, variable] of env.entries()) { + if (index > 0) { + await page.getByTestId("provider-account-env-add").click(); + } + await page.getByTestId(`provider-account-env-key-${index}`).fill(variable.key); + await page.getByTestId(`provider-account-env-value-${index}`).fill(variable.value); + } +} + +export async function submitProviderAccountForm(page: Page): Promise { + await page.getByTestId("provider-account-submit").click(); +} + export async function expectProviderInstalledInSettings( page: Page, providerName: string, diff --git a/packages/app/src/components/provider-account-sheet.tsx b/packages/app/src/components/provider-account-sheet.tsx new file mode 100644 index 00000000000..b042764eb79 --- /dev/null +++ b/packages/app/src/components/provider-account-sheet.tsx @@ -0,0 +1,369 @@ +import { useCallback, useMemo, useSyncExternalStore, type ReactElement } from "react"; +import { useTranslation } from "react-i18next"; +import { Pressable, Text, View } from "react-native"; +import { StyleSheet, withUnistyles } from "react-native-unistyles"; +import { Plus, X } from "lucide-react-native"; +import type { MutableDaemonConfigPatch } from "@getpaseo/protocol/messages"; +import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet"; +import { Button } from "@/components/ui/button"; +import type { FieldControlSize } from "@/components/ui/control-geometry"; +import { Field, FormTextInput } from "@/components/ui/form-field"; +import { useIsCompactFormFactor } from "@/constants/layout"; +import { useProviderAccountFormModel } from "@/provider-accounts/use-provider-account-form-model"; +import type { + ProviderAccountEnvRow, + ProviderAccountFormModel, + ProviderAccountFormState, +} from "@/provider-accounts/provider-account-form-model"; +import type { Theme } from "@/styles/theme"; + +const foregroundMutedColorMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted }); +const ThemedX = withUnistyles(X, foregroundMutedColorMapping); +const ThemedPlus = withUnistyles(Plus, foregroundMutedColorMapping); +const ADD_VARIABLE_ICON = ; + +export interface ProviderAccountCreateInput { + providerId: string; + patch: MutableDaemonConfigPatch; +} + +export interface ProviderAccountSheetProps { + visible: boolean; + baseProviderId: string; + baseProviderLabel: string; + existingProviderIds: readonly string[]; + onClose: () => void; + /** Resolves true when the account was written; the sheet then closes. */ + onCreate: (input: ProviderAccountCreateInput) => Promise; +} + +export function ProviderAccountSheet(props: ProviderAccountSheetProps): ReactElement | null { + if (!props.visible) return null; + return ; +} + +function OpenProviderAccountSheet({ + visible, + baseProviderId, + baseProviderLabel, + existingProviderIds, + onClose, + onCreate, +}: ProviderAccountSheetProps): ReactElement { + const { t } = useTranslation(); + const controlSize: FieldControlSize = useIsCompactFormFactor() ? "md" : "sm"; + const snapshot = useMemo( + () => ({ baseProviderId, baseProviderLabel, existingProviderIds }), + [baseProviderId, baseProviderLabel, existingProviderIds], + ); + const model = useProviderAccountFormModel(snapshot); + const state = useSyncExternalStore(model.subscribe, model.getState, model.getState); + + const handleSubmit = useCallback(async () => { + if (state.isSubmitting) return; + model.markSubmitAttempted(); + const patch = model.buildPatch(); + if (!patch) return; + + model.setSubmitting(true); + try { + const created = await onCreate({ providerId: state.providerId.trim(), patch }); + if (created) { + onClose(); + return; + } + } finally { + model.setSubmitting(false); + } + }, [model, onClose, onCreate, state.isSubmitting, state.providerId]); + + const handleSubmitPress = useCallback(() => { + void handleSubmit(); + }, [handleSubmit]); + + const header = useMemo( + () => ({ title: t("settings.providers.account.title", { provider: baseProviderLabel }) }), + [baseProviderLabel, t], + ); + + const footer = useMemo( + () => ( + + + + + ), + [handleSubmitPress, onClose, state.isSubmitting, t], + ); + + return ( + + + + + + + + + + + + + + + + {state.envRows.map((row, index) => ( + + ))} + + + + + ); +} + +type Translate = ReturnType["t"]; + +function resolveProviderIdError(state: ProviderAccountFormState, t: Translate): string | null { + switch (state.providerIdError) { + case "required": + return t("settings.providers.account.errors.idRequired"); + case "invalid": + return t("settings.providers.account.errors.idInvalid"); + case "taken": + return t("settings.providers.account.errors.idTaken"); + default: + return null; + } +} + +function resolveEnvError( + state: ProviderAccountFormState, + row: ProviderAccountEnvRow, + t: Translate, +): string | null { + switch (state.envErrors[row.id]) { + case "keyRequired": + return t("settings.providers.account.errors.envKeyRequired"); + case "duplicate": + return t("settings.providers.account.errors.envDuplicate"); + default: + return null; + } +} + +interface EnvVarRowProps { + row: ProviderAccountEnvRow; + index: number; + model: ProviderAccountFormModel; + controlSize: FieldControlSize; + disabled: boolean; + error: string | null; +} + +function EnvVarRow({ + row, + index, + model, + controlSize, + disabled, + error, +}: EnvVarRowProps): ReactElement { + const { t } = useTranslation(); + const handleKeyChange = useCallback( + (value: string) => { + model.setEnvKey(row.id, value); + }, + [model, row.id], + ); + const handleValueChange = useCallback( + (value: string) => { + model.setEnvValue(row.id, value); + }, + [model, row.id], + ); + const handleRemove = useCallback(() => { + model.removeEnvRow(row.id); + }, [model, row.id]); + + return ( + + + + + + + + + + + + + {error ? {error} : null} + + ); +} + +const styles = StyleSheet.create((theme) => ({ + footer: { + flex: 1, + flexDirection: "row", + gap: theme.spacing[3], + }, + footerButton: { + flex: 1, + }, + envRows: { + gap: theme.spacing[2], + }, + envRowGroup: { + gap: theme.spacing[1], + }, + envRow: { + flexDirection: "row", + alignItems: "center", + gap: theme.spacing[2], + }, + envKeyField: { + flex: 1, + minWidth: 0, + }, + envValueField: { + flex: 1, + minWidth: 0, + }, + envRemoveButton: { + width: 28, + height: 28, + alignItems: "center", + justifyContent: "center", + borderRadius: theme.borderRadius.lg, + }, + envRowError: { + color: theme.colors.palette.red[300], + fontSize: theme.fontSize.xs, + lineHeight: Math.round(theme.fontSize.xs * 1.4), + }, + addEnvButton: { + alignSelf: "flex-start", + }, +})); diff --git a/packages/app/src/i18n/resources/ar.ts b/packages/app/src/i18n/resources/ar.ts index 05ef39bda67..c901d7ecb19 100644 --- a/packages/app/src/i18n/resources/ar.ts +++ b/packages/app/src/i18n/resources/ar.ts @@ -2565,9 +2565,42 @@ export const ar: TranslationResources = { updateErrorTitle: "غير قادر على تحديث الموفر", actions: { menu: "{{name}} actions", + addAccount: "إضافة حساب", remove: "Remove provider", removing: "Removing...", }, + account: { + title: "إضافة حساب {{provider}}", + errorTitle: "تعذر إضافة الحساب", + submit: "إضافة حساب", + fields: { + label: "الاسم", + providerId: "معرّف المزود", + description: "الوصف", + env: "متغيرات البيئة", + envKey: "اسم المتغير", + envValue: "قيمة المتغير", + }, + placeholders: { + label: "{{provider}} (العمل)", + providerId: "claude-work", + description: "اختياري", + envKey: "الاسم", + envValue: "القيمة", + }, + actions: { + addVariable: "إضافة متغير", + removeVariable: "إزالة المتغير", + }, + errors: { + labelRequired: "أدخل اسمًا.", + idRequired: "أدخل معرّف المزود.", + idInvalid: "استخدم أحرفًا صغيرة وأرقامًا وشرطات، بدءًا بحرف.", + idTaken: "معرّف المزود هذا مستخدم بالفعل.", + envKeyRequired: "أدخل اسم المتغير.", + envDuplicate: "هذا المتغير معيّن بالفعل.", + }, + }, remove: { confirmTitle: "Remove {{name}}?", confirmMessage: "This deletes the provider entry from config.json. It cannot be undone.", diff --git a/packages/app/src/i18n/resources/en.ts b/packages/app/src/i18n/resources/en.ts index 7ec3c1018de..a180bccbf89 100644 --- a/packages/app/src/i18n/resources/en.ts +++ b/packages/app/src/i18n/resources/en.ts @@ -2692,9 +2692,42 @@ export const en = { updateErrorTitle: "Unable to update provider", actions: { menu: "{{name}} actions", + addAccount: "Add account", remove: "Remove provider", removing: "Removing...", }, + account: { + title: "Add {{provider}} account", + errorTitle: "Unable to add account", + submit: "Add account", + fields: { + label: "Name", + providerId: "Provider ID", + description: "Description", + env: "Environment variables", + envKey: "Variable name", + envValue: "Variable value", + }, + placeholders: { + label: "{{provider}} (Work)", + providerId: "claude-work", + description: "Optional", + envKey: "NAME", + envValue: "Value", + }, + actions: { + addVariable: "Add variable", + removeVariable: "Remove variable", + }, + errors: { + labelRequired: "Enter a name.", + idRequired: "Enter a provider ID.", + idInvalid: "Use lowercase letters, numbers, and dashes, starting with a letter.", + idTaken: "This provider ID is already taken.", + envKeyRequired: "Enter a variable name.", + envDuplicate: "This variable is already set.", + }, + }, remove: { confirmTitle: "Remove {{name}}?", confirmMessage: "This deletes the provider entry from config.json. It cannot be undone.", diff --git a/packages/app/src/i18n/resources/es.ts b/packages/app/src/i18n/resources/es.ts index a285459213e..eef90c8de77 100644 --- a/packages/app/src/i18n/resources/es.ts +++ b/packages/app/src/i18n/resources/es.ts @@ -2624,9 +2624,42 @@ export const es: TranslationResources = { updateErrorTitle: "No se puede actualizar el proveedor", actions: { menu: "{{name}} actions", + addAccount: "Añadir cuenta", remove: "Remove provider", removing: "Removing...", }, + account: { + title: "Añadir cuenta de {{provider}}", + errorTitle: "No se pudo añadir la cuenta", + submit: "Añadir cuenta", + fields: { + label: "Nombre", + providerId: "ID del proveedor", + description: "Descripción", + env: "Variables de entorno", + envKey: "Nombre de la variable", + envValue: "Valor de la variable", + }, + placeholders: { + label: "{{provider}} (Trabajo)", + providerId: "claude-work", + description: "Opcional", + envKey: "NOMBRE", + envValue: "Valor", + }, + actions: { + addVariable: "Añadir variable", + removeVariable: "Quitar variable", + }, + errors: { + labelRequired: "Escribe un nombre.", + idRequired: "Escribe un ID de proveedor.", + idInvalid: "Usa minúsculas, números y guiones, empezando por una letra.", + idTaken: "Este ID de proveedor ya está en uso.", + envKeyRequired: "Escribe el nombre de la variable.", + envDuplicate: "Esta variable ya está definida.", + }, + }, remove: { confirmTitle: "Remove {{name}}?", confirmMessage: "This deletes the provider entry from config.json. It cannot be undone.", diff --git a/packages/app/src/i18n/resources/fr.ts b/packages/app/src/i18n/resources/fr.ts index 738ac685896..bd6854a1f95 100644 --- a/packages/app/src/i18n/resources/fr.ts +++ b/packages/app/src/i18n/resources/fr.ts @@ -2632,9 +2632,43 @@ export const fr: TranslationResources = { updateErrorTitle: "Impossible de mettre à jour le fournisseur", actions: { menu: "{{name}} actions", + addAccount: "Ajouter un compte", remove: "Remove provider", removing: "Removing...", }, + account: { + title: "Ajouter un compte {{provider}}", + errorTitle: "Impossible d'ajouter le compte", + submit: "Ajouter un compte", + fields: { + label: "Nom", + providerId: "ID du fournisseur", + description: "Description", + env: "Variables d'environnement", + envKey: "Nom de la variable", + envValue: "Valeur de la variable", + }, + placeholders: { + label: "{{provider}} (Travail)", + providerId: "claude-work", + description: "Facultatif", + envKey: "NOM", + envValue: "Valeur", + }, + actions: { + addVariable: "Ajouter une variable", + removeVariable: "Supprimer la variable", + }, + errors: { + labelRequired: "Saisissez un nom.", + idRequired: "Saisissez un ID de fournisseur.", + idInvalid: + "Utilisez des minuscules, des chiffres et des tirets, en commençant par une lettre.", + idTaken: "Cet ID de fournisseur est déjà utilisé.", + envKeyRequired: "Saisissez le nom de la variable.", + envDuplicate: "Cette variable est déjà définie.", + }, + }, remove: { confirmTitle: "Remove {{name}}?", confirmMessage: "This deletes the provider entry from config.json. It cannot be undone.", diff --git a/packages/app/src/i18n/resources/ja.ts b/packages/app/src/i18n/resources/ja.ts index 09ecc457119..048b1b87e64 100644 --- a/packages/app/src/i18n/resources/ja.ts +++ b/packages/app/src/i18n/resources/ja.ts @@ -2593,9 +2593,42 @@ export const ja: TranslationResources = { updateErrorTitle: "プロバイダーを更新できません", actions: { menu: "{{name}} actions", + addAccount: "アカウントを追加", remove: "Remove provider", removing: "Removing...", }, + account: { + title: "{{provider}} アカウントを追加", + errorTitle: "アカウントを追加できません", + submit: "アカウントを追加", + fields: { + label: "名前", + providerId: "プロバイダー ID", + description: "説明", + env: "環境変数", + envKey: "変数名", + envValue: "変数の値", + }, + placeholders: { + label: "{{provider}}(仕事)", + providerId: "claude-work", + description: "省略可", + envKey: "名前", + envValue: "値", + }, + actions: { + addVariable: "変数を追加", + removeVariable: "変数を削除", + }, + errors: { + labelRequired: "名前を入力してください。", + idRequired: "プロバイダー ID を入力してください。", + idInvalid: "英小文字・数字・ハイフンを使い、先頭は英字にしてください。", + idTaken: "このプロバイダー ID は既に使われています。", + envKeyRequired: "変数名を入力してください。", + envDuplicate: "この変数は既に設定されています。", + }, + }, remove: { confirmTitle: "Remove {{name}}?", confirmMessage: "This deletes the provider entry from config.json. It cannot be undone.", diff --git a/packages/app/src/i18n/resources/pt-BR.ts b/packages/app/src/i18n/resources/pt-BR.ts index be65df9f934..7aede8d6514 100644 --- a/packages/app/src/i18n/resources/pt-BR.ts +++ b/packages/app/src/i18n/resources/pt-BR.ts @@ -2607,9 +2607,42 @@ export const ptBR: TranslationResources = { updateErrorTitle: "Não foi possível atualizar provedor", actions: { menu: "{{name}} actions", + addAccount: "Adicionar conta", remove: "Remove provider", removing: "Removing...", }, + account: { + title: "Adicionar conta do {{provider}}", + errorTitle: "Não foi possível adicionar a conta", + submit: "Adicionar conta", + fields: { + label: "Nome", + providerId: "ID do provedor", + description: "Descrição", + env: "Variáveis de ambiente", + envKey: "Nome da variável", + envValue: "Valor da variável", + }, + placeholders: { + label: "{{provider}} (Trabalho)", + providerId: "claude-work", + description: "Opcional", + envKey: "NOME", + envValue: "Valor", + }, + actions: { + addVariable: "Adicionar variável", + removeVariable: "Remover variável", + }, + errors: { + labelRequired: "Digite um nome.", + idRequired: "Digite um ID de provedor.", + idInvalid: "Use letras minúsculas, números e hifens, começando por uma letra.", + idTaken: "Este ID de provedor já está em uso.", + envKeyRequired: "Digite o nome da variável.", + envDuplicate: "Esta variável já está definida.", + }, + }, remove: { confirmTitle: "Remove {{name}}?", confirmMessage: "This deletes the provider entry from config.json. It cannot be undone.", diff --git a/packages/app/src/i18n/resources/ru.ts b/packages/app/src/i18n/resources/ru.ts index 24df5f6478e..e6e97804ee7 100644 --- a/packages/app/src/i18n/resources/ru.ts +++ b/packages/app/src/i18n/resources/ru.ts @@ -2615,9 +2615,42 @@ export const ru: TranslationResources = { updateErrorTitle: "Не удалось обновить провайдера", actions: { menu: "Действия с {{name}}", + addAccount: "Добавить аккаунт", remove: "Удалить провайдера", removing: "Удаление...", }, + account: { + title: "Добавить аккаунт {{provider}}", + errorTitle: "Не удалось добавить аккаунт", + submit: "Добавить аккаунт", + fields: { + label: "Название", + providerId: "ID провайдера", + description: "Описание", + env: "Переменные окружения", + envKey: "Имя переменной", + envValue: "Значение переменной", + }, + placeholders: { + label: "{{provider}} (Работа)", + providerId: "claude-work", + description: "Необязательно", + envKey: "ИМЯ", + envValue: "Значение", + }, + actions: { + addVariable: "Добавить переменную", + removeVariable: "Удалить переменную", + }, + errors: { + labelRequired: "Введите название.", + idRequired: "Введите ID провайдера.", + idInvalid: "Используйте строчные буквы, цифры и дефисы, начиная с буквы.", + idTaken: "Этот ID провайдера уже занят.", + envKeyRequired: "Введите имя переменной.", + envDuplicate: "Эта переменная уже задана.", + }, + }, remove: { confirmTitle: "Удалить {{name}}?", confirmMessage: diff --git a/packages/app/src/i18n/resources/zh-CN.ts b/packages/app/src/i18n/resources/zh-CN.ts index 850a25724fd..97b247239ff 100644 --- a/packages/app/src/i18n/resources/zh-CN.ts +++ b/packages/app/src/i18n/resources/zh-CN.ts @@ -2534,9 +2534,42 @@ export const zhCN: TranslationResources = { updateErrorTitle: "无法更新 Provider", actions: { menu: "{{name}} actions", + addAccount: "添加账户", remove: "Remove provider", removing: "Removing...", }, + account: { + title: "添加 {{provider}} 账户", + errorTitle: "无法添加账户", + submit: "添加账户", + fields: { + label: "名称", + providerId: "Provider ID", + description: "描述", + env: "环境变量", + envKey: "变量名", + envValue: "变量值", + }, + placeholders: { + label: "{{provider}}(工作)", + providerId: "claude-work", + description: "可选", + envKey: "名称", + envValue: "值", + }, + actions: { + addVariable: "添加变量", + removeVariable: "移除变量", + }, + errors: { + labelRequired: "请输入名称。", + idRequired: "请输入 Provider ID。", + idInvalid: "只能使用小写字母、数字和连字符,且以字母开头。", + idTaken: "该 Provider ID 已被占用。", + envKeyRequired: "请输入变量名。", + envDuplicate: "该变量已设置。", + }, + }, remove: { confirmTitle: "Remove {{name}}?", confirmMessage: "This deletes the provider entry from config.json. It cannot be undone.", diff --git a/packages/app/src/provider-accounts/provider-account-form-model.test.ts b/packages/app/src/provider-accounts/provider-account-form-model.test.ts new file mode 100644 index 00000000000..0e22235f397 --- /dev/null +++ b/packages/app/src/provider-accounts/provider-account-form-model.test.ts @@ -0,0 +1,167 @@ +import { describe, expect, it } from "vitest"; +import { + canAddProviderAccount, + deriveProviderAccountId, + openProviderAccountForm, + type ProviderAccountFormSnapshot, +} from "./provider-account-form-model"; + +const SNAPSHOT: ProviderAccountFormSnapshot = { + baseProviderId: "claude", + baseProviderLabel: "Claude Code", + existingProviderIds: ["claude", "codex", "junie"], +}; + +function openForm(overrides: Partial = {}) { + return openProviderAccountForm({ ...SNAPSHOT, ...overrides }); +} + +describe("canAddProviderAccount", () => { + it("accepts builtin providers that can be extended", () => { + expect(canAddProviderAccount({ providerId: "claude", source: "builtin" })).toBe(true); + expect(canAddProviderAccount({ providerId: "omp", source: "builtin" })).toBe(true); + }); + + it("rejects acp, custom rows, and unknown sources", () => { + expect(canAddProviderAccount({ providerId: "acp", source: "builtin" })).toBe(false); + expect(canAddProviderAccount({ providerId: "junie", source: "custom" })).toBe(false); + expect(canAddProviderAccount({ providerId: "claude", source: undefined })).toBe(false); + }); +}); + +describe("deriveProviderAccountId", () => { + it("slugs a label into a legal provider id", () => { + expect(deriveProviderAccountId("Claude (Work)")).toBe("claude-work"); + expect(deriveProviderAccountId(" Z.AI ")).toBe("z-ai"); + expect(deriveProviderAccountId("2nd Account")).toBe("nd-account"); + expect(deriveProviderAccountId("!!!")).toBe(""); + }); +}); + +describe("provider account form model", () => { + it("tracks the label until the id is edited by hand", () => { + const model = openForm(); + model.setLabel("Claude Work"); + expect(model.getState().providerId).toBe("claude-work"); + expect(model.getState().providerIdEdited).toBe(false); + + model.setProviderId("work"); + model.setLabel("Claude Personal"); + expect(model.getState().providerId).toBe("work"); + expect(model.getState().providerIdEdited).toBe(true); + }); + + it("hides required errors until submit is attempted", () => { + const model = openForm(); + expect(model.getState().labelError).toBeNull(); + expect(model.getState().providerIdError).toBeNull(); + expect(model.getState().canSubmit).toBe(false); + + model.markSubmitAttempted(); + expect(model.getState().labelError).toBe("required"); + expect(model.getState().providerIdError).toBe("required"); + }); + + it("reports format and collision errors as soon as the id is touched", () => { + const model = openForm(); + model.setProviderId("Claude Work"); + expect(model.getState().providerIdError).toBe("invalid"); + + model.setProviderId("junie"); + expect(model.getState().providerIdError).toBe("taken"); + + model.setProviderId("acp"); + expect(model.getState().providerIdError).toBe("taken"); + + model.setProviderId("claude-work"); + expect(model.getState().providerIdError).toBeNull(); + }); + + it("rejects env rows with a value but no key, and duplicate keys", () => { + const model = openForm(); + model.setLabel("Claude Work"); + const [firstRow] = model.getState().envRows; + if (!firstRow) throw new Error("expected a seeded env row"); + + model.setEnvValue(firstRow.id, "sk-test"); + expect(model.getState().envErrors[firstRow.id]).toBe("keyRequired"); + expect(model.getState().canSubmit).toBe(false); + + model.setEnvKey(firstRow.id, "ANTHROPIC_API_KEY"); + expect(model.getState().envErrors).toEqual({}); + expect(model.getState().canSubmit).toBe(true); + + model.addEnvRow(); + const secondRow = model.getState().envRows[1]; + if (!secondRow) throw new Error("expected a second env row"); + model.setEnvKey(secondRow.id, "ANTHROPIC_API_KEY"); + expect(model.getState().envErrors[secondRow.id]).toBe("duplicate"); + expect(model.getState().canSubmit).toBe(false); + + model.removeEnvRow(secondRow.id); + expect(model.getState().canSubmit).toBe(true); + }); + + it("keeps one env row after removing the last one", () => { + const model = openForm(); + const [firstRow] = model.getState().envRows; + if (!firstRow) throw new Error("expected a seeded env row"); + model.removeEnvRow(firstRow.id); + expect(model.getState().envRows).toHaveLength(1); + }); + + it("builds the config patch and drops empty rows", () => { + const model = openForm(); + model.setLabel("Claude (Work)"); + model.setDescription(" Work account "); + const [firstRow] = model.getState().envRows; + if (!firstRow) throw new Error("expected a seeded env row"); + model.setEnvKey(firstRow.id, " ANTHROPIC_API_KEY "); + model.setEnvValue(firstRow.id, " sk-test "); + model.addEnvRow(); + + expect(model.buildPatch()).toEqual({ + providers: { + "claude-work": { + extends: "claude", + label: "Claude (Work)", + description: "Work account", + env: { ANTHROPIC_API_KEY: "sk-test" }, + }, + }, + }); + }); + + it("omits description when blank and returns no patch while invalid", () => { + const model = openForm(); + model.setLabel("Claude Work"); + expect(model.buildPatch()).toEqual({ + providers: { + "claude-work": { extends: "claude", label: "Claude Work", env: {} }, + }, + }); + + model.setProviderId("claude"); + expect(model.buildPatch()).toBeNull(); + }); + + it("revalidates when the provider snapshot gains the id", () => { + const model = openForm({ existingProviderIds: [] }); + model.setLabel("Claude Work"); + expect(model.getState().canSubmit).toBe(true); + + model.applyExistingProviderIds(["claude-work"]); + model.markSubmitAttempted(); + expect(model.getState().providerIdError).toBe("taken"); + expect(model.getState().canSubmit).toBe(false); + }); + + it("blocks submission while submitting", () => { + const model = openForm(); + model.setLabel("Claude Work"); + model.setSubmitting(true); + expect(model.getState().canSubmit).toBe(false); + model.setSubmitting(false); + expect(model.getState().canSubmit).toBe(true); + }); +}); diff --git a/packages/app/src/provider-accounts/provider-account-form-model.ts b/packages/app/src/provider-accounts/provider-account-form-model.ts new file mode 100644 index 00000000000..5f45ef1f2bb --- /dev/null +++ b/packages/app/src/provider-accounts/provider-account-form-model.ts @@ -0,0 +1,305 @@ +import type { MutableDaemonConfigPatch } from "@getpaseo/protocol/messages"; + +/** Provider ids the daemon reserves; a new account can never claim one. */ +export const RESERVED_PROVIDER_IDS = [ + "claude", + "codex", + "copilot", + "opencode", + "pi", + "omp", + "acp", +] as const; + +/** + * Builtin providers an account can extend. `acp` is excluded: ACP entries are + * installed from the catalog with their own command, not cloned per account. + */ +export const ACCOUNT_BASE_PROVIDER_IDS = [ + "claude", + "codex", + "copilot", + "opencode", + "pi", + "omp", +] as const; + +// Mirrors ProviderOverridesSchema in packages/protocol/src/provider-config.ts. +export const PROVIDER_ID_PATTERN = /^[a-z][a-z0-9-]*$/; + +export function canAddProviderAccount(input: { + providerId: string; + source: "builtin" | "custom" | undefined; +}): boolean { + if (input.source !== "builtin") return false; + return (ACCOUNT_BASE_PROVIDER_IDS as readonly string[]).includes(input.providerId); +} + +export function deriveProviderAccountId(label: string): string { + return label + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^[^a-z]+/, "") + .replace(/-+$/, ""); +} + +export type ProviderAccountLabelError = "required"; +export type ProviderAccountIdError = "required" | "invalid" | "taken"; +export type ProviderAccountEnvError = "keyRequired" | "duplicate"; + +export interface ProviderAccountEnvRow { + id: string; + key: string; + value: string; +} + +export interface ProviderAccountFormState { + baseProviderId: string; + baseProviderLabel: string; + label: string; + providerId: string; + /** False while the id still tracks the label; the id input remounts on change. */ + providerIdEdited: boolean; + description: string; + envRows: ProviderAccountEnvRow[]; + /** Errors are only populated once the user can act on them. */ + labelError: ProviderAccountLabelError | null; + providerIdError: ProviderAccountIdError | null; + envErrors: Record; + canSubmit: boolean; + isSubmitting: boolean; +} + +export interface ProviderAccountFormSnapshot { + baseProviderId: string; + baseProviderLabel: string; + existingProviderIds: readonly string[]; +} + +export interface ProviderAccountFormModel { + getState: () => ProviderAccountFormState; + subscribe: (listener: () => void) => () => void; + close: () => void; + applyExistingProviderIds: (providerIds: readonly string[]) => void; + setLabel: (value: string) => void; + setProviderId: (value: string) => void; + setDescription: (value: string) => void; + addEnvRow: () => void; + removeEnvRow: (rowId: string) => void; + setEnvKey: (rowId: string, value: string) => void; + setEnvValue: (rowId: string, value: string) => void; + setSubmitting: (value: boolean) => void; + markSubmitAttempted: () => void; + buildPatch: () => MutableDaemonConfigPatch | null; +} + +interface InternalState { + label: string; + providerId: string; + providerIdEdited: boolean; + description: string; + envRows: ProviderAccountEnvRow[]; + existingProviderIds: readonly string[]; + submitAttempted: boolean; + isSubmitting: boolean; +} + +interface Validation { + labelError: ProviderAccountLabelError | null; + providerIdError: ProviderAccountIdError | null; + envErrors: Record; +} + +function validate(internal: InternalState): Validation { + const labelError: ProviderAccountLabelError | null = + internal.label.trim().length === 0 ? "required" : null; + + const providerId = internal.providerId.trim(); + const taken = new Set([ + ...RESERVED_PROVIDER_IDS, + ...internal.existingProviderIds.map((value) => value.trim()), + ]); + let providerIdError: ProviderAccountIdError | null = null; + if (providerId.length === 0) { + providerIdError = "required"; + } else if (!PROVIDER_ID_PATTERN.test(providerId)) { + providerIdError = "invalid"; + } else if (taken.has(providerId)) { + providerIdError = "taken"; + } + + const envErrors: Record = {}; + const seenKeys = new Set(); + for (const row of internal.envRows) { + const key = row.key.trim(); + if (key.length === 0) { + if (row.value.trim().length > 0) { + envErrors[row.id] = "keyRequired"; + } + continue; + } + if (seenKeys.has(key)) { + envErrors[row.id] = "duplicate"; + continue; + } + seenKeys.add(key); + } + + return { labelError, providerIdError, envErrors }; +} + +function project(internal: InternalState, snapshot: ProviderAccountFormSnapshot) { + const validation = validate(internal); + const isValid = + validation.labelError === null && + validation.providerIdError === null && + Object.keys(validation.envErrors).length === 0; + + // "required" is noise until the user tries to submit; format and collision + // errors are actionable the moment the id field has been touched. + const showLabelError = internal.submitAttempted; + const showProviderIdError = + internal.submitAttempted || + (internal.providerIdEdited && validation.providerIdError !== "required"); + + const state: ProviderAccountFormState = { + baseProviderId: snapshot.baseProviderId, + baseProviderLabel: snapshot.baseProviderLabel, + label: internal.label, + providerId: internal.providerId, + providerIdEdited: internal.providerIdEdited, + description: internal.description, + envRows: internal.envRows, + labelError: showLabelError ? validation.labelError : null, + providerIdError: showProviderIdError ? validation.providerIdError : null, + envErrors: validation.envErrors, + canSubmit: isValid && !internal.isSubmitting, + isSubmitting: internal.isSubmitting, + }; + return state; +} + +export function buildProviderAccountConfigPatch(input: { + providerId: string; + baseProviderId: string; + label: string; + description: string; + envRows: readonly ProviderAccountEnvRow[]; +}): MutableDaemonConfigPatch { + const env: Record = {}; + for (const row of input.envRows) { + const key = row.key.trim(); + if (key.length === 0) continue; + env[key] = row.value.trim(); + } + const description = input.description.trim(); + + return { + providers: { + [input.providerId.trim()]: { + extends: input.baseProviderId, + label: input.label.trim(), + ...(description ? { description } : {}), + env, + }, + }, + }; +} + +export function openProviderAccountForm( + snapshot: ProviderAccountFormSnapshot, +): ProviderAccountFormModel { + let rowCounter = 0; + const createRow = (): ProviderAccountEnvRow => { + rowCounter += 1; + return { id: `env-${rowCounter}`, key: "", value: "" }; + }; + + let internal: InternalState = { + label: "", + providerId: "", + providerIdEdited: false, + description: "", + envRows: [createRow()], + existingProviderIds: [...snapshot.existingProviderIds], + submitAttempted: false, + isSubmitting: false, + }; + + let listeners = new Set<() => void>(); + let state = project(internal, snapshot); + + const publish = (next: InternalState) => { + internal = next; + state = project(internal, snapshot); + for (const listener of listeners) listener(); + }; + + const mapRows = (rowId: string, update: (row: ProviderAccountEnvRow) => ProviderAccountEnvRow) => + internal.envRows.map((row) => (row.id === rowId ? update(row) : row)); + + return { + getState: () => state, + subscribe: (listener) => { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + close: () => { + listeners = new Set(); + }, + applyExistingProviderIds: (providerIds) => { + const next = [...providerIds]; + const unchanged = + next.length === internal.existingProviderIds.length && + next.every((value, index) => value === internal.existingProviderIds[index]); + if (unchanged) return; + publish({ ...internal, existingProviderIds: next }); + }, + setLabel: (value) => { + publish({ + ...internal, + label: value, + providerId: internal.providerIdEdited + ? internal.providerId + : deriveProviderAccountId(value), + }); + }, + setProviderId: (value) => { + publish({ ...internal, providerId: value, providerIdEdited: true }); + }, + setDescription: (value) => { + publish({ ...internal, description: value }); + }, + addEnvRow: () => { + publish({ ...internal, envRows: [...internal.envRows, createRow()] }); + }, + removeEnvRow: (rowId) => { + const remaining = internal.envRows.filter((row) => row.id !== rowId); + publish({ ...internal, envRows: remaining.length > 0 ? remaining : [createRow()] }); + }, + setEnvKey: (rowId, value) => { + publish({ ...internal, envRows: mapRows(rowId, (row) => ({ ...row, key: value })) }); + }, + setEnvValue: (rowId, value) => { + publish({ ...internal, envRows: mapRows(rowId, (row) => ({ ...row, value })) }); + }, + setSubmitting: (value) => { + publish({ ...internal, isSubmitting: value }); + }, + markSubmitAttempted: () => { + publish({ ...internal, submitAttempted: true }); + }, + buildPatch: () => { + if (!state.canSubmit) return null; + return buildProviderAccountConfigPatch({ + providerId: internal.providerId, + baseProviderId: snapshot.baseProviderId, + label: internal.label, + description: internal.description, + envRows: internal.envRows, + }); + }, + }; +} diff --git a/packages/app/src/provider-accounts/use-provider-account-form-model.ts b/packages/app/src/provider-accounts/use-provider-account-form-model.ts new file mode 100644 index 00000000000..4923fc6e9f1 --- /dev/null +++ b/packages/app/src/provider-accounts/use-provider-account-form-model.ts @@ -0,0 +1,21 @@ +import { useEffect, useState } from "react"; +import { + openProviderAccountForm, + type ProviderAccountFormSnapshot, +} from "./provider-account-form-model"; + +export function useProviderAccountFormModel(snapshot: ProviderAccountFormSnapshot) { + const [model] = useState(() => openProviderAccountForm(snapshot)); + + useEffect(() => { + return () => { + model.close(); + }; + }, [model]); + + useEffect(() => { + model.applyExistingProviderIds(snapshot.existingProviderIds); + }, [model, snapshot.existingProviderIds]); + + return model; +} diff --git a/packages/app/src/screens/settings/providers-section.tsx b/packages/app/src/screens/settings/providers-section.tsx index 69e5caadac7..45e283296f7 100644 --- a/packages/app/src/screens/settings/providers-section.tsx +++ b/packages/app/src/screens/settings/providers-section.tsx @@ -22,6 +22,11 @@ import { type AcpProviderCatalogItem, } from "@/hooks/use-acp-provider-catalog"; import { ProviderCatalogList } from "@/components/provider-catalog-list"; +import { + ProviderAccountSheet, + type ProviderAccountCreateInput, +} from "@/components/provider-account-sheet"; +import { canAddProviderAccount } from "@/provider-accounts/provider-account-form-model"; import { getProviderIcon } from "@/components/provider-icons"; import { LoadingSpinner } from "@/components/ui/loading-spinner"; import { Switch } from "@/components/ui/switch"; @@ -35,7 +40,7 @@ import { SettingsSection } from "@/components/settings/headings/settings-section import { useProviderSettingsStore } from "@/stores/provider-settings-store"; import { confirmDialog } from "@/utils/confirm-dialog"; import { filterSelectableModels } from "@/provider-selection/model-catalog"; -import { ChevronRight, MoreHorizontal, Trash2 } from "lucide-react-native"; +import { ChevronRight, MoreHorizontal, Trash2, UserPlus } from "lucide-react-native"; type ProviderDefinition = ReturnType[number]; type ProviderEntry = NonNullable["entries"]>[number]; @@ -84,10 +89,12 @@ interface ProviderRowProps { isToggling: boolean; isRemoving: boolean; canRemove: boolean; + canAddAccount: boolean; isFirst: boolean; onPress: (providerId: string) => void; onToggleEnabled: (providerId: string, enabled: boolean) => void; onRemove: (providerId: string, providerLabel: string) => void; + onAddAccount: (providerId: string, providerLabel: string) => void; } function stopPressInPropagation(event: GestureResponderEvent) { @@ -98,27 +105,36 @@ interface ProviderActionsMenuProps { providerId: string; providerLabel: string; isRemoving: boolean; + canRemove: boolean; + canAddAccount: boolean; iconSize: number; foregroundColor: string; foregroundMutedColor: string; dangerColor: string; onRemove: (providerId: string, providerLabel: string) => void; + onAddAccount: (providerId: string, providerLabel: string) => void; } function ProviderActionsMenu({ providerId, providerLabel, isRemoving, + canRemove, + canAddAccount, iconSize, foregroundColor, foregroundMutedColor, dangerColor, onRemove, + onAddAccount, }: ProviderActionsMenuProps) { const { t } = useTranslation(); const handleRemove = useCallback(() => { onRemove(providerId, providerLabel); }, [onRemove, providerId, providerLabel]); + const handleAddAccount = useCallback(() => { + onAddAccount(providerId, providerLabel); + }, [onAddAccount, providerId, providerLabel]); const triggerStyle = useCallback( ({ pressed, @@ -132,6 +148,10 @@ function ProviderActionsMenu({ [], ); const trashLeading = useMemo(() => , [dangerColor]); + const addAccountLeading = useMemo( + () => , + [foregroundMutedColor], + ); return ( @@ -152,16 +172,27 @@ function ProviderActionsMenu({ )} - - {t("settings.providers.actions.remove")} - + {canAddAccount ? ( + + {t("settings.providers.actions.addAccount")} + + ) : null} + {canRemove ? ( + + {t("settings.providers.actions.remove")} + + ) : null} ); @@ -175,10 +206,12 @@ function ProviderRow({ isToggling, isRemoving, canRemove, + canAddAccount, isFirst, onPress, onToggleEnabled, onRemove, + onAddAccount, }: ProviderRowProps) { const { t } = useTranslation(); const { theme } = useUnistyles(); @@ -252,16 +285,19 @@ function ProviderRow({ accessibilityLabel={t("settings.providers.enableProvider", { name: def.label })} /> - {canRemove ? ( + {canRemove || canAddAccount ? ( ) : null} @@ -319,6 +355,11 @@ function StatusIndicator({ status, compact }: { status: ProviderStatus; compact: ); } +interface ProviderAccountTarget { + id: string; + label: string; +} + export interface ProvidersSectionProps { serverId: string; } @@ -334,8 +375,15 @@ export function ProvidersSection({ serverId }: ProvidersSectionProps) { const [removingProviderId, setRemovingProviderId] = useState(null); const removingProviderIdRef = useRef(null); const [installingProviderId, setInstallingProviderId] = useState(null); + const [accountBaseProvider, setAccountBaseProvider] = useState( + null, + ); const providerDefinitions = useMemo(() => buildProviderDefinitions(entries), [entries]); + const existingProviderIds = useMemo( + () => (entries ?? []).map((entry) => entry.provider), + [entries], + ); const hasServer = serverId.length > 0; const handleOpenProviderSettings = useCallback( @@ -413,6 +461,31 @@ export function ProvidersSection({ serverId }: ProvidersSectionProps) { [installingProviderId, patchConfig, refresh, t], ); + const handleOpenAddAccount = useCallback((providerId: string, providerLabel: string) => { + setAccountBaseProvider({ id: providerId, label: providerLabel }); + }, []); + + const handleCloseAddAccount = useCallback(() => { + setAccountBaseProvider(null); + }, []); + + const handleCreateAccount = useCallback( + async ({ providerId, patch }: ProviderAccountCreateInput) => { + try { + await patchConfig(patch); + await refresh([providerId]); + return true; + } catch (error) { + Alert.alert( + t("settings.providers.account.errorTitle"), + error instanceof Error ? error.message : String(error), + ); + return false; + } + }, + [patchConfig, refresh, t], + ); + return ( <> ); })} @@ -469,6 +547,18 @@ export function ProvidersSection({ serverId }: ProvidersSectionProps) { /> ) : null} + + {accountBaseProvider ? ( + + ) : null} ); } diff --git a/packages/cli/src/commands/provider/add.test.ts b/packages/cli/src/commands/provider/add.test.ts new file mode 100644 index 00000000000..846e7bd81bc --- /dev/null +++ b/packages/cli/src/commands/provider/add.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from "vitest"; +import { buildProviderOverride } from "./add.js"; + +describe("provider add override", () => { + it("builds a profile that extends a built-in provider", () => { + expect( + buildProviderOverride("claude-work", { + extends: "claude", + label: "Claude (Work)", + description: "Work account", + env: ["ANTHROPIC_API_KEY=sk-ant-123", "ANTHROPIC_BASE_URL=https://proxy/v1"], + }), + ).toEqual({ + id: "claude-work", + override: { + extends: "claude", + label: "Claude (Work)", + description: "Work account", + env: { + ANTHROPIC_API_KEY: "sk-ant-123", + ANTHROPIC_BASE_URL: "https://proxy/v1", + }, + }, + }); + }); + + it("defaults the label to the id and marks the first model as default", () => { + expect( + buildProviderOverride("zai", { + extends: "claude", + model: ["glm-5-turbo=GLM 5 Turbo", "glm-4.5-air"], + }), + ).toEqual({ + id: "zai", + override: { + extends: "claude", + label: "zai", + models: [ + { id: "glm-5-turbo", label: "GLM 5 Turbo", isDefault: true }, + { id: "glm-4.5-air", label: "glm-4.5-air" }, + ], + }, + }); + }); + + it("keeps the command argv for acp providers", () => { + expect( + buildProviderOverride("gemini", { + extends: "acp", + label: "Gemini", + command: ["npx", "-y", "@google/gemini-cli", "--experimental-acp"], + }).override.command, + ).toEqual(["npx", "-y", "@google/gemini-cli", "--experimental-acp"]); + }); + + it("rejects ids that do not match the provider id pattern", () => { + expect(() => buildProviderOverride("Claude_Work", { extends: "claude" })).toThrow( + /Invalid provider id/, + ); + }); + + it("refuses to shadow a built-in provider id", () => { + expect(() => buildProviderOverride("claude", { extends: "claude" })).toThrow(/built-in/); + }); + + it("rejects an unknown extends target", () => { + expect(() => buildProviderOverride("mine", { extends: "gpt" })).toThrow(/Invalid --extends/); + }); + + it("requires a command when extending acp", () => { + expect(() => buildProviderOverride("mine", { extends: "acp" })).toThrow( + /--command is required/, + ); + }); + + it("rejects env entries that are not KEY=VALUE", () => { + expect(() => buildProviderOverride("mine", { extends: "claude", env: ["NOPE"] })).toThrow( + /expected KEY=VALUE/, + ); + }); +}); diff --git a/packages/cli/src/commands/provider/add.ts b/packages/cli/src/commands/provider/add.ts new file mode 100644 index 00000000000..b5d71f57367 --- /dev/null +++ b/packages/cli/src/commands/provider/add.ts @@ -0,0 +1,175 @@ +import type { Command } from "commander"; +import type { ProviderOverride, ProviderProfileModel } from "@getpaseo/protocol/provider-config"; +import type { + CommandError, + CommandOptions, + OutputSchema, + SingleResult, +} from "../../output/index.js"; +import { connectToDaemon, getDaemonHost } from "../../utils/client.js"; +import { PROVIDER_ID_PATTERN, VALID_EXTENDS_VALUES, isBuiltinProviderId } from "./shared.js"; + +export interface ProviderAddOptions extends CommandOptions { + extends?: string; + label?: string; + description?: string; + env?: string[]; + model?: string[]; + command?: string[]; +} + +export interface ProviderAddRow { + provider: string; + label: string; + extends: string; + models: string; + env: string; + command: string; +} + +export const providerAddSchema: OutputSchema = { + idField: "provider", + columns: [ + { header: "PROVIDER", field: "provider", width: 16 }, + { header: "LABEL", field: "label", width: 20 }, + { header: "EXTENDS", field: "extends", width: 10 }, + { header: "MODELS", field: "models", width: 30 }, + { header: "ENV", field: "env", width: 24 }, + { header: "COMMAND", field: "command", width: 30 }, + ], +}; + +const ENV_KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/; + +function parseEnvEntries(entries: string[]): Record { + const env: Record = {}; + for (const entry of entries) { + const separator = entry.indexOf("="); + if (separator <= 0) { + throw new Error(`Invalid --env "${entry}": expected KEY=VALUE`); + } + const key = entry.slice(0, separator); + if (!ENV_KEY_PATTERN.test(key)) { + throw new Error(`Invalid --env key "${key}": must match ${ENV_KEY_PATTERN}`); + } + env[key] = entry.slice(separator + 1); + } + return env; +} + +function parseModelEntries(entries: string[]): ProviderProfileModel[] { + return entries.map((entry, index) => { + const separator = entry.indexOf("="); + const id = separator === -1 ? entry : entry.slice(0, separator); + const label = separator === -1 ? entry : entry.slice(separator + 1); + if (!id) { + throw new Error(`Invalid --model "${entry}": expected id or id=label`); + } + if (!label) { + throw new Error(`Invalid --model "${entry}": label must not be empty`); + } + return { id, label, ...(index === 0 ? { isDefault: true } : {}) }; + }); +} + +/** + * Build the provider override for `provider add`. The daemon validates too; this + * catches the common mistakes before a round trip so the message names the flag. + */ +export function buildProviderOverride( + id: string, + options: ProviderAddOptions, +): { id: string; override: ProviderOverride } { + if (!PROVIDER_ID_PATTERN.test(id)) { + throw new Error( + `Invalid provider id "${id}": must start with a lowercase letter and contain only lowercase letters, digits, and hyphens`, + ); + } + if (isBuiltinProviderId(id)) { + throw new Error( + `"${id}" is a built-in provider. Pick a different id and use --extends ${id} to base a profile on it.`, + ); + } + + const extendsProvider = options.extends; + if (!extendsProvider) { + throw new Error(`--extends is required (one of: ${VALID_EXTENDS_VALUES.join(", ")})`); + } + if (!VALID_EXTENDS_VALUES.includes(extendsProvider)) { + throw new Error( + `Invalid --extends "${extendsProvider}": expected one of ${VALID_EXTENDS_VALUES.join(", ")}`, + ); + } + + const commandArgv = options.command ?? []; + if (extendsProvider === "acp" && commandArgv.length === 0) { + throw new Error("--command is required when extending acp"); + } + + const env = parseEnvEntries(options.env ?? []); + const models = parseModelEntries(options.model ?? []); + + const override: ProviderOverride = { + extends: extendsProvider, + label: options.label ?? id, + ...(options.description ? { description: options.description } : {}), + ...(commandArgv.length > 0 ? { command: commandArgv } : {}), + ...(Object.keys(env).length > 0 ? { env } : {}), + ...(models.length > 0 ? { models } : {}), + }; + + return { id, override }; +} + +function toRow(id: string, override: ProviderOverride): ProviderAddRow { + return { + provider: id, + label: override.label ?? id, + extends: override.extends ?? "-", + models: (override.models ?? []).map((model) => model.id).join(", ") || "-", + env: Object.keys(override.env ?? {}).join(", ") || "-", + command: (override.command ?? []).join(" ") || "-", + }; +} + +export async function runAddCommand( + id: string, + options: ProviderAddOptions, + _command: Command, +): Promise> { + let built: { id: string; override: ProviderOverride }; + try { + built = buildProviderOverride(id, options); + } catch (error) { + throw { + code: "INVALID_PROVIDER_CONFIG", + message: error instanceof Error ? error.message : String(error), + } satisfies CommandError; + } + + const host = getDaemonHost({ host: options.host }); + const client = await connectToDaemon({ host: options.host }).catch((error: unknown) => { + const message = error instanceof Error ? error.message : String(error); + throw { + code: "DAEMON_NOT_RUNNING", + message: `Cannot connect to daemon at ${host}: ${message}`, + } satisfies CommandError; + }); + + try { + const { config } = await client.getDaemonConfig(); + if (built.id in (config.providers ?? {})) { + throw new Error( + `Provider "${built.id}" already exists. Remove it with "paseo provider rm ${built.id}" first.`, + ); + } + + await client.patchDaemonConfig({ providers: { [built.id]: built.override } }); + return { type: "single", data: toRow(built.id, built.override), schema: providerAddSchema }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + throw { code: "PROVIDER_ADD_FAILED", message } satisfies CommandError; + } finally { + await client.close().catch(() => undefined); + } +} diff --git a/packages/cli/src/commands/provider/index.ts b/packages/cli/src/commands/provider/index.ts index 1e934940ee2..264033144c9 100644 --- a/packages/cli/src/commands/provider/index.ts +++ b/packages/cli/src/commands/provider/index.ts @@ -1,9 +1,12 @@ import { Command } from "commander"; +import { runAddCommand } from "./add.js"; +import { runDiagnosticCommand } from "./diagnostic.js"; import { runLsCommand } from "./ls.js"; import { runModelsCommand } from "./models.js"; -import { runDiagnosticCommand } from "./diagnostic.js"; +import { runRmCommand } from "./rm.js"; +import { VALID_EXTENDS_VALUES } from "./shared.js"; import { withOutput } from "../../output/index.js"; -import { addJsonAndDaemonHostOptions } from "../../utils/command-options.js"; +import { addJsonAndDaemonHostOptions, collectMultiple } from "../../utils/command-options.js"; export function createProviderCommand(): Command { const provider = new Command("provider").description("Manage agent providers"); @@ -27,5 +30,38 @@ export function createProviderCommand(): Command { .argument("", "Provider name"), ).action(withOutput(runDiagnosticCommand)); + addJsonAndDaemonHostOptions( + provider + .command("add") + .description("Add a custom provider profile") + .argument("", "New provider id (lowercase letters, digits, hyphens)") + .requiredOption( + "--extends ", + `Provider to inherit from (${VALID_EXTENDS_VALUES.join(", ")})`, + ) + .option("--label