Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
chore: sync main and preserve provider detection alongside Codex summary
shenjiachengfc1e7a429348
diff --cc apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsxindex 88ab1f5d05,5b8635e984..1eaf923ab9--- a/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx+++ b/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx@@@ -2237,14 -2530,9 +2530,14 @@@ export function ProviderConnectionDialo})}/><span className="text-12 leading-snug text-[var(--text-tertiary)]">- {templateBound ? (boundPreset ? presetDisplayName(boundPreset, i18n.language) : name) : activeTab === 'codex' ? (- {templateBound ? (boundPreset ? presetDisplayName(boundPreset, i18n.language) : name) : t(!editing && onDetected ? 'settings.providers.detection.hint' : TAB_META[activeTab].helpKey)}++ {templateBound ? (boundPreset ? presetDisplayName(boundPreset, i18n.language) : name) : !editing && onDetected ? t('settings.providers.detection.hint') : activeTab === 'codex' ? (+ <>+ <span>{t('settings.providers.custom.protocol.codexUpstream')}</span>+ <span>{t(customProviderCodexWireProtocolOption(f.wireProtocol).labelKey)}</span>+ </>+ ) : t(TAB_META[activeTab].helpKey)}</span>- </div>+ </div>}{/* 当前 Tab 的独立配置面板 */}<divdiff --cc apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsxindex a9fd56a390,c9624fca68..24e75d0fa3--- a/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx@@@ -2082,36 -2106,526 +2106,559 @@@ it('main provider form contains Tab anexpect(screen.queryByRole('dialog')).toBeNull();});+ // New scheme-2 behavior: real dialog, fake IPC and clocks. Existing accessibility tests+ // do not cover delayed navigation or a previous connection's late model result.+ describe('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(available: ProviderPreset = preset, url = 'https://api.deepseek.com', apiKey = 'fake-key') {+ 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: [available] })), fetchProviderModels,+ detectProvider: vi.fn(async () => ({ candidates: [], reason: 'insufficient_evidence', catalog: { ok: true, models: [{ id: 'custom-model', name: 'Custom' }] } })),+ });+ const onDetected = vi.fn();+ render(<ProviderConnectionDialog focusAgent="pi" onDetected={onDetected} onClose={vi.fn()} onSaved={vi.fn()} />);+ await act(async () => {});+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: url } });+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder'), { target: { value: apiKey } });+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });+ return { onDetected, fetchProviderModels };+ }+ it.each([+ ['http://127.0.0.1:1234/v1', '', 'none'],+ ['http://localhost:1234/v1', '', 'none'],+ ['http://[::1]:1234/v1', '', 'none'],+ ['https://remote.example/v1', '', 'apiKey'],+ ['https://localhost.example/v1', '', 'apiKey'],+ ['http://127.0.0.1:1234/v1', 'fake-key', 'apiKey'],+ ])('keeps discovery, testing and saving on the same add-form auth: %s / %s', async (url, key, method) => {+ await openIdentification(preset, url, key);+ const testConnection = vi.fn(async () => ({ ok: true, latencyMs: 1 }));+ window.electronAPI.maker.testProviderConnection = testConnection;+ expect(window.electronAPI.maker.detectProvider).toHaveBeenCalledWith(expect.objectContaining({ authMethod: method }));+ // Local inference must never hide the input needed to add authentication later.+ expect(screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder')).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));+ await act(async () => {});+ expect(testConnection).toHaveBeenCalledWith(expect.objectContaining({ spec: expect.objectContaining({ authMethod: method, apiKey: key || null }) }));+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.namePlaceholder'), { target: { value: 'Auth regression' } });+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.connection.saveProvider' }));+ await act(async () => {});+ const [config, keys] = customProviderMocks.createCustomProvider.mock.calls[0];+ expect(config.auth?.method ?? 'apiKey').toBe(method);+ expect(keys).toEqual(key ? { pi: key } : {});+ });+ it('saves refreshed metadata after first discovery and a corrected API key', async () => {+ const { fetchProviderModels } = await openIdentification();+ fetchProviderModels.mockResolvedValue({ ok: true, models: [+ { id: 'private-model', name: 'Model', discoveredMetadata: { contextWindow: 64000 }, discoveredCost: { input: 2, output: 8 } },+ { id: 'new-model', name: 'Not automatically selected' },+ ] } as any);+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder'), { target: { value: 'fake-corrected' } });+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });+ expect(fetchProviderModels).toHaveBeenCalledTimes(2);+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.namePlaceholder'), { target: { value: 'Corrected key' } });+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.connection.saveProvider' }));+ await act(async () => {});+ expect(customProviderMocks.createCustomProvider).toHaveBeenCalledOnce();+ expect(customProviderMocks.createCustomProvider.mock.calls[0][0].runtimes.pi.models).toEqual([+ expect.objectContaining({ id: 'private-model', discoveredMetadata: { contextWindow: 64000 }, discoveredCost: { input: 2, output: 8 } }),+ ]);+ });+ it.each(['key', 'endpoint'])('refreshes discovered facts after changing %s without changing selected models or overrides', async change => {+ vi.useFakeTimers();+ const detectProvider = vi.fn(async (_spec: any) => ({ candidates: [], reason: 'insufficient_evidence', catalog: { ok: true, models: [+ { id: 'selected', name: 'Upstream name', discoveredMetadata: { contextWindow: 64000, supportsImageInput: true }, discoveredCost: { input: 2, output: 8 } },+ { id: 'not-selected', name: 'Do not import again' },+ ] } }));+ Object.assign(window.electronAPI.maker, { listProviderPresets: vi.fn(async () => ({ presets: [] })), detectProvider });+ render(<ProviderConnectionDialog onDetected={vi.fn()} onClose={vi.fn()} onSaved={vi.fn()} draft={{+ preset, agent: 'pi', apiKey: 'fake-old', keys: { pi: 'fake-old' },+ config: { id: 'draft', name: 'Refresh regression', runtimes: { pi: {+ baseUrl: 'https://custom.example/v1', models: [{ id: 'selected', name: 'My name', contextWindow: 32000, defaultEnabled: false,+ discoveredMetadata: { contextWindow: 16000 }, discoveredCost: { input: 1, output: 4 } }],+ } } },+ }} />);+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });+ fireEvent.change(screen.getByPlaceholderText(change === 'key'+ ? 'settings.providers.custom.fields.apiKeyPlaceholder' : 'settings.providers.custom.fields.baseUrlPlaceholder'),+ { target: { value: change === 'key' ? 'fake-corrected' : 'https://other.example/v1' } });+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });+ expect(detectProvider.mock.calls.filter(args => !(args[0] as any)?.cancel)).toHaveLength(2);+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.connection.saveProvider' }));+ await act(async () => {});+ expect(customProviderMocks.createCustomProvider).toHaveBeenCalledOnce();+ expect(customProviderMocks.createCustomProvider.mock.calls[0][0].runtimes.pi.models).toEqual([+ expect.objectContaining({ id: 'selected', name: 'My name', contextWindow: 32000, defaultEnabled: false,+ discoveredMetadata: { contextWindow: 64000, supportsImageInput: true }, discoveredCost: { input: 2, output: 8 } }),+ ]);+ });+ it('invalidates inferred no-auth when key or destination changes', async () => {+ await openIdentification(preset, 'http://127.0.0.1:1234/v1', '');+ const testConnection = vi.fn(async () => ({ ok: true, latencyMs: 1 }));+ window.electronAPI.maker.testProviderConnection = testConnection;+ const key = screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder');+ for (const [value, method] of [['fake-key', 'apiKey'], ['', 'none']] as const) {+ fireEvent.change(key, { target: { value } });+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));+ await act(async () => {});+ expect(testConnection).toHaveBeenLastCalledWith(expect.objectContaining({ spec: expect.objectContaining({ authMethod: method }) }));+ }+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: 'https://remote.example/v1' } });+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));+ await act(async () => {});+ expect(testConnection).toHaveBeenLastCalledWith(expect.objectContaining({ spec: expect.objectContaining({ authMethod: 'apiKey' }) }));+ });+ it.each(['remote-engine', 'independent-key', 'remote-directory'])('does not infer global no-auth across a %s draft', async variant => {+ vi.useFakeTimers();+ const local = { baseUrl: 'http://127.0.0.1:1234/v1', models: [{ id: 'local-model', name: 'Local' }] };+ const own = { ...local, baseUrl: variant === 'remote-engine' ? 'https://remote.example/v1' : local.baseUrl,+ ...(variant === 'remote-directory' ? { modelsUrl: 'https://remote.example/v1/models' } : {}) };+ const testConnection = vi.fn(async () => ({ ok: true, latencyMs: 1 }));+ Object.assign(window.electronAPI.maker, { listProviderPresets: vi.fn(async () => ({ presets: [] })), testProviderConnection: testConnection });+ render(<ProviderConnectionDialog onDetected={vi.fn()} onClose={vi.fn()} onSaved={vi.fn()} draft={{+ preset, agent: 'pi', apiKey: '', keys: { pi: '', codex: variant === 'independent-key' ? 'own-key' : '' },+ config: { id: 'draft', name: 'Local with independent runtime', runtimes: { pi: local, codex: own } },+ }} />);+ await act(async () => {});+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));+ await act(async () => {});+ expect(testConnection).toHaveBeenCalledWith(expect.objectContaining({ spec: expect.objectContaining({ authMethod: 'apiKey' }) }));+ });+ it('preserves header-only credentials on a local new connection', async () => {+ await openIdentification(preset, 'http://127.0.0.1:1234/v1', '');+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.fields.addHeader' }));+ // Header input labels are shared by the existing form; use its placeholders.+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.headerNamePlaceholder'), { target: { value: 'Authorization' } });+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.headerValuePlaceholder'), { target: { value: 'Bearer fake-header' } });+ const testConnection = vi.fn(async () => ({ ok: true, latencyMs: 1 }));+ window.electronAPI.maker.testProviderConnection = testConnection;+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));+ await act(async () => {});+ expect(testConnection).toHaveBeenCalledWith(expect.objectContaining({ spec: expect.objectContaining({ authMethod: 'apiKey', headers: { Authorization: 'Bearer fake-header' } }) }));+ });+ // Empty-key GUI regressions: address identification must survive a 401 from+ // model discovery and reach the wizard without saving an account. Unit.+ it.each([+ ['https://ark.cn-beijing.volces.com/api/v3', 'volcengine-api'],+ ['https://api.siliconflow.cn/v1', 'siliconflow-cn'],+ ['https://api.siliconflow.com/v1', 'siliconflow-global'],+ ['https://api.mistral.ai/v1', 'mistral'],+ ['https://api.together.xyz/v1', 'together'],+ ['https://api.fireworks.ai/inference/v1', 'fireworks'],+ ])('hands off %s with an empty key even when discovery requires authentication', async (url, id) => {+ const available = BUNDLED_CATALOG.presets!.find(p => p.id === id)!;+ const { onDetected, fetchProviderModels } = await openIdentification(available, '', '');+ fetchProviderModels.mockResolvedValue({ ok: false, code: 'AUTH_INVALID' } as any);+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: url } });+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });+ expect(onDetected).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.detection.configure' }));+ await act(async () => {});+ expect(onDetected).toHaveBeenCalledOnce();+ expect(onDetected.mock.calls[0][0]).toMatchObject({ apiKey: '', preset: { id }, agent: 'pi' });+ expect(fetchProviderModels).toHaveBeenCalledWith(expect.objectContaining({ apiKey: null }));+ expect(customProviderMocks.createCustomProvider).not.toHaveBeenCalled();+ });+ it('shows missing-key guidance instead of an expired-key error, and clears stale authentication feedback on edit', async () => {+ await openIdentification();+ Object.assign(window.electronAPI.maker, {+ detectProvider: vi.fn(async () => ({ candidates: [], reason: 'insufficient_evidence', catalog: { ok: false, code: 'AUTH_INVALID' } })),+ });+ const key = screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder');+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: 'https://relay.example/v1' } });+ fireEvent.change(key, { target: { value: '' } });+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });+ expect(screen.getByText('settings.providers.detection.keyRequired')).toBeTruthy();+ expect(key.getAttribute('aria-invalid')).not.toBe('true');+ expect(screen.queryByText('providerError.AUTH_INVALID')).toBeNull();+ expect(screen.queryByText('settings.providers.detection.custom')).toBeNull();+ fireEvent.change(key, { target: { value: 'rejected-test-key' } });+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });+ expect(screen.getByText('settings.providers.detection.authRejected')).toBeTruthy();+ expect(key.getAttribute('aria-invalid')).toBe('true');+ fireEvent.change(key, { target: { value: 'replacement-test-key' } });+ expect(screen.queryByText('settings.providers.detection.authRejected')).toBeNull();+ expect(key.getAttribute('aria-invalid')).not.toBe('true');+ });+ it('still accepts a successful directory response from a service with an empty key', async () => {+ await openIdentification();+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: 'http://localhost:1234/v1' } });+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder'), { target: { value: '' } });+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });+ expect(window.electronAPI.maker.detectProvider).toHaveBeenCalledWith(expect.objectContaining({ baseUrl: 'http://localhost:1234/v1', apiKey: null }));+ expect(screen.queryByText('settings.providers.detection.keyRequired')).toBeNull();+ expect(screen.getByText('settings.providers.detection.custom')).toBeTruthy();+ });+ it('only hands off after an explicit click, even long after identification succeeds', async () => {+ const { onDetected, fetchProviderModels } = await openIdentification();+ expect(onDetected).not.toHaveBeenCalled();+ await act(async () => { await vi.advanceTimersByTimeAsync(10000); });+ expect(onDetected).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.detection.configure' }));+ await act(async () => {});+ expect(onDetected).toHaveBeenCalledOnce();+ expect(onDetected.mock.calls[0][0]).toMatchObject({ apiKey: 'fake-key', agent: 'pi', config: { runtimes: { pi: { baseUrl: 'https://api.deepseek.com', models: [{ id: 'private-model' }] } } } });+ expect(fetchProviderModels).toHaveBeenCalledOnce();+ expect(customProviderMocks.createCustomProvider).not.toHaveBeenCalled();+ });+ it('uses the HTML add layout and saves only Pi for the shared custom connection', 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];+ expect(Object.keys(config.runtimes)).toEqual(['pi']);+ expect(config.runtimes.pi).toMatchObject({ baseUrl: 'https://api.deepseek.com', wireProtocol: 'openai-chat', models: [{ id: 'my-model' }] });+ expect(keys).toEqual({ pi: 'fake-key' });+ });+ // New one-click connection contract: real form actions must preserve the successful+ // route through Save; changed inputs must invalidate an in-flight paid probe (unit tier).+ it('applies an automatically verified protocol and saves the same Pi model route', async () => {+ await openIdentification();+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.detection.keepCustom' }));+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: 'https://unknown.example/team/v1' } });+ window.electronAPI.maker.testProviderConnection = vi.fn(async () => ({ ok: true, latencyMs: 3, decision: 'success' as const,+ selected: { baseUrl: 'https://unknown.example/team', wireProtocol: 'anthropic-messages' as const } }));+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));+ await act(async () => {});+ expect(window.electronAPI.maker.testProviderConnection).toHaveBeenCalledWith(expect.objectContaining({+ requestId: expect.any(String), strategy: 'auto', kind: 'adhoc',+ spec: expect.objectContaining({ agent: 'pi', baseUrl: 'https://unknown.example/team/v1', modelId: 'private-model' }),+ }));+ expect(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder')).toHaveProperty('value', 'https://unknown.example/team');+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));+ await act(async () => {});+ expect(window.electronAPI.maker.testProviderConnection).toHaveBeenLastCalledWith(expect.objectContaining({+ strategy: 'auto', spec: expect.objectContaining({ wireProtocol: 'anthropic-messages', baseUrl: 'https://unknown.example/team' }),+ }));+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.namePlaceholder'), { target: { value: 'Verified custom' } });+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.connection.saveProvider' }));+ await act(async () => {});+ const [config] = customProviderMocks.createCustomProvider.mock.calls[0];+ expect(Object.keys(config.runtimes)).toEqual(['pi']);+ expect(config.runtimes.pi).toMatchObject({ baseUrl: 'https://unknown.example/team', wireProtocol: 'anthropic-messages',+ models: [{ id: 'private-model', api: 'anthropic-messages', route: { baseUrl: 'https://unknown.example/team', wireProtocol: 'anthropic-messages' } }] });+ });+ it.each(['key', 'address', 'stop'] as const)('cancels on %s and ignores a late successful protocol result', async change => {+ await openIdentification();+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.detection.keepCustom' }));+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: 'https://unknown.example/v1' } });+ let finish!: (value: unknown) => void;+ window.electronAPI.maker.testProviderConnection = vi.fn().mockImplementation(input => input.kind === 'cancel'+ ? Promise.resolve({ ok: false, latencyMs: 0, decision: 'cancelled' }) : new Promise(resolve => { finish = resolve; }));+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));+ expect(window.electronAPI.maker.testProviderConnection).toHaveBeenCalledOnce();+ if (change === 'key') {+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder'), { target: { value: 'different-fake-key' } });+ } else if (change === 'address') {+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: 'https://new.example/v1' } });+ } else {+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.stop' }));+ }+ expect(window.electronAPI.maker.testProviderConnection).toHaveBeenLastCalledWith(expect.objectContaining({ kind: 'cancel' }));+ await act(async () => { finish({ ok: true, latencyMs: 1, selected: { baseUrl: 'https://stale.example', wireProtocol: 'openai-responses' } }); });+ expect(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder')).toHaveProperty('value', change === 'address' ? 'https://new.example/v1' : 'https://unknown.example/v1');+ expect(screen.queryByText('settings.providers.custom.test.ok')).toBeNull();+ });+ 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);+ expect(onDetected).not.toHaveBeenCalled();+ 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']).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).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.detection.configure' }));+ await act(async () => {});+ 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.each([true, false])('does not sync shared edits to an independent runtime with overlapping fields: %s', async sameAddress => {+ const own = { baseUrl: sameAddress ? 'https://api.deepseek.com' : 'https://independent.example/v1',+ models: [{ id: 'one', name: 'One' }], requestPath: '/independent/messages' };+ render(<ProviderConnectionDialog onDetected={vi.fn()} onClose={vi.fn()} onSaved={vi.fn()}+ draft={{ preset, agent: 'pi', apiKey: 'fake-key', keys: { pi: 'fake-key', 'claude-code': 'fake-key' },+ config: { id: 'draft', name: 'Draft', runtimes: {+ pi: { baseUrl: 'https://api.deepseek.com', models: [{ id: 'one', name: 'One' }] }, 'claude-code': own,+ } } }} />);+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder'), { target: { value: 'new-shared-key' } });+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: 'https://new.example/v1' } });+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.connection.saveProvider' }));+ await act(async () => {});+ const [config, keys] = customProviderMocks.createCustomProvider.mock.calls[0];+ expect(keys['claude-code']).toBe('fake-key');+ expect(config.runtimes['claude-code']).toMatchObject(own);+ });+ 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' }));+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder'), { target: { value: 'another-fake-key' } });+ await act(async () => { await vi.advanceTimersByTimeAsync(2000); });+ expect(onDetected).not.toHaveBeenCalled();+ });+ it('carries an explicit Codex image-generation option into the identified preset', async () => {+ vi.useFakeTimers();+ const codexPreset = { ...preset, runtimes: { codex: { ...preset.runtimes.pi, wireProtocol: 'openai-responses' as const } } };+ Object.assign(window.electronAPI.maker, {+ listProviderPresets: vi.fn(async () => ({ presets: [codexPreset] })),+ 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()}+ draft={{ agent: 'codex', preset: codexPreset, apiKey: '', config: { id: 'draft', name: '', runtimes: {+ codex: { baseUrl: '', wireProtocol: 'openai-responses', models: [], supportsImageGeneration: true },+ } } }} />);+ await act(async () => {});+ 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);+ });+ it('reuses the directory after returning to custom without restarting detection', async () => {+ const { onDetected, fetchProviderModels } = await openIdentification();+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.detection.configure' }));+ await act(async () => {});+ const draft = onDetected.mock.calls[0][0];+ cleanup();+ fetchProviderModels.mockClear();+ const onReturnDetection = vi.fn();+ render(<ProviderConnectionDialog draft={draft} focusAgent="pi" onDetected={onReturnDetection} onClose={vi.fn()} onSaved={vi.fn()} />);+ await act(async () => { await vi.advanceTimersByTimeAsync(2000); });+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.fetch.button' }));+ await act(async () => {});+ expect(fetchProviderModels).not.toHaveBeenCalled();+ expect(onReturnDetection).not.toHaveBeenCalled();+ expect(screen.getAllByRole('dialog')).toHaveLength(2);+ });+ it('does not navigate over an open model picker and opening it reuses the successful directory', async () => {+ const { onDetected, fetchProviderModels } = await openIdentification();+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.fetch.button' }));+ await act(async () => {});+ await act(async () => { await vi.advanceTimersByTimeAsync(1200); });+ expect(onDetected).not.toHaveBeenCalled();+ expect(fetchProviderModels).toHaveBeenCalledOnce();+ });+ it.each([+ [[], 'insufficient_evidence'],+ [['sub2api', 'litellm'], 'conflict'],+ [['missing-preset'], 'matched'],+ ])('stays custom for unusable deployment candidates: %s', async (candidates, reason) => {+ const { onDetected } = await openIdentification();+ window.electronAPI.maker.detectProvider = vi.fn(async () => ({ candidates, reason, catalog: { ok: true, models: [] } })) as any;+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: 'https://unknown.example/team/v1' } });+ await act(async () => { await vi.advanceTimersByTimeAsync(2000); });+ expect(onDetected).not.toHaveBeenCalled();+ expect(screen.queryByRole('button', { name: 'settings.providers.detection.configure' })).toBeNull();+ });+ it('does not navigate after unmount with an identified provider', async () => {+ const { onDetected } = await openIdentification();+ cleanup();+ await act(async () => { await vi.advanceTimersByTimeAsync(2000); });+ expect(onDetected).not.toHaveBeenCalled();+ });+ it('uses the current name when the user edits it before clicking configure', async () => {+ const { onDetected } = await openIdentification();+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.namePlaceholder'), { target: { value: 'Latest name' } });+ expect(onDetected).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.detection.configure' }));+ await act(async () => {});+ expect(onDetected).toHaveBeenCalledOnce();+ expect(onDetected.mock.calls[0][0].config.name).toBe('Latest name');+ });+ it('ignores a late response after the connection changes', async () => {+ const { onDetected, fetchProviderModels } = await openIdentification();+ let finish!: (value: { ok: true; models: { id: string; name: string }[] }) => void;+ fetchProviderModels.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ const key = screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder');+ fireEvent.change(key, { target: { value: 'old-fake-key' } });+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });+ fireEvent.change(key, { target: { value: 'new-fake-key' } });+ await act(async () => { finish({ ok: true, models: [{ id: 'obsolete-model', name: 'Obsolete' }] }); });+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });+ expect(onDetected).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.detection.configure' }));+ await act(async () => {});+ expect(onDetected).toHaveBeenCalledOnce();+ expect(onDetected.mock.calls[0][0].apiKey).toBe('new-fake-key');+ expect(onDetected.mock.calls[0][0].config.runtimes.pi.models.map((m: { id: string }) => m.id)).not.toContain('obsolete-model');+ });+ });++it('keeps the outer Codex summary on the saved upstream protocol', async () => {+ const chat = {+ id: 'relay',+ name: 'Relay',+ runtimes: {+ codex: {+ baseUrl: 'https://relay.example.test/v1',+ wireProtocol: 'openai-chat' as const,+ models: [{ id: 'chat-model', name: 'Chat model' }],+ },+ },+ };+ const user = userEvent.setup();+ const { rerender } = render(<ProviderConnectionDialog initial={chat} onSaved={vi.fn()} onClose={vi.fn()} />);+ await screen.findByRole('tab', { name: 'settings.providers.custom.protocol.codex' });+ expect(screen.getByRole('button', { name: 'settings.providers.custom.wireProtocol.chat' }).getAttribute('aria-pressed')).toBe('true');+ expect(screen.getAllByText('settings.providers.custom.wireProtocol.chat').length).toBeGreaterThanOrEqual(2);+ expect(screen.getAllByText('settings.providers.custom.wireProtocol.responses')).toHaveLength(1);++ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.wireProtocol.responses' }));+ expect(screen.getByRole('button', { name: 'settings.providers.custom.wireProtocol.responses' }).getAttribute('aria-pressed')).toBe('true');+ expect(screen.getAllByText('settings.providers.custom.wireProtocol.responses').length).toBeGreaterThanOrEqual(2);+ expect(screen.getAllByText('settings.providers.custom.wireProtocol.chat')).toHaveLength(1);++ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.wireProtocol.chat' }));+ rerender(<ProviderConnectionDialog initial={chat} onSaved={vi.fn()} onClose={vi.fn()} />);+ await screen.findByRole('button', { name: 'settings.providers.custom.wireProtocol.chat' });+ expect(screen.getAllByText('settings.providers.custom.wireProtocol.chat').length).toBeGreaterThanOrEqual(2);++ render(<ProviderConnectionDialog focusAgent="codex" onSaved={vi.fn()} onClose={vi.fn()} />);+ expect(screen.getAllByRole('button', { name: 'settings.providers.custom.wireProtocol.responses' }).some((button) => button.getAttribute('aria-pressed') === 'true')).toBe(true);+});