Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(providers): align custom provider add flow with approved prototype
xdf838a7b51c82
diff --git a/apps/desktop/scripts/fixtures/provider-detection/provider-detection-fixture.tsx b/apps/desktop/scripts/fixtures/provider-detection/provider-detection-fixture.tsxindex 6a2fbaf4ed..40a36bf13a 100644--- a/apps/desktop/scripts/fixtures/provider-detection/provider-detection-fixture.tsx+++ b/apps/desktop/scripts/fixtures/provider-detection/provider-detection-fixture.tsx@@ -5,14 +5,14 @@ import { ProviderConnectionDialog } from '../../../src/renderer/components/settiimport { AddProviderWizard } from '../../../src/renderer/components/settings/AddProviderWizard';import type { DetectedProviderDraft } from '../../../src/shared/providerDetection';-const models = ['team-chat', 'team-coding', 'fast-chat', 'reasoning', 'vision-chat'].map(id => ({ id, name: id }));+const models = ['example-chat', 'example-reasoning', 'example-vision', 'example-fast', 'example-long-context'].map(id => ({ id, name: id, discoveredMetadata: { mode: 'chat' as const } }));function Page() {const [identified, setIdentified] = useState<DetectedProviderDraft>();const [draft, setDraft] = useState<DetectedProviderDraft>();return identified ? <AddProviderWizard providers={[]} detected={identified}onReturnCustom={value => { setDraft(value); setIdentified(undefined); }}onClose={() => undefined} onDone={() => undefined} onOpenCustomForm={() => undefined} />- : <ProviderConnectionDialog focusAgent="pi" draft={draft} onDetected={setIdentified}+ : <ProviderConnectionDialog draft={draft} onDetected={setIdentified}onClose={() => undefined} onSaved={() => undefined} />;}mountPage({@@ -20,8 +20,8 @@ mountPage({listProviderPresets: async () => ({ presets: BUNDLED_CATALOG.presets }),fetchProviderModels: async () => ctx.case === 'failed' ? { ok: false, code: 'AUTH_INVALID' } : { ok: true, models },detectProvider: async (input: { cancel?: boolean }) => input.cancel ? { candidates: [] }- : { candidates: ctx.case === 'relay' ? ['sub2api'] : [], reason: ctx.case === 'relay' ? 'matched' : 'insufficient_evidence',- catalog: ctx.case === 'failed' ? { ok: false, code: 'AUTH_INVALID' } : { ok: true, models } },+ : { candidates: ctx.case === 'relay' ? ['sub2api'] : ctx.case === 'litellm' ? ['litellm'] : [], reason: ['relay', 'litellm'].includes(ctx.case) ? 'matched' : 'insufficient_evidence',+ catalog: ctx.case === 'manual-fetch' ? undefined : ctx.case === 'failed' ? { ok: false, code: 'AUTH_INVALID' } : { ok: true, models } },localModelList: async () => ({ status: { kind: 'absent', appInstalled: false }, models: [], memoryGb: 0 }),scanLocalCli: async () => ({ detections: [] }),onProviderOAuthProgress: subscription('providerOAuthProgress'),diff --git a/apps/desktop/scripts/fixtures/provider-detection/ui-page.mjs b/apps/desktop/scripts/fixtures/provider-detection/ui-page.mjsindex 48362ef156..2b47664041 100644--- a/apps/desktop/scripts/fixtures/provider-detection/ui-page.mjs+++ b/apps/desktop/scripts/fixtures/provider-detection/ui-page.mjs@@ -5,35 +5,56 @@ export default {real: 'ProviderConnectionDialog and AddProviderWizard, delayed handoff, model selection, translations and themes',notCovered: 'Network/IPC logic has separate injected production-unit tests. Live credentials, persistence integration and actual harness calls are not covered here. Windows platform is simulated when requested.',cases: {+ empty: { about: 'HTML design: one default connection, collapsed manual entry and bottom actions' },+ return: { about: 'Return from the identified wizard with inputs preserved and no automatic navigation' },default: { about: 'Official address matches DeepSeek and enters its existing connection step' },+ litellm: { about: 'LiteLLM maps to its existing provider connection' },+ 'manual-fetch': { about: 'Unidentified endpoint has no cached list; user explicitly fetches models' },relay: { about: 'Identified Sub2API deployment keeps its own URL and key' },custom: { about: 'Unknown deployment retains discovered models and opens the full picker' },failed: { about: 'Unknown deployment with failed discovery permits manual addition' },},async ready(page) { await page.getByRole('dialog').waitFor(); },async check(page, ui) {- await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.namePlaceholder')).fill('Team connection');+ if (ui.case === 'empty') {+ assert.equal(await page.getByRole('tablist').count(), 0);+ assert.equal(await page.getByLabel(await ui.t('settings.providers.connection.manualId'), { exact: true }).count(), 0);+ await ui.capture('empty-add', { locator: page.getByRole('dialog') });+ return;+ }+ await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.namePlaceholder')).fill('我的自定义供应商');await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.apiKeyPlaceholder')).fill('fake-ui-key');- const address = ui.case === 'default' ? 'https://api.deepseek.com' : 'https://relay.example/team/v1';+ const address = ['default', 'return'].includes(ui.case) ? 'https://api.deepseek.com' : 'https://relay.example/team/v1';await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.baseUrlPlaceholder')).fill(address);- if (ui.case === 'default' || ui.case === 'relay') {+ if (['default', 'return', 'relay', 'litellm'].includes(ui.case)) {await page.getByRole('button', { name: await ui.t('settings.providers.detection.keepCustom') }).waitFor();- await ui.capture('identified');+ await ui.capture('identified', { locator: page.getByRole('dialog') });await page.getByText(await ui.t('settings.providers.wizard.nameLabel'), { exact: true }).waitFor();assert.equal(await page.getByPlaceholder('sk-…').inputValue(), 'fake-ui-key');- await ui.capture('provider-connection');+ await ui.capture('provider-connection', { locator: page.getByRole('dialog') });+ if (ui.case === 'return') {+ await page.getByRole('button', { name: await ui.t('settings.providers.wizard.back'), exact: true }).click();+ await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.baseUrlPlaceholder')).waitFor();+ await page.waitForTimeout(1800);+ await ui.capture('returned-custom', { locator: page.getByRole('dialog') });+ return;+ }await page.getByRole('button', { name: await ui.t('settings.providers.wizard.next'), exact: true }).click();await page.getByRole('button', { name: await ui.t('settings.providers.wizard.finish'), exact: true }).waitFor();- await ui.capture('models');+ await ui.capture('models', { locator: page.getByRole('dialog') });} else {await page.getByText(await ui.t('settings.providers.detection.custom'), { exact: true }).waitFor();- if (ui.case === 'custom') {+ if (['custom', 'manual-fetch'].includes(ui.case)) {+ await ui.capture('custom-model-list', { locator: page.getByRole('dialog') });+ await page.getByRole('button', { name: await ui.t('settings.providers.custom.fetch.button'), exact: true }).scrollIntoViewIfNeeded();+ await ui.capture('custom-bottom', { locator: page.getByRole('dialog') });await page.getByRole('button', { name: await ui.t('settings.providers.custom.fetch.button'), exact: true }).click();- await page.getByText('team-chat', { exact: true }).last().waitFor();+ await page.getByText('example-chat', { exact: true }).last().waitFor();await ui.capture('model-picker');} else {- await page.getByLabel(await ui.t('settings.providers.connection.manualModel'), { exact: true }).fill('private-model');- await ui.capture('manual-fallback');+ await page.getByRole('button', { name: await ui.t('settings.providers.connection.manualAdd'), exact: true }).click();+ await page.getByLabel(await ui.t('settings.providers.connection.manualId'), { exact: true }).fill('private-model');+ await ui.capture('manual-fallback', { locator: page.getByRole('dialog') });}}},diff --git a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsxindex ac35accc2d..a4c7592866 100644--- a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx+++ b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx@@ -1556,6 +1556,75 @@ describe('identified provider handoff', () => {await waitFor(() => expect(createCustomProvider).toHaveBeenCalledOnce());expect(vi.mocked(createCustomProvider).mock.calls[0][0].runtimes.pi!.models.find(m => m.id === model.id)).toMatchObject({ id: model.id, contextWindow: 4096 });});+ it('preserves hand-entered models for every inherited engine and never fetches an independent draft', async () => {+ const runtime = detected.preset.runtimes.pi;+ const own = { baseUrl: 'https://independent.example/anthropic', models: [{ id: 'own-only', name: 'Own' }] };+ const handoff = { ...detected,+ preset: { ...detected.preset, runtimes: { pi: runtime, codex: { ...runtime } } },+ keys: { pi: 'fake-key', codex: 'fake-key', 'claude-code': 'own-key' },+ config: { ...detected.config, runtimes: { pi: detected.config.runtimes.pi, codex: { ...detected.config.runtimes.pi }, 'claude-code': own } },+ };+ vi.mocked(window.electronAPI.maker.fetchProviderModels).mockResolvedValue({ ok: true, models: [{ id: 'directory-only', name: 'Directory' }] });+ render(<AddProviderWizard providers={[]} detected={handoff} onClose={vi.fn()} onDone={vi.fn()} onOpenCustomForm={vi.fn()} />);+ fireEvent.click(await screen.findByRole('button', { name: 'settings.providers.wizard.next' }));+ const finish = await screen.findByRole('button', { name: 'settings.providers.wizard.finish' });+ await waitFor(() => expect(finish.hasAttribute('disabled')).toBe(false));+ fireEvent.click(finish);+ await waitFor(() => expect(createCustomProvider).toHaveBeenCalledOnce());+ const [config, keys] = vi.mocked(createCustomProvider).mock.calls[0];+ expect(config.runtimes.codex!.models.some(m => m.id === 'private-alias')).toBe(true);+ expect(config.runtimes['claude-code']).toEqual(own);+ expect(keys['claude-code']).toBe('own-key');+ expect(vi.mocked(window.electronAPI.maker.fetchProviderModels).mock.calls.every(([request]) => request.baseUrl !== own.baseUrl)).toBe(true);+ });+ it('returns selected models only to their own engine with its discovery metadata', async () => {+ const onReturnCustom = vi.fn();+ const runtime = detected.preset.runtimes.pi;+ const handoff = { ...detected, preset: { ...detected.preset, runtimes: { pi: runtime, codex: { ...runtime } } },+ config: { ...detected.config, runtimes: { pi: detected.config.runtimes.pi, codex: { ...detected.config.runtimes.pi } } },+ };+ vi.mocked(window.electronAPI.maker.fetchProviderModels).mockResolvedValue({ ok: true, models: [+ { id: 'codex-exclusive', name: 'Only Codex', discoveredMetadata: { contextWindow: 50000 } },+ ] });+ render(<AddProviderWizard providers={[]} detected={handoff} onReturnCustom={onReturnCustom} onClose={vi.fn()} onDone={vi.fn()} onOpenCustomForm={vi.fn()} />);+ fireEvent.click(await screen.findByRole('button', { name: 'settings.providers.wizard.next' }));+ fireEvent.click(await screen.findByText('Only Codex'));+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.wizard.back' }));+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.wizard.back' }));+ const runtimes = onReturnCustom.mock.calls[0][0].config.runtimes;+ expect(runtimes.pi.models.some((m: { id: string }) => m.id === 'codex-exclusive')).toBe(false);+ expect(runtimes.codex.models.find((m: { id: string }) => m.id === 'codex-exclusive')).toMatchObject({ discoveredMetadata: { contextWindow: 50000 } });+ });+ it('retains a non-active engine URL edited inside the identified wizard when returning', async () => {+ const onReturnCustom = vi.fn();+ const codexUrl = 'https://relay.example/codex/v1';+ const handoff = { ...detected, preset: { ...detected.preset, runtimes: { ...detected.preset.runtimes,+ codex: { ...detected.preset.runtimes.pi, baseUrl: codexUrl },+ } }, config: { ...detected.config, runtimes: { ...detected.config.runtimes, codex: { ...detected.config.runtimes.pi } } } };+ render(<AddProviderWizard providers={[]} detected={handoff} onReturnCustom={onReturnCustom} onClose={vi.fn()} onDone={vi.fn()} onOpenCustomForm={vi.fn()} />);+ fireEvent.change(await screen.findByDisplayValue(codexUrl), { target: { value: 'https://edited.example/v1' } });+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.wizard.back' }));+ expect(onReturnCustom.mock.calls[0][0].config.runtimes.codex.baseUrl).toBe('https://edited.example/v1');+ expect(onReturnCustom.mock.calls[0][0].config.runtimes.pi.baseUrl).toBe(detected.config.runtimes.pi.baseUrl);+ });+ it('returns shared URL/key edits without replacing an independent engine draft', async () => {+ const onReturnCustom = vi.fn();+ const shared = detected.config.runtimes.pi;+ const handoff = { ...detected, keys: { pi: 'fake-key', codex: 'fake-key', 'claude-code': 'independent-key' },+ config: { ...detected.config, runtimes: { pi: shared, codex: { ...shared },+ 'claude-code': { baseUrl: 'https://independent.example/anthropic', models: [{ id: 'own-model', name: 'Own' }] },+ } },+ };+ render(<AddProviderWizard providers={[]} detected={handoff} onReturnCustom={onReturnCustom} onClose={vi.fn()} onDone={vi.fn()} onOpenCustomForm={vi.fn()} />);+ fireEvent.change(await screen.findByPlaceholderText('sk-…'), { target: { value: 'edited-fake-key' } });+ fireEvent.change(screen.getByDisplayValue(shared.baseUrl), { target: { value: 'https://new-relay.example/v1' } });+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.wizard.back' }));+ const returned = onReturnCustom.mock.calls[0][0];+ expect(returned.keys).toEqual({ pi: 'edited-fake-key', codex: 'edited-fake-key', 'claude-code': 'independent-key' });+ expect(returned.config.runtimes.codex.baseUrl).toBe('https://new-relay.example/v1');+ expect(returned.config.runtimes['claude-code']).toEqual(handoff.config.runtimes['claude-code']);+ expect(returned.catalog).toBeUndefined();+ });it('returns the draft instead of navigating to the provider gallery, keeping edited credentials', async () => {const onReturnCustom = vi.fn();render(<AddProviderWizard providers={[]} detected={detected} onReturnCustom={onReturnCustom} onClose={vi.fn()} onDone={vi.fn()} onOpenCustomForm={vi.fn()} />);diff --git a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsxindex a4a7252630..c5a1821bd8 100644--- a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx+++ b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx@@ -1025,12 +1025,16 @@ export function AddProviderWizard({}}if (detected) {- const selected = detected.config.runtimes[detected.agent]?.models ?? [];- for (const [id, value] of initial) initial.set(id, { ...value, checked: selected.some(m => m.id === id), recommended: false });- for (const m of selected) initial.set(m.id, { name: m.name, checked: true, recommended: false,- agents: [detected.agent], discoveredMetadata: { [detected.agent]: m.discoveredMetadata },- ...(m.route ? { routes: { [detected.agent]: m.route } } : {}),- });+ const selectedIds = new Set(agents.flatMap(agent => detected.config.runtimes[agent]?.models.map(m => m.id) ?? []));+ for (const [id, value] of initial) initial.set(id, { ...value, checked: selectedIds.has(id), recommended: false });+ for (const agent of agents) for (const m of detected.config.runtimes[agent]?.models ?? []) {+ const existing = initial.get(m.id);+ initial.set(m.id, { ...existing, name: m.name, checked: true, recommended: false,+ agents: [...new Set([...(existing?.agents ?? []), agent])],+ discoveredMetadata: { ...existing?.discoveredMetadata, [agent]: m.discoveredMetadata },+ ...(m.route ? { routes: { ...existing?.routes, [agent]: m.route } } : {}),+ });+ }}setPicks(previous => detected && previous.size ? previous : initial);setStep(3);@@ -1506,7 +1510,7 @@ export function AddProviderWizard({{/* 头部:标题居左 + 步骤指示居右,同一行(2026-07 定稿原型形态)。 */}<div className="flex items-center justify-between gap-4 px-4 pb-3 pt-4"><Dialog.Title asChild><h3- className="min-w-0 truncate text-16 font-medium"+ className="min-w-0 break-words text-16 font-medium"style={{ color: 'var(--settings-section-title)' }}>{sel@@ -2226,14 +2230,32 @@ export function AddProviderWizard({const editedBase = presetRuntimeBaseUrl(sel.preset, agent, presetBaseUrls);const previous = detected.config.runtimes[agent]!;const baseUrl = editedBase === detected.preset.runtimes[agent]?.baseUrl ? previous.baseUrl : editedBase;- const models = picks.size ? [...picks].filter(([, m]) => m.checked).map(([id, m]) => ({- ...previous.models.find(row => row.id === id), id, name: m.name,- discoveredMetadata: m.discoveredMetadata?.[agent],- })) : previous.models;+ const runtimes = { ...detected.config.runtimes };+ const keys = { ...detected.keys };+ for (const target of Object.keys(runtimes) as AgentKind[]) {+ const original = runtimes[target]!;+ const followsAddress = original.baseUrl === previous.baseUrl;+ const bound = sel.preset.runtimes[target];+ const targetInput = bound ? presetRuntimeBaseUrl(sel.preset, target, presetBaseUrls) : undefined;+ const targetBase = targetInput && targetInput !== bound?.baseUrl ? targetInput+ : followsAddress ? baseUrl : original.baseUrl;+ const models = bound && picks.size ? [...picks]+ .filter(([, model]) => model.checked && model.agents.includes(target))+ .map(([id, model]) => {+ const saved = original.models.find(row => row.id === id);+ return { ...saved, id, name: model.name,+ discoveredMetadata: model.discoveredMetadata?.[target] ?? saved?.discoveredMetadata,+ ...(saved?.route ?? model.routes?.[target] ? { route: saved?.route ?? model.routes?.[target] } : {}),+ };+ }) : original.models;+ runtimes[target] = { ...original, baseUrl: targetBase,+ models: modelsAfterProviderEndpointEdit(models, original.baseUrl, targetBase),+ };+ if (target === agent || keys[target] === detected.apiKey) keys[target] = apiKey;+ }onReturnCustom({ ...detected, apiKey,catalog: apiKey === detected.apiKey && editedBase === detected.preset.runtimes[agent]?.baseUrl ? detected.catalog : undefined,- keys: { ...detected.keys, [agent]: apiKey },- config: { ...detected.config, name, runtimes: { ...detected.config.runtimes, [agent]: { ...previous, baseUrl, models: modelsAfterProviderEndpointEdit(models, previous.baseUrl, baseUrl) } } } });+ keys, config: { ...detected.config, name, runtimes } });return;}if (step === 3) {diff --git a/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx b/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsxindex ce521eefa6..5fc53382cb 100644--- a/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx+++ b/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx@@ -158,6 +158,22 @@ function defaultWireFor(agent: DialogAgentKind): ProviderWireProtocol {return 'openai-responses';}+function modelTypeLabelKey(mode: string | undefined): string {+ if (mode === 'chat') return 'settings.providers.models.kindFilter.chat';+ const category: Record<string, string> = {+ image_generation: 'image', video_generation: 'video', audio_speech: 'tts',+ audio_transcription: 'stt', audio_generation: 'audio', realtime: 'realtime', embedding: 'embedding',+ };+ return mode && category[mode] ? `newChat.modelSelector.category.${category[mode]}`+ : 'settings.providers.connection.modelTypeAutomatic';+}++function bindAddPageProvider(preset: ProviderPreset, baseUrl: string): ProviderPreset | undefined {+ const runtimes = Object.assign({}, ...AGENTS.map(agent =>+ bindDetectedProvider(preset, agent, baseUrl)?.runtimes ?? {}));+ return Object.keys(runtimes).length ? { ...preset, runtimes } : undefined;+}+interface ProviderConnectionDialogProps {draft?: DetectedProviderDraft;onDetected?: (draft: DetectedProviderDraft) => void;@@ -211,6 +227,14 @@ interface RuntimeFields extends RuntimeFillDraft {videoApi?: 'xai-videos';}+function followsDefaultConnection(agent: DialogAgentKind, value: RuntimeFields, source: RuntimeFields): boolean {+ return value.baseUrl.trim() === source.baseUrl.trim() && value.apiKey === source.apiKey &&+ JSON.stringify(value.headers) === JSON.stringify(source.headers) &&+ JSON.stringify(value.models) === JSON.stringify(source.models) &&+ value.wireProtocol === defaultWireFor(agent) && !value.requestPath && !value.modelsUrl &&+ !value.catalogPresetId && !value.piCatalogProviderId && !value.imageApi && !value.videoApi && !value.supportsImageGeneration;+}+function runtimeProbeFields(agent: DialogAgentKind,runtime: RuntimeFields,@@ -432,6 +456,8 @@ export function ProviderConnectionDialog({const onClose = useCallback(() => dialog.close(notifyClosed), [dialog.close, notifyClosed]);const onSaved = useCallback(() => dialog.close(notifySaved), [dialog.close, notifySaved]);const editing = !!initial;+ const simpleAdding = !editing && !!onDetected;+ const [manualOpen, setManualOpen] = useState(false);const catalogModelsRef = useRef(catalogModels);const initialOAuth = initial?.auth?.method === 'oauth' ? initial.auth.oauth : undefined;@@ -468,13 +494,21 @@ export function ProviderConnectionDialog({const [manualModelMode, setManualModelMode] = useState('inherit');const [rt, setRt] = useState<Record<DialogAgentKind, RuntimeFields>>(() => {const fields = initRuntimes(initial ?? draft?.config);- if (draft) for (const a of AGENTS) fields[a].apiKey = draft.keys?.[a] ?? (a === draft.agent ? draft.apiKey : '');+ if (simpleAdding && !draft) for (const a of AGENTS) fields[a].headers = [];+ if (draft) {+ for (const a of AGENTS) fields[a].apiKey = draft.keys?.[a] ?? (a === draft.agent ? draft.apiKey : '');+ if (simpleAdding) for (const a of AGENTS) if (!draft.config.runtimes[a]) {+ const source = fields[draft.agent as DialogAgentKind];+ fields[a] = { ...fields[a], baseUrl: source.baseUrl, apiKey: source.apiKey,+ headers: source.headers, models: source.models };+ }+ }return fields;});const [activeTab, setActiveTab] = useState<DialogAgentKind>(() =>draft?.agent ?? (focusAgent && VISIBLE_AGENTS.includes(focusAgent as DialogAgentKind) ? focusAgent as DialogAgentKind : null) ??- ((initial && VISIBLE_AGENTS.find((a) => initial.runtimes[a])) || 'claude-code'),+ ((initial && VISIBLE_AGENTS.find((a) => initial.runtimes[a])) || (simpleAdding ? 'pi' : 'claude-code')),);const [hasKey, setHasKey] = useState<Record<DialogAgentKind, boolean>>({'claude-code': false,@@ -717,7 +751,23 @@ export function ProviderConnectionDialog({fn: (prev: Record<DialogAgentKind, RuntimeFields>) => Record<DialogAgentKind, RuntimeFields>,) => {setRt((prev) => {- const updated = fn(prev);+ const updated = { ...fn(prev) };+ // The add page edits one default connection. Keep independently configured+ // draft fields, but let untouched engines follow this connection.+ if (simpleAdding) {+ const source = activeTab;+ for (const agent of AGENTS) {+ if (agent === source) continue;+ const next = { ...updated[agent] };+ for (const field of ['baseUrl', 'apiKey', 'headers', 'models'] as const) {+ if (JSON.stringify(prev[agent][field]) === JSON.stringify(prev[source][field]) &&+ JSON.stringify(updated[agent][field]) === JSON.stringify(prev[agent][field])) {+ Object.assign(next, { [field]: updated[source][field] });+ }+ }+ updated[agent] = next;+ }+ }const normalized = Object.fromEntries(AGENTS.map((agent) => [agent,@@ -742,7 +792,7 @@ export function ProviderConnectionDialog({return normalized;});},- [rowId],+ [rowId, simpleAdding, activeTab],);// 编辑态回填的已存明文 key(按 agent);测试连接据此判定凭证材料是否被改动。@@ -920,13 +970,18 @@ export function ProviderConnectionDialog({const enterDetectedProvider = useCallback((preset: ProviderPreset) => {if (savingRef.current || childLayerRef.current || runtimeFillRef.current) return;const context = detectionContext.current;- const agent = context.activeTab;- const fields = rtRef.current[agent];+ const sourceAgent = context.activeTab;+ const fields = rtRef.current[sourceAgent];+ const agent = preset.runtimes[sourceAgent] ? sourceAgent : AGENTS.find(a =>+ preset.runtimes[a] && followsDefaultConnection(a, rtRef.current[a], fields));+ if (!agent) return;const runtimes: CustomProviderConfig['runtimes'] = {};const keys: Partial<Record<AgentKind, string>> = {};for (const a of AGENTS) {const value = rtRef.current[a];if (!value.baseUrl.trim()) continue;+ const inherits = followsDefaultConnection(a, value, fields);+ if (!preset.runtimes[a] && inherits) continue;keys[a] = value.apiKey;runtimes[a] = { baseUrl: value.baseUrl.trim(), models: value.models.filter(m => m.id.trim()),wireProtocol: customProviderWireProtocolForSave(a, value.wireProtocol, defaultWireFor(a)),@@ -940,21 +995,31 @@ export function ProviderConnectionDialog({...(a === 'codex' && value.supportsImageGeneration && canRuntimeUseNativeImageGeneration(value) ? { supportsImageGeneration: true } : {}),};}- const runtime = preset.runtimes[agent]!;- const bound = { ...preset, authMethod: authModeRef.current === 'none' ? 'none' as const : 'apiKey' as const,- runtimes: { [agent]: { ...runtime,- headers: { ...runtime.headers, ...runtimes[agent]?.headers },- ...(fields.requestPath ? { requestPath: fields.requestPath } : {}),- ...(fields.modelsUrl.trim() ? { modelsUrl: fields.modelsUrl.trim() } : {}),- ...(runtimes[agent]?.supportsImageGeneration ? { supportsImageGeneration: true } : {}),- ...(fields.wireProtocol !== defaultWireFor(agent) || runtimes[agent]?.supportsImageGeneration ? { wireProtocol: fields.wireProtocol } : {}),- } } };+ const bound: ProviderPreset = { ...preset, authMethod: authModeRef.current === 'none' ? 'none' : 'apiKey',+ runtimes: Object.fromEntries(AGENTS.flatMap(a => {+ const runtime = preset.runtimes[a];+ if (!runtime) return [];+ const value = rtRef.current[a];+ const independent = a !== sourceAgent && !followsDefaultConnection(a, value, fields);+ // The existing wizard has one shared key. Never enroll independent+ // drafts into its fetch/save loop; they remain in config/keys untouched.+ if (independent) return [];+ // Inherited connections use each engine's provider defaults.+ return [[a, { ...runtime,+ headers: { ...runtime.headers, ...runtimes[a]?.headers },+ ...(value.requestPath ? { requestPath: value.requestPath } : {}),+ ...(value.modelsUrl.trim() ? { modelsUrl: value.modelsUrl.trim() } : {}),+ ...(runtimes[a]?.supportsImageGeneration ? { supportsImageGeneration: true } : {}),+ ...(value.wireProtocol !== defaultWireFor(a) || runtimes[a]?.supportsImageGeneration ? { wireProtocol: value.wireProtocol } : {}),+ }]];+ })),+ };// The cache is settled before announcing a match; no credentials enter saved detection data.- const cache = discoveryCache.current.get(agent);+ const cache = discoveryCache.current.get(sourceAgent);void (cache?.signature === context.signature ? cache.promise : Promise.resolve(undefined)).then(catalog => {if (detectionContext.current.signature !== context.signature || savingRef.current || childLayerRef.current || runtimeFillRef.current) return;context.onDetected?.({ preset: bound, agent, apiKey: fields.apiKey, keys, catalog,- config: { id: 'draft', name: context.name, auth: { method: bound.authMethod }, runtimes } });+ config: { id: 'draft', name: context.name, auth: { method: bound.authMethod ?? 'apiKey' }, runtimes } });});}, []);@@ -990,18 +1055,21 @@ export function ProviderConnectionDialog({authMethod: authMode, headers, wireProtocol: fields.wireProtocol };const work = (async () => {if (official.length) {- const preset = official.length === 1 ? bindDetectedProvider(official[0], agent, spec.baseUrl) : undefined;+ const preset = official.length === 1 ? bindAddPageProvider(official[0], spec.baseUrl) : undefined;if (!preset) return { preset, ambiguous: official.length > 1, catalog: undefined };- const runtime = preset.runtimes[agent]!;- const catalog = await window.electronAPI.maker.fetchProviderModels({ ...spec,+ const fetchAgent = preset.runtimes[agent] ? agent : AGENTS.find(a =>+ preset.runtimes[a] && followsDefaultConnection(a, rtRef.current[a], fields));+ if (!fetchAgent) return { preset: undefined, catalog: undefined };+ const runtime = preset.runtimes[fetchAgent]!;+ const catalog = await window.electronAPI.maker.fetchProviderModels({ ...spec, agent: fetchAgent,allowEmpty: true, redirect: 'error',- baseUrl: runtime.baseUrl, modelsUrl: fields.modelsUrl.trim() || runtime.modelsUrl, wireProtocol: runtime.wireProtocol ?? defaultWireFor(agent),+ baseUrl: runtime.baseUrl, modelsUrl: fields.modelsUrl.trim() || runtime.modelsUrl, wireProtocol: runtime.wireProtocol ?? defaultWireFor(fetchAgent),headers: { ...runtime.headers, ...headers } });return { preset, catalog };}const result = await window.electronAPI.maker.detectProvider?.({ ...spec, requestId });const preset = result?.candidates.length === 1 ? all.find(p => p.id === result.candidates[0]) : undefined;- return { preset: preset && bindDetectedProvider(preset, agent, spec.baseUrl), catalog: result?.catalog, ambiguous: result?.reason === 'conflict' };+ return { preset: preset && bindAddPageProvider(preset, spec.baseUrl), catalog: result?.catalog, ambiguous: result?.reason === 'conflict' };})().catch(() => ({ preset: undefined, catalog: undefined, ambiguous: false }));discoveryCache.current.set(agent, { signature, promise: work.then(r => r.catalog ?? { ok: false }) });void work.then(({ preset, catalog, ambiguous }) => {@@ -1016,6 +1084,8 @@ export function ProviderConnectionDialog({})),] } }));}+ if (preset && !AGENTS.some(a => preset!.runtimes[a] &&+ (a === agent || followsDefaultConnection(a, rtRef.current[a], rtRef.current[agent])))) preset = undefined;setDetection({ signature, preset, ambiguous, code: catalog && !catalog.ok ? (catalog.code ?? 'UNKNOWN') : undefined });if (preset && !detectionSuppressed.current) jump = setTimeout(() => {if (live && !detectionSuppressed.current && detectionContext.current.signature === signature) enterDetectedProvider(preset);@@ -1832,6 +1902,7 @@ export function ProviderConnectionDialog({}// OAuth 形态模型可留空——授权成功后自动发现并持久化(与内置订阅统一)。if (models.length === 0 && authMode !== 'oauth') {+ setManualOpen(true);setActiveTab(a);reportFieldError(`${a}:manualModel`,@@ -2217,14 +2288,14 @@ export function ProviderConnectionDialog({</div>{/* Body (scrollable) */}- <div className="flex min-h-0 flex-col gap-4 overflow-y-auto px-4 pb-2 pt-1">+ <div className="flex min-h-0 flex-col gap-5 overflow-y-auto px-4 pb-4"><p className="text-13 leading-[1.55] text-[var(--settings-section-desc)]">{t('settings.providers.custom.dialog.desc')}</p>{/* 预设模板(仅新建态、有预设时显示):下拉选择,选中即预填 baseUrl / 模型清单,用户只补 key。列表已按厂商首字母分组排序(同厂商国内/海外相邻,按构建区域排序)。 */}- {!editing && presets.length > 0 && (+ {!editing && !simpleAdding && presets.length > 0 && (<div className="flex flex-col gap-2"><FieldLabel>{t('settings.providers.custom.presets.label')}</FieldLabel><PresetDropdown@@ -2247,23 +2318,12 @@ export function ProviderConnectionDialog({</div>)}- {!editing && detection?.signature === detectionSignature && (- <div className="flex flex-col gap-2 rounded-xl border border-[var(--border-default)] p-3 text-13 text-[var(--text-secondary)]" role="status">- <span>{detection.pending ? t('settings.providers.detection.pending') : detection.preset- ? t('settings.providers.detection.matched', { name: presetDisplayName(detection.preset, i18n.language) })- : t(detection.ambiguous ? 'settings.providers.detection.ambiguous' : 'settings.providers.detection.custom')}</span>- {detection.code && <span className="text-[var(--error-fg)]">{t(`providerError.${detection.code}`)}</span>}- {detection.preset && <div className="flex flex-wrap gap-2">- <Button type="button" variant="secondary" onClick={() => enterDetectedProvider(detection.preset!)}>{t('settings.providers.detection.configure')}</Button>- <Button type="button" variant="secondary" tone="quiet" onClick={() => { detectionSuppressed.current = true; setDetection(null); }}>{t('settings.providers.detection.keepCustom')}</Button>- </div>}- </div>- )}{/* 显示名称(共享) */}<div className="flex flex-col gap-[7px]"><FormFieldid={fieldId('name')}label={t('settings.providers.custom.fields.name')}+ className={simpleAdding ? '[&>div>p:last-child]:!min-h-4' : undefined}error={errorFor('name')}requiredreserveFeedback@@ -2272,6 +2332,7 @@ export function ProviderConnectionDialog({<SettingsTextInput{...control}surface="ivory"+ size={simpleAdding ? 'md' : undefined}value={name}onChange={setName}placeholder={t('settings.providers.custom.fields.namePlaceholder')}@@ -2282,7 +2343,7 @@ export function ProviderConnectionDialog({{/* 鉴权形态:API 密钥 / OAuth / 无鉴权。 */}{!initial?.auth?.native && <>- <div className="flex flex-col gap-2">+ {!simpleAdding && <div className="flex flex-col gap-2"><FieldLabel>{t('settings.providers.custom.authMode.label')}</FieldLabel><SegmentedControlaria-label={t('settings.providers.custom.authMode.label')}@@ -2357,10 +2418,10 @@ export function ProviderConnectionDialog({{t('settings.providers.custom.authMode.noneHelp')}</span>)}- </div>+ </div>}{/* Runtime 分段 Tab:Claude Code 与 Codex 各自维护端点、协议、模型与凭证。 */}- <div className="flex flex-col gap-2">+ {!simpleAdding && <div className="flex flex-col gap-2"><FieldLabel>{t('settings.providers.custom.fields.protocols')}</FieldLabel><SegmentedControlrole="tablist"@@ -2394,7 +2455,7 @@ export function ProviderConnectionDialog({<span className="text-12 leading-snug text-[var(--text-tertiary)]">{templateBound ? (boundPreset ? presetDisplayName(boundPreset, i18n.language) : name) : t(!editing && onDetected ? 'settings.providers.detection.hint' : TAB_META[activeTab].helpKey)}</span>- </div>+ </div>}{/* 当前 Tab 的独立配置面板 */}<div@@ -2464,7 +2525,7 @@ export function ProviderConnectionDialog({id={fieldId(`${activeTab}:baseUrl`)}label={t('settings.providers.custom.fields.baseUrl')}error={errorFor(`${activeTab}:baseUrl`)}- labelAction={!templateBound && (+ labelAction={!simpleAdding && !templateBound && (<buttonref={runtimeFillTriggerRef}type="button"@@ -2474,12 +2535,13 @@ export function ProviderConnectionDialog({{t('settings.providers.custom.runtimeFill.action')}</button>)}- reserveFeedback+ reserveFeedback={!simpleAdding}>{(control) => (<SettingsTextInput{...control}surface="ivory"+ size={simpleAdding ? 'md' : undefined}value={displayedBaseUrl}readOnly={fixedTemplateEndpoint}onChange={(v) => {@@ -2525,7 +2587,7 @@ export function ProviderConnectionDialog({id={fieldId(`${activeTab}:apiKey`)}label={t('settings.providers.custom.fields.apiKey')}error={errorFor(`${activeTab}:apiKey`)}- hint={t('settings.providers.custom.fields.apiKeyHelp')}+ hint={simpleAdding ? undefined : t('settings.providers.custom.fields.apiKeyHelp')}labelAction={activeKeyCanRemainSaved &&f.apiKey.trim() && (@@ -2547,13 +2609,14 @@ export function ProviderConnectionDialog({{...control}key={activeTab}surface="ivory"+ size={simpleAdding ? 'md' : undefined}value={f.apiKey}onChange={(v) => {keyEditRevisionRef.current[activeTab] += 1;patch(activeTab, (x) => ({ ...x, apiKey: v }));}}placeholder={keyPlaceholder}- mono+ mono={!simpleAdding}secretsecretTipContentClassName="z-[10001]"/>@@ -2562,6 +2625,18 @@ export function ProviderConnectionDialog({</div>)}+ {!editing && detection?.signature === detectionSignature && (+ <div className="flex flex-col gap-2 rounded-xl border border-[var(--border-default)] p-3 text-13 text-[var(--text-secondary)]" role="status">+ <span>{detection.pending ? t('settings.providers.detection.pending') : detection.preset+ ? t('settings.providers.detection.matched', { name: presetDisplayName(detection.preset, i18n.language) })+ : t(detection.ambiguous ? 'settings.providers.detection.ambiguous' : 'settings.providers.detection.custom')}</span>+ {detection.code && <span className="text-[var(--error-fg)]">{t(`providerError.${detection.code}`)}</span>}+ {detection.preset && <div className="flex flex-wrap gap-2">+ <Button type="button" variant="secondary" onClick={() => enterDetectedProvider(detection.preset!)}>{t('settings.providers.detection.configure')}</Button>+ <Button type="button" variant="secondary" tone="quiet" onClick={() => { detectionSuppressed.current = true; setDetection(null); }}>{t('settings.providers.detection.keepCustom')}</Button>+ </div>}+ </div>+ )}{/* OAuth 形态:模型清单授权成功后自动发现(与内置订阅统一),模型 / 请求头收进默认折叠的「高级配置」——普通用户不需要看到这些字段。 */}{authMode === 'oauth' && (@@ -2587,8 +2662,31 @@ export function ProviderConnectionDialog({<><div className="flex flex-col gap-2 text-13 text-[var(--text-secondary)]"><span>{t('settings.providers.connection.modelCount', { count: f.models.filter((model) => model.id.trim()).length })}</span>- <span className="text-12">{t('settings.providers.connection.modelsAutomatic')}</span>- <FormField id={fieldId(`${activeTab}:manualModel`)} label={t('settings.providers.connection.manualModel')} error={errorFor(`${activeTab}:manualModel`)}>+ {!simpleAdding && <span className="text-12">{t('settings.providers.connection.modelsAutomatic')}</span>}+ {simpleAdding && <>+ {f.models.filter(model => model.id.trim()).map(model => (+ <div key={model.id} className="flex items-center justify-between gap-2 border-b border-[var(--border-default)] py-2">+ <span className="min-w-0 break-words text-[var(--text-primary)]">+ {model.id}{' '}+ <span className="inline-flex rounded-full border border-[var(--border-default)] px-2 py-0.5 text-11 text-[var(--text-secondary)]">+ {t(modelTypeLabelKey(model.mode ?? model.discoveredMetadata?.mode))}+ </span>+ </span>+ <Button type="button" variant="secondary" size="sm" className="shrink-0"+ onClick={() => patch(activeTab, value => ({ ...value, models: value.models.filter(row => row.id !== model.id) }))}>+ {t('settings.providers.connection.removeModel')}+ </Button>+ </div>+ ))}+ <Button type="button" variant="secondary" className="w-full justify-between [--button-face-bg:transparent]"+ aria-expanded={manualOpen} aria-controls={fieldId('manual-fields')}+ onClick={() => setManualOpen(open => !open)}>+ {t('settings.providers.connection.manualAdd')}+ <ChevronDown size={14} aria-hidden className={cn('shrink-0', manualOpen && 'rotate-180')} />+ </Button>+ </>}+ {(!simpleAdding || manualOpen) && <div id={fieldId('manual-fields')} className="flex flex-col gap-3">+ <FormField id={fieldId(`${activeTab}:manualModel`)} label={t(simpleAdding ? 'settings.providers.connection.manualId' : 'settings.providers.connection.manualModel')} error={errorFor(`${activeTab}:manualModel`)}>{(control) => (<SettingsTextInput {...control} surface="ivory" value={manualModel}onChange={setManualModel} />@@ -2623,10 +2721,11 @@ export function ProviderConnectionDialog({setManualModelMode('inherit');setFieldError(null);}}>{t('settings.providers.custom.fields.addModel')}</Button>+ </div>}</div>{/* 请求头(可选) */}- <div className="flex flex-col gap-2">+ <div className={cn('flex flex-col gap-3', simpleAdding && 'border-t border-[var(--border-default)] pt-4')}><div className="flex items-center gap-2"><FieldLabel>{t('settings.providers.custom.fields.headers')}</FieldLabel>{/* 已存密文头时给明确徽标 —— 明文不回读进 renderer,无徽标会让人误以为没存上。 */}@@ -2738,14 +2837,14 @@ export function ProviderConnectionDialog({patch(activeTab, (x) => ({ ...x, headers: [...x.headers, row] }));requestAnimationFrame(() => document.getElementById(nextId)?.focus());}}- className="flex items-center gap-1.5 self-start py-0.5 text-13 font-medium text-[var(--settings-section-title)]"+ className={cn('flex items-center gap-1.5 self-start text-13 font-medium text-[var(--settings-section-title)]', simpleAdding ? 'h-8 rounded-full border border-[var(--border-default)] px-4' : 'py-0.5')}><Plus size={14} className="text-[var(--settings-section-desc)]" />{t('settings.providers.custom.fields.addHeader')}</button></div>- {authMode !== 'oauth' && (+ {!simpleAdding && authMode !== 'oauth' && (<div className="flex flex-col gap-1.5 border-t border-[var(--border-default)] pt-3"><label className="flex cursor-pointer items-center gap-2 text-13 text-[var(--settings-section-title)]"><input@@ -2778,7 +2877,7 @@ export function ProviderConnectionDialog({</div>)}- {authMode !== 'oauth' && (+ {!simpleAdding && authMode !== 'oauth' && (<div className="flex flex-col gap-1.5 border-t border-[var(--border-default)] pt-3"><label className="flex cursor-pointer items-center gap-2 text-13 text-[var(--settings-section-title)]"><input@@ -2813,7 +2912,7 @@ export function ProviderConnectionDialog({{/* Codex Responses Provider 级能力。放在自定义请求头之后,默认收起;同一张说明卡片支持 hover/focus 临时预览和 click/tap 固定。 */}- {canShowImageGenerationAdvanced && (+ {!simpleAdding && canShowImageGenerationAdvanced && (<div className="flex flex-col gap-2 border-t border-[var(--border-default)] pt-3"><buttontype="button"@@ -2954,7 +3053,7 @@ export function ProviderConnectionDialog({{/* 预设模板(仅新建态、有预设时显示):下拉选择,选中即预填 baseUrl / 模型清单,用户只补 key。列表已按厂商首字母分组排序(同厂商国内/海外相邻,按构建区域排序)。 */}{authMode !== 'oauth' && (- <div className="flex min-h-[32px] flex-wrap items-center gap-2.5">+ <div className="flex min-h-[32px] flex-wrap items-center gap-2.5 border-t border-[var(--border-default)] pt-4">{!mediaOnly && <Buttonvariant="secondary"size="sm"@@ -3008,7 +3107,7 @@ export function ProviderConnectionDialog({</div>{/* Footer: only the save request owns this busy state. */}- <div className="flex shrink-0 flex-wrap justify-end gap-2.5 p-4">+ <div className="flex shrink-0 flex-wrap justify-end gap-2.5 border-t border-[var(--border-default)] p-4"><Buttonvariant="secondary"size="lg"@@ -3022,14 +3121,14 @@ export function ProviderConnectionDialog({</Button><Buttonref={saveButtonRef}- variant="primary"+ variant={simpleAdding ? 'cta' : 'primary'}size="lg"loading={saving}onClick={() => void handleSave()}- palette="confirmation"+ palette={simpleAdding ? 'default' : 'confirmation'}className="min-w-[96px]">- {t('settings.providers.custom.save')}+ {t(simpleAdding ? 'settings.providers.connection.saveProvider' : 'settings.providers.custom.save')}</Button></div></Dialog.Content>diff --git a/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsxindex 3a6edd9bc6..a2afd61e82 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx@@ -3,7 +3,7 @@ import { useRef, useState } from 'react';import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';-import { buildUserProvider, type CustomProviderConfig, type ModelRegistry } from '@cindy/model-providers';+import { buildUserProvider, type CustomProviderConfig, type ProviderPreset, type ModelRegistry } from '@cindy/model-providers';import { customProviderModelConfigFromCatalogModel } from '@/lib/customProviders';import { ProviderConnectionDialog } from '../ProviderConnectionDialog';@@ -2087,11 +2087,11 @@ it('main provider form contains Tab and blocks dismissal only during the actualdescribe('new-connection identification', () => {afterEach(() => { cleanup(); vi.useRealTimers(); });const preset = { id: 'deepseek', name: 'DeepSeek', runtimes: { pi: { baseUrl: 'https://api.deepseek.com', wireProtocol: 'openai-chat' as const, models: [] } } };- async function openIdentification() {+ async function openIdentification(available: ProviderPreset = preset) {vi.useFakeTimers();const fetchProviderModels = vi.fn(async () => ({ ok: true, models: [{ id: 'private-model', name: 'Model' }] }));Object.assign(window.electronAPI.maker, {- listProviderPresets: vi.fn(async () => ({ presets: [preset] })), fetchProviderModels,+ listProviderPresets: vi.fn(async () => ({ presets: [available] })), fetchProviderModels,detectProvider: vi.fn(async () => ({ candidates: [], reason: 'insufficient_evidence', catalog: { ok: true, models: [{ id: 'custom-model', name: 'Custom' }] } })),});const onDetected = vi.fn();@@ -2113,6 +2113,163 @@ describe('new-connection identification', () => {expect(fetchProviderModels).toHaveBeenCalledOnce();expect(customProviderMocks.createCustomProvider).not.toHaveBeenCalled();});+ it('uses the HTML add layout and saves the shared connection with each engine default', async () => {+ await openIdentification();+ expect(screen.queryByRole('tablist')).toBeNull();+ expect(screen.queryByText('settings.providers.custom.authMode.label')).toBeNull();+ expect(screen.queryByText('settings.providers.custom.presets.label')).toBeNull();+ expect(screen.queryByLabelText('settings.providers.connection.manualId')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.detection.keepCustom' }));+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.connection.removeModel' }));+ expect(screen.queryByText('private-model')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.connection.manualAdd' }));+ fireEvent.change(screen.getByLabelText('settings.providers.connection.manualId'), { target: { value: 'my-model' } });+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.fields.addModel' }));+ expect(screen.getByText('my-model')).toBeTruthy();+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.namePlaceholder'), { target: { value: 'My custom' } });+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.connection.saveProvider' }));+ await act(async () => {});+ expect(customProviderMocks.createCustomProvider).toHaveBeenCalledOnce();+ const [config, keys] = customProviderMocks.createCustomProvider.mock.calls[0];+ for (const [agent, protocol] of [['claude-code', 'anthropic-messages'], ['codex', 'openai-responses'], ['pi', 'openai-chat']]) {+ expect(config.runtimes[agent]).toMatchObject({ baseUrl: 'https://api.deepseek.com', models: [{ id: 'my-model' }] });+ expect(config.runtimes[agent].wireProtocol).toBe(agent === 'pi' ? protocol : undefined);+ expect(keys[agent]).toBe('fake-key');+ }+ });+ it('binds each supported engine to the identified provider instead of copying the active protocol', async () => {+ const available: ProviderPreset = { ...preset, runtimes: {+ ...preset.runtimes,+ 'claude-code': { baseUrl: 'https://api.deepseek.com/anthropic', wireProtocol: 'anthropic-messages', models: [] },+ codex: { baseUrl: 'https://api.deepseek.com', wireProtocol: 'openai-chat', models: [] },+ } };+ const { onDetected } = await openIdentification(available);+ await act(async () => { await vi.advanceTimersByTimeAsync(1200); });+ const value = onDetected.mock.calls[0][0];+ expect(value.preset.runtimes['claude-code']).toMatchObject({ baseUrl: 'https://api.deepseek.com/anthropic', wireProtocol: 'anthropic-messages' });+ expect(value.preset.runtimes.codex.wireProtocol).toBe('openai-chat');+ expect(value.preset.runtimes.pi.wireProtocol).toBe('openai-chat');+ });+ it('identifies a provider supported only by another engine without asking the user to choose an engine', async () => {+ vi.useFakeTimers();+ const onlyClaude: ProviderPreset = { ...preset, runtimes: {+ 'claude-code': { baseUrl: 'https://api.deepseek.com', wireProtocol: 'anthropic-messages', models: [] },+ } };+ Object.assign(window.electronAPI.maker, {+ listProviderPresets: vi.fn(async () => ({ presets: [onlyClaude] })),+ fetchProviderModels: vi.fn(async () => ({ ok: true, models: [{ id: 'one', name: 'One' }] })),+ });+ const onDetected = vi.fn();+ render(<ProviderConnectionDialog onDetected={onDetected} onClose={vi.fn()} onSaved={vi.fn()} />);+ await act(async () => {});+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: 'https://api.deepseek.com' } });+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder'), { target: { value: 'fake-key' } });+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });+ expect(onDetected).toHaveBeenCalledOnce();+ const draft = onDetected.mock.calls[0][0];+ expect(draft.agent).toBe('claude-code');+ expect(Object.keys(draft.config.runtimes)).toEqual(['claude-code']);+ expect(window.electronAPI.maker.fetchProviderModels).toHaveBeenCalledWith(expect.objectContaining({ agent: 'claude-code', wireProtocol: 'anthropic-messages' }));+ });+ it('keeps independent endpoint credentials out of the shared-key wizard', async () => {+ vi.useFakeTimers();+ const available: ProviderPreset = { ...preset, runtimes: { ...preset.runtimes,+ 'claude-code': { baseUrl: 'https://api.deepseek.com/anthropic', wireProtocol: 'anthropic-messages', models: [] },+ } };+ Object.assign(window.electronAPI.maker, {+ listProviderPresets: vi.fn(async () => ({ presets: [available] })),+ fetchProviderModels: vi.fn(async () => ({ ok: true, models: [{ id: 'source-model', name: 'Source' }] })),+ });+ const independent = { baseUrl: 'https://independent.example/anthropic', models: [{ id: 'own-model', name: 'Own' }] };+ const onDetected = vi.fn();+ render(<ProviderConnectionDialog onDetected={onDetected} onClose={vi.fn()} onSaved={vi.fn()}+ draft={{ preset: available, agent: 'pi', apiKey: 'source-key', keys: { pi: 'source-key', 'claude-code': 'independent-key' },+ config: { id: 'draft', name: 'Shared', runtimes: { pi: { baseUrl: 'https://api.deepseek.com', models: [] }, 'claude-code': independent } } }} />);+ await act(async () => {});+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.detection.configure' }));+ await act(async () => {});+ const value = onDetected.mock.calls[0][0];+ expect(value.preset.runtimes['claude-code']).toBeUndefined();+ expect(value.config.runtimes['claude-code']).toMatchObject(independent);+ expect(value.keys['claude-code']).toBe('independent-key');+ expect(window.electronAPI.maker.fetchProviderModels).toHaveBeenCalledOnce();+ expect(window.electronAPI.maker.fetchProviderModels).toHaveBeenCalledWith(expect.objectContaining({ baseUrl: 'https://api.deepseek.com', apiKey: 'source-key' }));+ });+ it('does not hand off to an independently configured fallback engine', async () => {+ vi.useFakeTimers();+ const available: ProviderPreset = { ...preset, runtimes: {+ 'claude-code': { baseUrl: 'https://api.deepseek.com', wireProtocol: 'anthropic-messages', models: [] },+ } };+ Object.assign(window.electronAPI.maker, {+ listProviderPresets: vi.fn(async () => ({ presets: [available] })),+ fetchProviderModels: vi.fn(async () => ({ ok: true, models: [] })),+ });+ const onDetected = vi.fn();+ render(<ProviderConnectionDialog onDetected={onDetected} onClose={vi.fn()} onSaved={vi.fn()}+ draft={{ preset: available, agent: 'pi', apiKey: 'source-key', keys: { pi: 'source-key', 'claude-code': 'independent-key' },+ config: { id: 'draft', name: 'Shared', runtimes: {+ pi: { baseUrl: 'https://api.deepseek.com', models: [] },+ 'claude-code': { baseUrl: 'https://private.example', models: [] },+ } } }} />);+ await act(async () => {});+ await act(async () => { await vi.advanceTimersByTimeAsync(2000); });+ expect(onDetected).not.toHaveBeenCalled();+ expect(screen.queryByRole('button', { name: 'settings.providers.detection.configure' })).toBeNull();+ });+ it('fetches the catalog with the same inheriting engine used for handoff', async () => {+ vi.useFakeTimers();+ const available: ProviderPreset = { ...preset, runtimes: {+ 'claude-code': { baseUrl: 'https://api.deepseek.com', wireProtocol: 'anthropic-messages', models: [] },+ codex: { baseUrl: 'https://api.deepseek.com', wireProtocol: 'openai-responses', models: [] },+ } };+ const fetchProviderModels = vi.fn(async ({ agent }) => ({ ok: true, models: [{ id: agent + '-model', name: agent }] }));+ Object.assign(window.electronAPI.maker, {+ listProviderPresets: vi.fn(async () => ({ presets: [available] })), fetchProviderModels,+ });+ const onDetected = vi.fn();+ render(<ProviderConnectionDialog onDetected={onDetected} onClose={vi.fn()} onSaved={vi.fn()}+ draft={{ preset: available, agent: 'pi', apiKey: 'source-key', keys: { pi: 'source-key', 'claude-code': 'independent-key' },+ config: { id: 'draft', name: 'Shared', runtimes: {+ pi: { baseUrl: 'https://api.deepseek.com', models: [] },+ 'claude-code': { baseUrl: 'https://private.example', models: [] },+ } } }} />);+ await act(async () => {});+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.detection.configure' }));+ await act(async () => {});+ expect(fetchProviderModels).toHaveBeenCalledWith(expect.objectContaining({ agent: 'codex' }));+ expect(onDetected.mock.calls[0][0]).toMatchObject({ agent: 'codex', catalog: { models: [{ id: 'codex-model' }] } });+ });+ it('preserves unsupported engines with explicit request settings', async () => {+ vi.useFakeTimers();+ Object.assign(window.electronAPI.maker, {+ listProviderPresets: vi.fn(async () => ({ presets: [preset] })),+ fetchProviderModels: vi.fn(async () => ({ ok: true, models: [] })),+ });+ const independent = { baseUrl: 'https://api.deepseek.com', models: [], wireProtocol: 'openai-chat' as const, requestPath: '/special/chat' };+ const onDetected = vi.fn();+ render(<ProviderConnectionDialog onDetected={onDetected} onClose={vi.fn()} onSaved={vi.fn()}+ draft={{ preset, agent: 'pi', apiKey: 'source-key', keys: { pi: 'source-key', codex: 'source-key' },+ config: { id: 'draft', name: 'Shared', runtimes: { pi: { baseUrl: 'https://api.deepseek.com', models: [] }, codex: independent } } }} />);+ await act(async () => {});+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.detection.configure' }));+ await act(async () => {});+ expect(onDetected.mock.calls[0][0].config.runtimes.codex).toMatchObject(independent);+ expect(onDetected.mock.calls[0][0].preset.runtimes.codex).toBeUndefined();+ });+ it('opens manual entry and focuses its error when saving without models', async () => {+ await openIdentification();+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.detection.keepCustom' }));+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.connection.removeModel' }));+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.namePlaceholder'), { target: { value: 'My custom' } });+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.connection.saveProvider' }));+ await act(async () => {});+ expect(screen.getByLabelText('settings.providers.connection.manualId')).toBe(document.activeElement);+ expect(screen.getByText('settings.providers.custom.errors.modelRequired')).toBeTruthy();+ expect(customProviderMocks.createCustomProvider).not.toHaveBeenCalled();+ });it('keeps the user in custom settings after cancellation, including later input edits', async () => {const { onDetected } = await openIdentification();fireEvent.click(screen.getByRole('button', { name: 'settings.providers.detection.keepCustom' }));@@ -2128,13 +2285,17 @@ describe('new-connection identification', () => {fetchProviderModels: vi.fn(async () => ({ ok: true, models: [{ id: 'responses-model', name: 'Responses model' }] })),});const onDetected = vi.fn();- render(<ProviderConnectionDialog focusAgent="codex" onDetected={onDetected} onClose={vi.fn()} onSaved={vi.fn()} />);+ render(<ProviderConnectionDialog focusAgent="codex" onDetected={onDetected} onClose={vi.fn()} onSaved={vi.fn()}+ draft={{ agent: 'codex', preset: codexPreset, apiKey: '', config: { id: 'draft', name: '', runtimes: {+ codex: { baseUrl: '', wireProtocol: 'openai-responses', models: [], supportsImageGeneration: true },+ } } }} />);await act(async () => {});- fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.fields.runtimeAdvanced' }));- fireEvent.click(screen.getByRole('checkbox', { name: 'settings.providers.custom.fields.runtimeSupportsImageGeneration' }));+ expect(screen.queryByRole('button', { name: 'settings.providers.custom.fields.runtimeAdvanced' })).toBeNull();fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: 'https://api.deepseek.com' } });fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder'), { target: { value: 'fake-key' } });await act(async () => { await vi.advanceTimersByTimeAsync(1600); });+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.detection.configure' }));+ await act(async () => {});expect(onDetected).toHaveBeenCalledOnce();expect(onDetected.mock.calls[0][0].preset.runtimes.codex).toMatchObject({ supportsImageGeneration: true, wireProtocol: 'openai-responses' });expect(onDetected.mock.calls[0][0].config.runtimes.codex.supportsImageGeneration).toBe(true);diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 97fece84f3..0f07b8b650 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3757,6 +3757,10 @@"modelCount": "{{count}} models configured","modelsAutomatic": "Model details are imported automatically. Adjust individual models in the model list.","manualModel": "Model IDs (if discovery is unavailable)",+ "manualAdd": "Add a model manually",+ "manualId": "Model ID",+ "saveProvider": "Save provider",+ "removeModel": "Remove model","modelTypeAutomatic": "Detect Automatically","manualModelTypeHint": "Use the same ID to update its type. Automatic detection restores the catalog type.","mediaOnlyTestHint": "This connection has only non-chat models. Fetch the model list to check catalog access; model execution is not tested here."diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 18827d6469..8d01c6495e 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3726,6 +3726,10 @@"modelCount": "{{count}} 個のモデルを設定済み","modelsAutomatic": "モデル情報は自動取得されます。個別の設定はモデル一覧から変更できます。","manualModel": "モデル ID(自動取得できない場合)",+ "manualAdd": "モデルを手動で追加",+ "manualId": "モデル ID",+ "saveProvider": "プロバイダーを保存",+ "removeModel": "モデルを削除","modelTypeAutomatic": "自動判別","manualModelTypeHint": "同じ ID で種類を更新できます。自動判別を選ぶと、カタログの種類に戻ります。","mediaOnlyTestHint": "この接続にはチャット以外のモデルのみが含まれています。モデル一覧の取得でカタログへのアクセスを確認できます。ここではモデルの実行はテストしません。"diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex ec2998121e..f9cac15b64 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3726,6 +3726,10 @@"modelCount": "모델 {{count}}개 설정됨","modelsAutomatic": "모델 정보는 자동으로 가져옵니다. 개별 설정은 모델 목록에서 변경하세요.","manualModel": "모델 ID (자동으로 가져올 수 없는 경우)",+ "manualAdd": "모델 직접 추가",+ "manualId": "모델 ID",+ "saveProvider": "제공자 저장",+ "removeModel": "모델 제거","modelTypeAutomatic": "자동 감지","manualModelTypeHint": "같은 ID로 유형을 변경할 수 있습니다. 자동 감지를 선택하면 카탈로그의 유형으로 돌아갑니다.","mediaOnlyTestHint": "이 연결에는 채팅 이외의 모델만 있습니다. 모델 목록을 가져와 카탈로그 접근을 확인할 수 있습니다. 여기서는 모델 실행을 테스트하지 않습니다."diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 2da9c5c92e..10ca045d16 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3726,6 +3726,10 @@"modelCount": "已配置 {{count}} 个模型","modelsAutomatic": "模型资料自动获取。单个模型的设置在模型列表中调整。","manualModel": "模型 ID(无法自动获取时填写)",+ "manualAdd": "手动添加模型",+ "manualId": "模型 ID",+ "saveProvider": "保存供应商",+ "removeModel": "移除模型","modelTypeAutomatic": "自动识别","manualModelTypeHint": "同一 ID 可更新类型;自动识别会恢复目录中的类型。","mediaOnlyTestHint": "此连接仅含非对话模型。可获取模型列表检查目录访问,此处不验证模型调用。"diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 185ea1b479..db9dff7d3b 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -3726,6 +3726,10 @@"modelCount": "已設定 {{count}} 個模型","modelsAutomatic": "模型資料自動取得。個別模型的設定請在模型清單調整。","manualModel": "模型 ID(無法自動取得時填寫)",+ "manualAdd": "手動新增模型",+ "manualId": "模型 ID",+ "saveProvider": "儲存供應商",+ "removeModel": "移除模型","modelTypeAutomatic": "自動辨識","manualModelTypeHint": "相同 ID 可更新類型;自動辨識會恢復目錄中的類型。","mediaOnlyTestHint": "此連線僅含非對話模型。可取得模型列表檢查目錄存取,此處不驗證模型呼叫。"diff --git a/docs/product-rules/provider-auto-detection.md b/docs/product-rules/provider-auto-detection.mdindex 68312f9e80..1631481956 100644--- a/docs/product-rules/provider-auto-detection.md+++ b/docs/product-rules/provider-auto-detection.md@@ -7,16 +7,19 @@## 用户流程-1. 用户选择当前 Runtime,填写名称、基础 URL 和 API key;请求头仍可选填。+1. 添加页遵循已确认的 `simple-add-preview.html`:只填写显示名称、一组默认基础 URL 和 API key;请求头可选。+ 不展示预设下拉、鉴权方式、引擎页签或协议设置;独立引擎配置留在保存后的编辑入口。+ 未单独配置的引擎沿用默认连接与模型选择,仍各用自己的默认协议;已有独立草稿字段不覆盖。2. 输入稳定 400 ms 后,先按当前供应商目录匹配完整官方地址;未匹配时执行固定系统探测,同时读取通用模型目录。名称、模型勾选变化不重新探测。-3. 只有唯一结果且该预设支持当前 Runtime 时显示“已识别为…”,保留 1200 ms,+3. 只有唯一结果且该预设含可用引擎配置时显示“已识别为…”,保留 1200 ms,然后进入已有供应商连接步骤。用户可以立即前往或继续自定义;不会自动保存。4. 名称、URL、key、请求头、各 Runtime 草稿和模型选择随跳转保留。返回自定义后不再自动跳转。用户打开模型选择等子弹层或正在保存时不强制跳转。-5. 未识别、证据冲突、当前 Runtime 不受支持时保留自定义。成功取得的模型首次直接加入模型区;+5. 未识别、证据冲突、预设没有可绑定的引擎配置时保留自定义。成功取得的模型首次直接加入模型区;没有结果时由用户点击“获取模型列表”重试,也可手动添加。失败显示分类原因,不能据此断言站点不能调用。-6. “获取模型列表”优先使用当前输入的成功结果,保留完整勾选弹层。已有的选择、手动模型与显式能力配置优先;+6. 模型区域直接展示已配置数量、模型 ID、类型和移除按钮;数量随选择变化。“手动添加模型”使用默认折叠的胶囊入口。+ “测试连接”和“获取模型列表”位于请求头之后、连接区域底部。“获取模型列表”优先使用当前输入的成功结果,保留完整勾选弹层。已有的选择、手动模型与显式能力配置优先;后续获取出现的新模型不重新自动全选,已配置但目录不再返回的模型保留。7. URL、key、请求头、协议或 Runtime 变化使旧结果过期;旧请求不得修改新输入的界面或触发跳转。关闭弹窗、取消、新探测会取消对应的固定系统请求。官方模型读取沿用现有 IPC 的超时,界面丢弃迟到结果。@@ -29,9 +32,9 @@- 遍历当前目录的预设(包括生成目录与已有官方 API 入口),不复制一份地区供应商白名单。- 官方地址按规范化后的完整 origin/path 匹配,保留业务路径;同域不同路径不能混用。- Azure 等受约束资源模板使用既有模板绑定;任意 `{endpoint}`、回环地址及端口不能作为身份依据。-- 同地址对应多个套餐时不任意挑选,提示存在多个匹配,允许用户通过已有模板菜单选择。+- 同地址对应多个套餐时不任意挑选,提示存在多个匹配,保留自定义流程;需要指定套餐时可返回供应商选择入口。- 固定系统只有下面五类。用户部署地址替换预设端点,保留部署前缀和各模型路由;- 不能把用户的地址替换成预设中的 localhost。只绑定当前 Runtime,不创建兄弟账号。+ 不能把用户的地址替换成预设中的 localhost。识别后带入对应预设支持的各引擎配置,沿用各引擎的地址与协议规则,不创建兄弟账号。- Global 与中国大陆版仍使用原来的区域排序与可用目录,识别算法不按地区另写一套。## 固定系统证据