Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(providers): identify endpoints and reuse provider connection setup
xuzini-xzn0632864f86f8
diff --git a/apps/desktop/scripts/fixtures/provider-detection/provider-detection-fixture.tsx b/apps/desktop/scripts/fixtures/provider-detection/provider-detection-fixture.tsxnew file mode 100644index 0000000000..6a2fbaf4ed--- /dev/null+++ b/apps/desktop/scripts/fixtures/provider-detection/provider-detection-fixture.tsx@@ -0,0 +1,32 @@+import { useState } from 'react';+import { mountPage, forbid, subscription } from '../../ui-page/harness';+import { BUNDLED_CATALOG } from '@cindy/model-providers';+import { ProviderConnectionDialog } from '../../../src/renderer/components/settings/ProviderConnectionDialog';+import { 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 }));+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}+ onClose={() => undefined} onSaved={() => undefined} />;+}+mountPage({+ host: ctx => ({ maker: {+ 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 } },+ localModelList: async () => ({ status: { kind: 'absent', appInstalled: false }, models: [], memoryGb: 0 }),+ scanLocalCli: async () => ({ detections: [] }),+ onProviderOAuthProgress: subscription('providerOAuthProgress'),+ createCustomProvider: forbid('createCustomProvider'),+ testProviderConnection: forbid('testProviderConnection'),+ } }),+ render: () => <Page />,+});diff --git a/apps/desktop/scripts/fixtures/provider-detection/ui-page.mjs b/apps/desktop/scripts/fixtures/provider-detection/ui-page.mjsnew file mode 100644index 0000000000..48362ef156--- /dev/null+++ b/apps/desktop/scripts/fixtures/provider-detection/ui-page.mjs@@ -0,0 +1,40 @@+import assert from 'node:assert/strict';+export default {+ name: 'provider-detection', entry: './provider-detection-fixture.tsx',+ viewport: { width: 900, height: 900 },+ 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: {+ default: { about: 'Official address matches DeepSeek and enters its existing connection step' },+ 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');+ 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';+ await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.baseUrlPlaceholder')).fill(address);+ if (ui.case === 'default' || ui.case === 'relay') {+ await page.getByRole('button', { name: await ui.t('settings.providers.detection.keepCustom') }).waitFor();+ await ui.capture('identified');+ 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 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');+ } else {+ await page.getByText(await ui.t('settings.providers.detection.custom'), { exact: true }).waitFor();+ if (ui.case === 'custom') {+ 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 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');+ }+ }+ },+};diff --git a/apps/desktop/src/main/maker-host/__tests__/providerDetection.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerDetection.test.tsnew file mode 100644index 0000000000..1d1db3c97d--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/providerDetection.test.ts@@ -0,0 +1,120 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { detectProviderDeployment } from '../provider-detection.js';+// Protects scheme-2 request budgets/credential scope through the real discovery transport.+// Existing fetch tests do not dispatch identity probes. Missing/hostile diagnostics are the+// smallest failure inputs; unit injection avoids network and services. No real credentials.+const spec = { agent: 'pi' as const, authMethod: 'apiKey' as const, baseUrl: 'https://relay.example/team/v1', apiKey: 'fake-test-key', headers: { 'X-Project': 'example' } };+const json = (value: unknown, status = 200) => new Response(JSON.stringify(value), { status });+afterEach(() => vi.useRealTimers());++describe('bounded deployment detection', () => {+ it('recognizes Sub2API without exposing billing data and reuses the account directory', async () => {+ const fetcher = vi.fn<typeof fetch>(async (url, init) => {+ expect(String(url).startsWith('https://relay.example/team/')).toBe(true);+ expect(init?.redirect).toBe('error');+ if (String(url).endsWith('/v1/models')) return json({ data: [{ id: 'private-model' }] });+ if (String(url).endsWith('/settings/public')) {+ expect(init?.headers).toEqual({});+ return json({ code: 0, data: { version: '0.2.17', hide_ccs_import_button: false, backend_mode_enabled: true, subscription_enabled: false } });+ }+ if (String(url).endsWith('/sub2api/billing')) {+ expect(init?.headers).toEqual({ Authorization: 'Bearer fake-test-key', 'X-Project': 'example' });+ return json({ object: 'sub2api.key_billing', schema_version: 1, balance: 'must-not-return' });+ }+ return json({ error: 'not found' }, 404);+ });+ const result = await detectProviderDeployment(spec, new AbortController().signal, fetcher);+ expect(result).toMatchObject({ candidates: ['sub2api'], reason: 'matched', catalog: { ok: true, models: [{ id: 'private-model' }] } });+ expect(JSON.stringify(result)).not.toMatch(/must-not-return|fake-test-key/);+ expect(fetcher.mock.calls.filter(([url]) => String(url) === spec.baseUrl + '/models')).toHaveLength(1);+ expect(fetcher.mock.calls.length).toBeLessThanOrEqual(9);+ expect(fetcher.mock.calls.some(([url]) => String(url).endsWith('/health'))).toBe(false);+ });+ it.each([401, 403, 404, 429, 200])('keeps usable models when diagnostics fail with %s', async status => {+ const result = await detectProviderDeployment(spec, new AbortController().signal, async url =>+ String(url).endsWith('/v1/models') ? json({ data: [{ id: 'company-chat' }] }) : json({ error: 'unavailable' }, status));+ expect(result).toMatchObject({ candidates: [], catalog: { ok: true, models: [{ id: 'company-chat' }] } });+ });+ it('skips required Bearer diagnostics without a key; public probes carry no custom headers', async () => {+ const urls: string[] = [];+ await detectProviderDeployment({ ...spec, apiKey: undefined }, new AbortController().signal, async (url, init) => {+ urls.push(String(url));+ if (/greeting|\/version|settings\/public/.test(String(url))) expect(init?.headers).toEqual({});+ return json({ error: 'not found' }, 404);+ });+ expect(urls.some(url => /sub2api\/billing|model\/info|readiness/.test(url))).toBe(false);+ });+ it('does not probe query tokens or full generation URLs', async () => {+ const fetcher = vi.fn<typeof fetch>();+ for (const baseUrl of ['https://relay.example/team/v1?token=fake', 'https://relay.example/v1/chat/completions']) {+ expect(await detectProviderDeployment({ ...spec, baseUrl }, new AbortController().signal, fetcher)).toEqual({ candidates: [], reason: 'insufficient_evidence' });+ }+ expect(fetcher).not.toHaveBeenCalled();+ });+ it('rejects oversized identity bodies and redirects without losing the directory', async () => {+ const result = await detectProviderDeployment(spec, new AbortController().signal, async url => {+ if (String(url).endsWith('/v1/models')) return json({ data: [] });+ return String(url).endsWith('/props') ? json({ padding: 'x'.repeat(1024 * 1024) }) : new Response(null, { status: 302, headers: { location: 'https://other.example' } });+ });+ expect(result).toMatchObject({ candidates: [], catalog: { ok: true, models: [] } });+ });+ it('limits identity concurrency to two and aborts queued work when the draft closes', async () => {+ const controller = new AbortController();+ let active = 0, peak = 0, calls = 0;+ const started: (() => void)[] = [];+ const fetcher: typeof fetch = async (url, init) => {+ calls++;+ if (String(url).endsWith('/v1/models')) return json({ data: [] });+ active++; peak = Math.max(peak, active);+ return new Promise((_resolve, reject) => {+ const abort = () => { active--; reject(new DOMException('Aborted', 'AbortError')); };+ init?.signal?.addEventListener('abort', abort, { once: true });+ started.push(() => undefined);+ });+ };+ const promise = detectProviderDeployment(spec, controller.signal, fetcher);+ expect(started).toHaveLength(2);+ controller.abort();+ expect(await promise).toMatchObject({ catalog: undefined });+ expect(peak).toBe(2);+ expect(calls).toBe(3);+ });+});++it('ends identity work at eight seconds with two concurrent three-second requests', async () => {+ vi.useFakeTimers();+ const requests: number[] = [];+ const timeouts: number[] = [];+ const result = detectProviderDeployment(spec, new AbortController().signal, async (url, init) => {+ if (String(url) === spec.baseUrl + '/models') return json({ data: [] });+ requests.push(Date.now());+ return new Promise((_resolve, reject) => init!.signal!.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError')), { once: true }));+ }, ms => {+ timeouts.push(ms);+ const controller = new AbortController();+ setTimeout(() => controller.abort(), ms);+ return controller.signal;+ });+ await vi.advanceTimersByTimeAsync(7999);+ expect(requests).toHaveLength(6);+ await vi.advanceTimersByTimeAsync(1);+ expect(await result).toMatchObject({ reason: 'budget_exhausted', catalog: { ok: true } });+ expect(timeouts).toEqual([8000, 3000, 3000, 3000, 3000, 3000, 3000]);+});++it('settles already dispatched evidence before accepting a match', async () => {+ let finishProps!: () => void;+ let versionRead!: () => void;+ const reachedVersion = new Promise<void>(resolve => { versionRead = resolve; });+ const result = detectProviderDeployment(spec, new AbortController().signal, async url => {+ if (String(url) === spec.baseUrl + '/models') return json({ data: [{ id: 'model', root: 'weights', owned_by: 'vllm', max_model_len: 8192 }] });+ if (String(url).endsWith('/props')) return new Promise(resolve => {+ finishProps = () => resolve(json({ default_generation_settings: {}, total_slots: 1, build_info: 'b11723' }));+ });+ if (String(url).endsWith('/version')) { versionRead(); return json({ version: 'source.test' }); }+ return json({ error: 'not found' }, 404);+ });+ await reachedVersion;+ finishProps();+ expect(await result).toMatchObject({ reason: 'conflict', candidates: ['llamacpp', 'vllm'] });+});diff --git a/apps/desktop/src/main/maker-host/provider-detection.ts b/apps/desktop/src/main/maker-host/provider-detection.tsnew file mode 100644index 0000000000..1346fbfdf6--- /dev/null+++ b/apps/desktop/src/main/maker-host/provider-detection.ts@@ -0,0 +1,87 @@+import { detectDeploymentProviders, enrichDetectedModels, providerDeploymentRoot, type DeploymentProvider, type ProviderEvidence } from '@cindy/model-providers';+import { fetchProviderModels, type ProviderModelsFetchSpec } from './provider-model-fetch.js';+import type { DeploymentDetectionResult } from '../../shared/providerDetection.js';+import { outboundFetch } from './outbound-fetch.js';++type Probe = { id: keyof ProviderEvidence; system: DeploymentProvider; path: string; auth?: 'required' | 'optional' };+const PROBES: readonly Probe[] = [+ { id: 'lmGreeting', system: 'lmstudio', path: '/lmstudio-greeting' },+ { id: 'llamaProps', system: 'llamacpp', path: '/props', auth: 'optional' },+ { id: 'vllmVersion', system: 'vllm', path: '/version' },+ { id: 'subPublic', system: 'sub2api', path: '/api/v1/settings/public' },+ { id: 'lmModels', system: 'lmstudio', path: '/api/v1/models', auth: 'optional' },+ { id: 'liteReady', system: 'litellm', path: '/health/readiness/details', auth: 'required' },+ { id: 'subBilling', system: 'sub2api', path: '/v1/sub2api/billing', auth: 'required' },+ { id: 'liteModels', system: 'litellm', path: '/v1/model/info', auth: 'required' },+];++async function readIdentity(response: Response): Promise<unknown> {+ // A cloned stream's cancel waits for its sibling. Do not deadlock the directory reader.+ if (!response.ok || !response.body) { void response.body?.cancel().catch(() => undefined); return; }+ const reader = response.body.getReader();+ const chunks: Uint8Array[] = [];+ let size = 0;+ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ size += value.byteLength;+ if (size > 1024 * 1024) return;+ chunks.push(value);+ }+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));+ } finally { void reader.cancel().catch(() => undefined); }+}++/** Bounded read-only probes. All credentials stay in memory; errors never include responses. */+export async function detectProviderDeployment(+ spec: ProviderModelsFetchSpec,+ signal: AbortSignal,+ fetchImpl: typeof fetch = outboundFetch,+ timeoutSignal: (ms: number) => AbortSignal = ms => AbortSignal.timeout(ms),+): Promise<DeploymentDetectionResult> {+ const root = providerDeploymentRoot(spec.baseUrl);+ if (!root || signal.aborted) return { candidates: [], reason: 'insufficient_evidence' };+ const evidence: ProviderEvidence = {};+ const deadline = timeoutSignal(8000);+ const identitySignal = AbortSignal.any([signal, deadline]);+ let index = 0;+ let candidates: DeploymentProvider[] = [];+ const wrappedFetch: typeof fetch = async (url, init) => {+ const response = await fetchImpl(url, { ...init, redirect: 'error', signal: AbortSignal.any([signal, ...(init?.signal ? [init.signal] : [])]) });+ // Only a plain account-visible OpenAI directory supplies cross-check evidence.+ if (String(url) === root + '/v1/models') {+ try { evidence.models = await readIdentity(response.clone()); candidates = detectDeploymentProviders(evidence); } catch { /* optional clue */ }+ }+ return response;+ };+ const catalogPromise = fetchProviderModels({ ...spec, baseUrl: root + '/v1', modelsUrl: root + '/v1/models', redirect: 'error', allowEmpty: true, responseByteLimit: 8 * 1024 * 1024 }, wrappedFetch);+ const worker = async () => {+ while (index < PROBES.length && !identitySignal.aborted) {+ const probe = PROBES[index++];+ if (candidates.length && !candidates.includes(probe.system)) continue;+ if (probe.auth === 'required' && !spec.apiKey?.trim()) continue;+ const headers: Record<string, string> = {};+ if (probe.auth) {+ for (const [key, value] of Object.entries(spec.headers ?? {})) {+ if (!['authorization', 'x-api-key', 'x-goog-api-key', 'host', 'cookie', 'proxy-authorization'].includes(key.toLowerCase())) headers[key] = value;+ }+ if (spec.authMethod !== 'none' && spec.apiKey?.trim()) headers.Authorization = `Bearer ${spec.apiKey.trim()}`;+ }+ try {+ const response = await fetchImpl(root + probe.path, { method: 'GET', headers, redirect: 'error',+ signal: AbortSignal.any([identitySignal, timeoutSignal(3000)]) });+ evidence[probe.id] = await readIdentity(response);+ candidates = detectDeploymentProviders(evidence);+ } catch { /* Missing/forbidden diagnostics only disable identification. */ }+ }+ };+ await Promise.all([worker(), worker()]);+ const catalog = await catalogPromise;+ candidates = detectDeploymentProviders(evidence);+ if (catalog.models && candidates.length === 1) catalog.models = enrichDetectedModels(catalog.models, candidates[0], evidence);+ return { candidates, reason: candidates.length > 1 ? 'conflict' : candidates.length === 1 ? 'matched'+ : deadline.aborted ? 'budget_exhausted' : 'insufficient_evidence',+ // Return only existing classified errors/model metadata, never diagnostic/billing JSON.+ catalog: signal.aborted ? undefined : { ok: catalog.ok, models: catalog.models, code: catalog.code, status: catalog.status } };+}diff --git a/apps/desktop/src/main/maker-host/provider-model-fetch.ts b/apps/desktop/src/main/maker-host/provider-model-fetch.tsindex 9fc796693d..8564d4b588 100644--- a/apps/desktop/src/main/maker-host/provider-model-fetch.ts+++ b/apps/desktop/src/main/maker-host/provider-model-fetch.ts@@ -37,6 +37,8 @@ const INVALID_DISCOVERY_URL = 'model discovery requires HTTP(S) URLs without emb/** 一次「获取模型列表」的完整参数(表单值内存透传,不落盘)。 */export interface ProviderModelsFetchSpec {+ /** Add-flow callers distinguish an empty directory from an invalid response. */+ allowEmpty?: boolean;agent: AgentKind;/** 上游 wire protocol;用于区分 Codex 原生 OpenAI 与 Anthropic Messages 桥。 */wireProtocol?: ProviderWireProtocol;@@ -310,7 +312,7 @@ export async function fetchProviderModels(if (!page.ok) { await page.body?.cancel(); throw new Error('catalog page failed'); }return JSON.parse(await readLimitedBody(page, spec.responseByteLimit ?? 8 * 1024 * 1024));});- if (!models || models.length === 0) {+ if (!models || (models.length === 0 && !spec.allowEmpty)) {// 端点 200 但响应不是可识别的模型列表(或为空)——按「模型不存在」类引导用户手填。return {ok: false,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.tsindex 39e100e102..2ccff3b1f7 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts@@ -4667,3 +4667,39 @@ it('preserves the actual Vertex API through the probe IPC and rejects unknown SD{ kind: 'adhoc', spec: { ...spec, api: 'invented-sdk' } })).rejects.toThrow(/INVALID_PARAMS/);expect(deps.testConnection).toHaveBeenCalledOnce();});++// Scheme-2 detection shares the existing local credential boundary. The new ingress+// needs explicit sender/cancellation coverage; ordinary model fetch has no draft lifecycle.+describe('provider detection drafts', () => {+ const input = { requestId: 'draft-1', agent: 'pi', authMethod: 'apiKey', baseUrl: 'https://relay.example/v1', apiKey: 'fake-test-key' };+ it('rejects untrusted senders and invalid inputs before dispatch', async () => {+ const harness = new IpcHarness();+ const detectProvider = vi.fn();+ const guard = vi.fn<() => void>(() => { throwIpcError('PERMISSION_DENIED', 'untrusted'); });+ registerProviderHandlers(harness, makeDeps({ detectProvider, assertTrustedSender: guard }));+ await expect(harness.invokeFrom(1, MAKER_INVOKE.PROVIDER_DETECT, input)).rejects.toThrow(/PERMISSION_DENIED/);+ guard.mockImplementation(() => undefined);+ for (const invalid of [{ ...input, requestId: '../other' }, { ...input, savedProviderId: 'saved' }, { ...input, baseUrl: 'file:///tmp/key' }, { ...input, headers: { bad: 1 } }]) {+ await expect(harness.invokeFrom(1, MAKER_INVOKE.PROVIDER_DETECT, invalid)).rejects.toThrow(/INVALID_PARAMS/);+ }+ expect(detectProvider).not.toHaveBeenCalled();+ });+ it('isolates cancellations by sender and request, and cancels destroyed windows', async () => {+ const harness = new IpcHarness();+ const signals: AbortSignal[] = [];+ registerProviderHandlers(harness, makeDeps({ detectProvider: async (_spec, signal) => {+ signals.push(signal);+ await new Promise<void>(resolve => signal.addEventListener('abort', () => resolve(), { once: true }));+ return { candidates: [], reason: 'insufficient_evidence' };+ } }));+ const first = harness.invokeFrom(1, MAKER_INVOKE.PROVIDER_DETECT, input);+ const second = harness.invokeFrom(2, MAKER_INVOKE.PROVIDER_DETECT, input);+ await harness.invokeFrom(1, MAKER_INVOKE.PROVIDER_DETECT, { requestId: 'old-draft', cancel: true });+ expect(signals.map(s => s.aborted)).toEqual([false, false]);+ await harness.invokeFrom(1, MAKER_INVOKE.PROVIDER_DETECT, { requestId: 'draft-1', cancel: true });+ expect(signals.map(s => s.aborted)).toEqual([true, false]);+ harness.destroySender(2);+ await Promise.all([first, second]);+ expect(signals[1].aborted).toBe(true);+ });+});diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex 03d8dc613f..6b30d08920 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -592,6 +592,7 @@ export const MAKER_INVOKE = {* 需要 code 渲染分类文案)。带密钥材料,不进 device-link 白名单(口径同 test-connection)。*/PROVIDER_MODELS_FETCH: 'maker:provider:models-fetch',+ PROVIDER_DETECT: 'maker:provider:detect',/*** 通用 OAuth 供应商(目录 auth.oauth 描述符驱动、非 bespoke 四家)的登录 / 登出 / 取消。* 入参 = providerId;login 走 generic-oauth Runner(PKCE 浏览器流),成功后拉动态模型diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.tsindex 4ff55184ba..5122edb74d 100644--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts@@ -1,4 +1,5 @@import { setProviderPresentation, retainProviderPresentationAfterAuthChange } from '../maker-host/provider-presentation-store.js';+import type { DeploymentDetectionResult } from '../../shared/providerDetection.js';import { pruneProviderGroupBindings } from '../provider-group/bindings.js';import { writeProviderGroup } from '../provider-group/store.js';/**@@ -319,6 +320,7 @@ export interface ProviderHandlerDeps {testConnection(input: ProviderTestInput): Promise<ProviderTestResult>;/** 获取模型列表(生产 = fetchProviderModels;单测注入 stub 不联网)。 */fetchModels(spec: ProviderModelsFetchSpec): Promise<ProviderModelsFetchResult>;+ detectProvider?(spec: ProviderModelsFetchSpec, signal: AbortSignal): Promise<DeploymentDetectionResult>;/** 内置四家的模型真源刷新;生产按 providerId 分派到既有 discovery 机制。 */refreshBuiltinModels(providerId: BuiltinRefreshableProviderId): Promise<void>;/** Renderer 自动刷新提示;Main 侧负责静默失败、冷却和跨窗口去重。 */@@ -534,6 +536,8 @@ function parseTestInput(input: unknown): ProviderTestInput | null {function parseModelsFetchInput(input: unknown): ProviderModelsFetchSpec | null {if (!input || typeof input !== 'object') return null;const spec = input as Record<string, unknown>;+ if (spec.allowEmpty !== undefined && typeof spec.allowEmpty !== 'boolean') return null;+ if (spec.redirect !== undefined && spec.redirect !== 'error') return null;if (typeof spec.agent !== 'string' || !VALID_AGENTS.includes(spec.agent)) return null;if (typeof spec.authMethod !== 'string' || !VALID_ADHOC_AUTH_METHODS.includes(spec.authMethod))return null;@@ -580,6 +584,8 @@ function parseModelsFetchInput(input: unknown): ProviderModelsFetchSpec | null {baseUrl: spec.baseUrl,authMethod: spec.authMethod as ProviderModelsFetchSpec['authMethod'],modelsUrl: (spec.modelsUrl as string | null | undefined) ?? null,+ ...(spec.allowEmpty === true ? { allowEmpty: true } : {}),+ ...(spec.redirect === 'error' ? { redirect: 'error' as const } : {}),apiKey: (spec.apiKey as string | null | undefined) ?? null,headers: spec.headers as Record<string, string> | undefined,...(typeof spec.savedProviderId === 'string' ? { savedProviderId: spec.savedProviderId } : {}),@@ -2322,6 +2328,40 @@ export function registerProviderHandlers(});// 获取模型列表:查询型结构化返回(同上例外条款);仅网络/上游失败在结果 code 里,不抛。+ // Like provider creation, detection is local trusted settings only. Never expose keys via relay.+ const detections = new Map<ProviderOAuthRendererSender, { id: string; controller: AbortController }>();+ registry.handle(MAKER_INVOKE.PROVIDER_DETECT, async (event, input: unknown) => {+ assertTrustedProviderMutationSender(event);+ const sender = providerOAuthRendererSender(event);+ if (!sender || !input || typeof input !== 'object') throwIpcError('INVALID_PARAMS', 'invalid detection input');+ const value = input as Record<string, unknown>;+ if (typeof value.requestId !== 'string' || !/^[a-zA-Z0-9_-]{1,100}$/.test(value.requestId)) throwIpcError('INVALID_PARAMS', 'invalid detection id');+ const previous = detections.get(sender);+ if (value.cancel === true) {+ if (previous?.id === value.requestId) previous.controller.abort();+ return { candidates: [], reason: 'insufficient_evidence' };+ }+ const parsed = parseModelsFetchInput(value);+ if (!parsed || parsed.savedProviderId || parsed.authMethod === 'oauth' || parsed.baseUrl.length > 4096+ || (parsed.apiKey?.length ?? 0) > 16384 || Object.entries(parsed.headers ?? {}).some(([k,v]) => k.length > 256 || v.length > 16384)+ || Object.keys(parsed.headers ?? {}).length > 64) throwIpcError('INVALID_PARAMS', 'invalid detection input');+ previous?.controller.abort();+ const controller = new AbortController();+ const operation = { id: value.requestId, controller };+ detections.set(sender, operation);+ const owner = captureProviderOwnerSession();+ const abort = () => controller.abort();+ sender.once?.('destroyed', abort);+ try {+ const result = await deps.detectProvider?.(parsed, controller.signal);+ if (controller.signal.aborted || !providerMutationOwnerMatches(owner)) return { candidates: [], reason: 'insufficient_evidence' };+ return result ?? { candidates: [], reason: 'insufficient_evidence' };+ } finally {+ sender.removeListener?.('destroyed', abort);+ if (detections.get(sender) === operation) detections.delete(sender);+ }+ });+registry.handle(MAKER_INVOKE.PROVIDER_MODELS_FETCH, async (event, input: unknown) => {// 这条查询会把 renderer 提供的 API key / 自定义 headers 带到目标 endpoint;// 与重新发现一样,必须先确认调用方是 Cindy 自有顶层页面,避免 WebView / 子 framediff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 7a99b47b2a..3611536c71 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -1125,6 +1125,7 @@ import { refreshOpenAiMediaModels } from '../maker-host/model-discovery/openai-mimport { refreshXaiMediaModels } from '../maker-host/model-discovery/xai-media.js';import { testProviderConnection } from '../maker-host/provider-diagnostics.js';import { fetchProviderModels, fetchSavedOAuthProviderModels } from '../maker-host/provider-model-fetch.js';+import { detectProviderDeployment } from '../maker-host/provider-detection.js';import {beginProviderRouteMutation,setPendingCredentialSwitchReader,@@ -6781,6 +6782,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)getProviderOrder: () => readProviderOrder(),listPresets: () => getActiveCatalog().presets ?? [],testConnection: (input) => testProviderConnection(input),+ detectProvider: detectProviderDeployment,fetchModels: async (spec) => {if (spec.savedProviderId && subscriptionAccountKind(spec.savedProviderId)) {return { ok: await refreshSubscriptionAccountModels(spec.savedProviderId), models: [] };diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 6b8d8c5285..fe78243106 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -6347,7 +6347,15 @@ contextBridge.exposeInMainWorld('electronAPI', {* 供应商「获取模型列表」—— 用表单值 GET 该供应商的列模型端点(key 仅内存透传)。* 结构化结果:ok=true 带 models;失败 code 走 providerError.* i18n。*/+ detectProvider: (input: ({ requestId: string; cancel: true } | {+ requestId: string; agent: 'claude-code' | 'codex' | 'pi'; baseUrl: string;+ authMethod: 'apiKey' | 'none'; apiKey?: string | null; headers?: Record<string, string>;+ wireProtocol?: import('@cindy/model-providers').ProviderWireProtocol;+ })): Promise<import('../shared/providerDetection').DeploymentDetectionResult> =>+ ipcRenderer.invoke('maker:provider:detect', input),fetchProviderModels: (input: {+ allowEmpty?: boolean;+ redirect?: 'error';agent: 'claude-code' | 'codex' | 'pi';baseUrl: string;authMethod: 'apiKey' | 'oauth' | 'none';diff --git a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsxindex 22f61e4a41..ac35accc2d 100644--- a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx+++ b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx@@ -1493,3 +1493,75 @@ it('sets up Sub2API from one site address and retains discovered capabilities incontextWindow: 272000, contextWindowMax: 1050000, supportsFastMode: true, supportsImageInput: true });}});++// Scheme-2 handoff must keep connection ownership and user choices; the managed-local+// entry tests above do not cover an independently addressed LM Studio deployment.+describe('identified provider handoff', () => {+ const model = { id: 'private-alias', name: 'My model', contextWindow: 4096, route: { baseUrl: 'https://relay.example/team/v1', wireProtocol: 'openai-chat' as const } };+ const detected = {+ agent: 'pi' as const, apiKey: 'fake-key', keys: { pi: 'fake-key' },+ preset: { id: 'lmstudio', name: 'LM Studio', runtimes: { pi: {+ baseUrl: 'https://relay.example/team/v1', baseUrlEditable: true, wireProtocol: 'openai-chat' as const,+ headers: { 'X-Project': 'test' }, models: [],+ } } },+ config: { id: 'draft', name: 'My remote server', runtimes: { pi: { baseUrl: 'https://relay.example/team/v1', models: [model] } } },+ catalog: { ok: true, models: [{ id: 'private-alias', name: 'Upstream name' }, { id: 'unselected', name: 'Another' }] },+ };+ it.each([false, true])('saves an independent connection and retains overrides on its edited endpoint: %s', async edited => {+ const managed = { ...anthropicProvider, id: 'cindy-local-lmstudio', name: 'LM Studio', source: 'user' } as ProviderView;+ render(<AddProviderWizard providers={[managed]} detected={detected} onClose={vi.fn()} onDone={vi.fn()} onOpenCustomForm={vi.fn()} />);+ const baseUrl = edited ? 'https://new-relay.example/team/v1' : detected.config.runtimes.pi.baseUrl;+ if (edited) vi.mocked(window.electronAPI.maker.fetchProviderModels).mockResolvedValue(detected.catalog);+ if (edited) fireEvent.change(await screen.findByDisplayValue(detected.config.runtimes.pi.baseUrl), { target: { value: baseUrl } });+ 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));+ if (!edited) expect(window.electronAPI.maker.fetchProviderModels).not.toHaveBeenCalled();+ fireEvent.click(finish);+ await waitFor(() => expect(createCustomProvider).toHaveBeenCalledOnce());+ const [config, keys] = vi.mocked(createCustomProvider).mock.calls[0];+ expect(config.id).not.toBe('cindy-local-lmstudio');+ expect(config.runtimes.pi).toMatchObject({ baseUrl, wireProtocol: 'openai-chat', headers: { 'X-Project': 'test' } });+ expect(config.runtimes.pi!.models.find(m => m.id === 'private-alias')).toMatchObject({ ...model, route: { ...model.route, baseUrl } });+ expect(config.runtimes.pi!.models.find(m => m.id === 'unselected')?.defaultEnabled).toBe(false);+ expect(keys).toEqual({ pi: 'fake-key' });+ });+ it('saves the explicit native image option carried by a Codex handoff', async () => {+ const runtime = { ...detected.preset.runtimes.pi, wireProtocol: 'openai-responses' as const, supportsImageGeneration: true };+ const handoff = { ...detected, agent: 'codex' as const, keys: { codex: 'fake-key' },+ preset: { ...detected.preset, runtimes: { codex: runtime } },+ config: { ...detected.config, runtimes: { codex: { ...runtime, models: [{ id: 'private-alias', name: 'Model' }] } } },+ };+ 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());+ expect(vi.mocked(createCustomProvider).mock.calls[0][0].runtimes.codex).toMatchObject({ supportsImageGeneration: true, wireProtocol: 'openai-responses' });+ });+ it('retains a hand-entered model when OpenRouter returns a complete public catalog', async () => {+ const baseUrl = 'https://openrouter.ai/api/v1';+ const handoff = { ...detected,+ preset: { ...detected.preset, id: 'openrouter', name: 'OpenRouter', runtimes: { pi: { ...detected.preset.runtimes.pi, baseUrl } } },+ config: { ...detected.config, runtimes: { pi: { baseUrl, models: [{ ...model, route: { ...model.route, baseUrl } }] } } },+ catalog: { ok: true, models: [{ id: 'public-only', name: 'Public' }] },+ };+ 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));+ expect(screen.getByText('My model')).toBeTruthy();+ fireEvent.click(finish);+ 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('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()} />);+ fireEvent.change(await screen.findByPlaceholderText('sk-…'), { target: { value: 'edited-fake-key' } });+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.wizard.back' }));+ expect(onReturnCustom).toHaveBeenCalledWith(expect.objectContaining({ apiKey: 'edited-fake-key', config: expect.objectContaining({ name: 'My remote server' }) }));+ expect(createCustomProvider).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsxindex a29c732dba..a4a7252630 100644--- a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx+++ b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx@@ -51,6 +51,8 @@ import { LocalOllamaInstall, offersManagedOllamaInstall } from './LocalOllamaInsimport { MANAGED_LLAMACPP_PROVIDER_ID } from '../../../shared/llamaCpp';import { OAuthBrowserLink, OAuthDeviceCodeCard } from './OAuthDeviceCodeCard';import { SettingsTextInput } from './SettingsTextInput';+import { modelsAfterProviderEndpointEdit } from '@/lib/customProviderEndpointEdit';+import type { DetectedProviderDraft } from '../../../shared/providerDetection';import {PROVIDER_MEDIA_FIELDS,@@ -79,6 +81,8 @@ export type WizardEntry ={ kind: 'builtin'; providerId: string } | { kind: 'preset'; presetId: string };interface AddProviderWizardProps {+ detected?: DetectedProviderDraft;+ onReturnCustom?: (draft: DetectedProviderDraft) => void;providers: ProviderView[];entry?: WizardEntry;/** 「自定义端点」卡片 → 关闭向导并打开完整表单。 */@@ -356,6 +360,8 @@ function hasRetainedBuiltinConnection(provider: ProviderView): boolean {}export function AddProviderWizard({+ detected,+ onReturnCustom,providers,entry,onOpenCustomForm: openCustomForm,@@ -382,14 +388,15 @@ export function AddProviderWizard({const entryProvider =entry?.kind === 'builtin' ? providers.find((x) => x.id === entry.providerId) : undefined;const [sel, setSel] = useState<Selection | null>(() => {+ if (detected) return { kind: 'preset', preset: detected.preset };if (!entryProvider) return null;return entryProvider.auth?.method === 'apiKey'? { kind: 'builtinApiKey', provider: entryProvider }: { kind: 'oauth', provider: entryProvider };});// 预设表单态- const [name, setName] = useState('');- const [apiKey, setApiKey] = useState('');+ const [name, setName] = useState(detected?.config.name || (detected ? presetDisplayName(detected.preset, i18n.language) : ''));+ const [apiKey, setApiKey] = useState(detected?.apiKey ?? '');const [presetBaseUrls, setPresetBaseUrls] = useState<PresetBaseUrls>({});const [saving, setSaving] = useState(false);const savingRef = useRef(false);@@ -416,7 +423,7 @@ export function AddProviderWizard({browserLoginRef: accountLoginRef,});// Step 3 拉取态- const [step, setStep] = useState<1 | 2 | 3>(entryProvider ? 2 : 1);+ const [step, setStep] = useState<1 | 2 | 3>(entryProvider || detected ? 2 : 1);const [fetchState, setFetchState] = useState<| { status: 'idle' }| { status: 'fetching' }@@ -1017,7 +1024,15 @@ export function AddProviderWizard({}}}- setPicks(initial);+ 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 } } : {}),+ });+ }+ setPicks(previous => detected && previous.size ? previous : initial);setStep(3);setFetchState({ status: 'fetching' });const seq = ++fetchSeqRef.current;@@ -1082,7 +1097,11 @@ export function AddProviderWizard({];return sources.map(async (source) => {try {- const r = await window.electronAPI.maker.fetchProviderModels({+ const reuseDetection = detected?.catalog?.ok && agent === detected.agent+ && apiKey === detected.apiKey && source.baseUrl === detected.preset.runtimes[agent]?.baseUrl+ && !source.route && !source.modelsUrl?.includes('client_version=');+ const r = reuseDetection ? detected!.catalog! : await window.electronAPI.maker.fetchProviderModels({+ ...(detected ? { redirect: 'error' as const } : {}),agent,baseUrl: source.baseUrl,authMethod: preset.authMethod ?? 'apiKey',@@ -1138,7 +1157,8 @@ export function AddProviderWizard({const complete = results.filter(result => result.ok && result.completeInventory);if (complete.length === results.length && results.length === agents.length) {const available = new Set(complete.flatMap(result => result.models.map(model => model.id)));- for (const [id] of next) if (!available.has(id)) next.delete(id);+ const userModels = new Set(Object.values(detected?.config.runtimes ?? {}).flatMap(runtime => runtime?.models.map(model => model.id) ?? []));+ for (const [id] of next) if (!available.has(id) && !userModels.has(id)) next.delete(id);}for (const { agent, models, modelsUrl, route } of results) {const preservePresetOwnership = !!modelsUrl && splitDiscoveryUrls.has(modelsUrl);@@ -1220,7 +1240,7 @@ export function AddProviderWizard({failed: !results.some((r) => r.ok),empty: !results.some((r) => r.models.length > 0),});- }, [sel, apiKey, presetBaseUrls]);+ }, [sel, apiKey, presetBaseUrls, detected]);/*** 零推荐模型的本机代理(例如 LiteLLM)若 `/models` 不可用或返回空清单,仍允许用户@@ -1314,18 +1334,18 @@ export function AddProviderWizard({try {const existing = new Set(providers.map((p) => p.id));const id = oauthDraft?.id ?? (- preset.id === 'lmstudio'+ preset.id === 'lmstudio' && !detected? MANAGED_LMSTUDIO_PROVIDER_ID: uniqueCustomProviderId(name.trim() || presetDisplayName(preset, i18n.language),existing,));- if (preset.id === 'lmstudio' && existing.has(MANAGED_LMSTUDIO_PROVIDER_ID)) {+ if (!detected && preset.id === 'lmstudio' && existing.has(MANAGED_LMSTUDIO_PROVIDER_ID)) {onDone(MANAGED_LMSTUDIO_PROVIDER_ID);return;}- const runtimes: CustomProviderConfig['runtimes'] = {};- const keys: RuntimeKeys = {};+ const runtimes: CustomProviderConfig['runtimes'] = { ...detected?.config.runtimes };+ const keys: RuntimeKeys = { ...detected?.keys };for (const agent of configuredPresetAgents(preset)) {const originalRuntime = preset.runtimes[agent];const rt = originalRuntime ? bindProviderPresetRuntime(originalRuntime, presetRuntimeBaseUrl(preset, agent, presetBaseUrls)) : undefined;@@ -1339,6 +1359,7 @@ export function AddProviderWizard({// Only interface facts belong to discovery. Preset defaults follow a live reference.const discoveredMetadata = m.discoveredMetadata?.[agent] ?? {};return {+ ...(detected?.config.runtimes[agent]?.models.find(model => model.id === m.id) ?? {}),id: m.id,name: m.name,// Selecting a model follows native-engine defaults; it is not an@@ -1359,8 +1380,19 @@ export function AddProviderWizard({if (agentModels.length === 0) continue;runtimes[agent] = {...presetConnectionRuntime(preset, agent, agentModels, rt.baseUrl),+ ...(detected?.config.runtimes[agent]?.imageApi ? { imageApi: detected.config.runtimes[agent]!.imageApi } : {}),+ ...(detected?.config.runtimes[agent]?.videoApi ? { videoApi: detected.config.runtimes[agent]!.videoApi } : {}),...(rt.modelsUrl ? { modelsUrl: rt.modelsUrl } : {}),};+ if (detected) runtimes[agent]!.models = runtimes[agent]!.models.map(model => {+ const original = detected.config.runtimes[agent]?.models.find(m => m.id === model.id);+ if (!original) return model;+ // These are user fields from the custom draft, not imported preset defaults.+ const { defaultEnabled: _enabled, discoveredMetadata: _metadata, discoveredCost: _cost, ...explicit } = original;+ const preserved = { ...model, ...explicit };+ return rt.baseUrl === detected.preset.runtimes[agent]?.baseUrl ? preserved+ : modelsAfterProviderEndpointEdit([preserved], detected.config.runtimes[agent]?.baseUrl, rt.baseUrl)[0];+ });if (preset.authMethod !== 'none') {const k = apiKey.trim();if (k) keys[agent] = k;@@ -1394,7 +1426,7 @@ export function AddProviderWizard({savingRef.current = false;setSaving(false);}- }, [sel, picks, name, apiKey, presetBaseUrls, providers, onDone, t, i18n.language]);+ }, [sel, picks, name, apiKey, presetBaseUrls, providers, onDone, t, i18n.language, detected]);// ── 步骤指示 ─────────────────────────────────────────────────────────// 目录步默认按完整路径显示三步(选择供应商 → 连接 → 选择模型);选中真的@@ -1447,7 +1479,8 @@ export function AddProviderWizard({const presetCanContinue =sel?.kind === 'preset' &&presetBaseUrlsValid &&- (!presetNeedsApiKey || apiKey.trim().length > 0);+ (!presetNeedsApiKey || apiKey.trim().length > 0 || (detected?.catalog?.ok === true && apiKey === detected.apiKey+ && presetRuntimeBaseUrl(sel.preset, detected.agent, presetBaseUrls) === detected.preset.runtimes[detected.agent]?.baseUrl));return (<Dialog.Root open={dialog.open} onOpenChange={(open) => { if (!open) handleClose(); }}>@@ -2187,6 +2220,22 @@ export function AddProviderWizard({type="button"onClick={() => {if (savingRef.current) return;+ if (step === 2 && detected && onReturnCustom && sel?.kind === 'preset') {+ fetchSeqRef.current += 1;+ const agent = detected.agent;+ 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;+ 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) } } } });+ return;+ }if (step === 3) {if (oauthDraftRef.current && sel?.kind === 'preset') {pickPreset(presets.find(p => p.id === sel.preset.id) ?? sel.preset);diff --git a/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx b/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsxindex 7a8af183e4..ce521eefa6 100644--- a/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx+++ b/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx@@ -1,6 +1,10 @@import { useDialogExit } from '@/hooks/useDialogExit';import { WINDOW_DRAG_STYLE, WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';import { providerEndpointBindings, canonicalProviderEndpoint, BUNDLED_CATALOG, mergeModelMetadata } from '@cindy/model-providers';+import { matchOfficialProviders, bindDetectedProvider, isAgentSelectableModel } from '@cindy/model-providers';+import type { DetectedProviderDraft, DetectionCatalog } from '../../../shared/providerDetection';+import { OFFICIAL_API_PRESETS } from './AddProviderWizard';+let detectionRequestSequence = 0;/*** Connection credentials and advanced routing only. Model capabilities are imported into the* shared catalog and edited through standard model settings. Stored per-runtime credentials,@@ -155,6 +159,8 @@ function defaultWireFor(agent: DialogAgentKind): ProviderWireProtocol {}interface ProviderConnectionDialogProps {+ draft?: DetectedProviderDraft;+ onDetected?: (draft: DetectedProviderDraft) => void;initial?: CustomProviderConfig;/** Effective modes from the same connection's active catalog, separate from editable overrides. */catalogModels?: ProviderView['models'];@@ -411,6 +417,8 @@ function PresetDropdown({}export function ProviderConnectionDialog({+ draft,+ onDetected,initial,catalogModels,existingIds,@@ -455,13 +463,17 @@ export function ProviderConnectionDialog({input?.focus();input?.scrollIntoView?.({ block: 'nearest' });}, [fieldError]);- const [name, setName] = useState(initial?.name ?? '');+ const [name, setName] = useState(initial?.name ?? draft?.config.name ?? '');const [manualModel, setManualModel] = useState('');const [manualModelMode, setManualModelMode] = useState('inherit');- const [rt, setRt] = useState<Record<DialogAgentKind, RuntimeFields>>(() => initRuntimes(initial));+ 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 : '');+ return fields;+ });const [activeTab, setActiveTab] = useState<DialogAgentKind>(() =>- (focusAgent && VISIBLE_AGENTS.includes(focusAgent as DialogAgentKind) ? focusAgent as DialogAgentKind : null) ??+ draft?.agent ?? (focusAgent && VISIBLE_AGENTS.includes(focusAgent as DialogAgentKind) ? focusAgent as DialogAgentKind : null) ??((initial && VISIBLE_AGENTS.find((a) => initial.runtimes[a])) || 'claude-code'),);const [hasKey, setHasKey] = useState<Record<DialogAgentKind, boolean>>({@@ -476,7 +488,7 @@ export function ProviderConnectionDialog({const [authMode, setAuthModeState] = useState<CustomProviderAuthMode>(initial?.auth?.method === 'oauth'? 'oauth'- : initial?.auth?.method === 'none'+ : (initial ?? draft?.config)?.auth?.method === 'none'? 'none': 'apiKey',);@@ -893,6 +905,132 @@ export function ProviderConnectionDialog({[i18n.language, setRtSynced],);+ const detectionSuppressed = useRef(!!draft);+ const [detection, setDetection] = useState<{ signature: string; preset?: ProviderPreset; pending?: boolean; ambiguous?: boolean; code?: string } | null>(null);+ const discoveryCache = useRef(new Map<DialogAgentKind, { signature: string; promise: Promise<DetectionCatalog> }>(+ draft?.catalog ? [[draft.agent, { signature: `${draft.agent}:${providerModelFetchRequestSignature(rt[draft.agent], authMode)}`,+ promise: Promise.resolve(draft.catalog) }]] : [],+ ));+ const importedOnce = useRef(new Set<DialogAgentKind>(draft ? [draft.agent] : []));+ const detectionSignature = `${activeTab}:${providerModelFetchRequestSignature(rt[activeTab], authMode)}`;+ const detectionContext = useRef({ name, activeTab, onDetected, signature: detectionSignature });+ const previousDetectionSignatures = useRef(new Map<DialogAgentKind, string>());+ detectionContext.current = { name, activeTab, onDetected, signature: detectionSignature };++ 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 runtimes: CustomProviderConfig['runtimes'] = {};+ const keys: Partial<Record<AgentKind, string>> = {};+ for (const a of AGENTS) {+ const value = rtRef.current[a];+ if (!value.baseUrl.trim()) 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)),+ headers: Object.fromEntries(value.headers.filter(h => h.name.trim()).map(h => [h.name.trim(), h.value])),+ ...(value.requestPath ? { requestPath: value.requestPath } : {}),+ ...(value.modelsUrl.trim() ? { modelsUrl: value.modelsUrl.trim() } : {}),+ ...(value.catalogPresetId ? { catalogPresetId: value.catalogPresetId } : {}),+ ...(value.piCatalogProviderId ? { piCatalogProviderId: value.piCatalogProviderId } : {}),+ ...(value.imageApi ? { imageApi: value.imageApi } : {}),+ ...(value.videoApi ? { videoApi: value.videoApi } : {}),+ ...(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 } : {}),+ } } };+ // The cache is settled before announcing a match; no credentials enter saved detection data.+ const cache = discoveryCache.current.get(agent);+ 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 } });+ });+ }, []);++ useEffect(() => {+ if (editing || !onDetected || authMode === 'oauth' || saving || !dialog.open) return;+ let live = true;+ let jump: ReturnType<typeof setTimeout> | undefined;+ // Correlation only, scoped to this renderer; randomUUID requires a secure context.+ const requestId = `detect-${Date.now()}-${++detectionRequestSequence}`;+ const agent = activeTab;+ const fields = rt[agent];+ const signature = detectionSignature;+ const previousSignature = previousDetectionSignatures.current.get(agent);+ previousDetectionSignatures.current.set(agent, signature);+ if (previousSignature && previousSignature !== signature) {+ setRtSynced(prev => ({ ...prev, [agent]: { ...prev[agent], models: prev[agent].models.map(model => {+ const { discoveredMetadata: _metadata, discoveredCost: _cost, ...userFields } = model;+ return userFields;+ }) } }));+ }+ setDetection(null);+ const timer = setTimeout(() => {+ if (modelFetchInFlightRef.current || !fields.baseUrl.trim() || !areProviderRequestUrlsAllowed(authMode, fields.baseUrl)) return;+ if (draft?.catalog && discoveryCache.current.get(agent)?.signature === signature) {+ setDetection({ signature });+ return;+ }+ setDetection({ signature, pending: true });+ const all = [...presets, ...Object.values(OFFICIAL_API_PRESETS).filter(p => !presets.some(existing => existing.id === p.id))];+ const official = matchOfficialProviders(fields.baseUrl.trim(), all);+ const headers = Object.fromEntries(fields.headers.filter(h => h.name.trim()).map(h => [h.name.trim(), h.value]));+ const spec = { agent, baseUrl: fields.baseUrl.trim(), apiKey: fields.apiKey.trim() || null,+ authMethod: authMode, headers, wireProtocol: fields.wireProtocol };+ const work = (async () => {+ if (official.length) {+ const preset = official.length === 1 ? bindDetectedProvider(official[0], agent, 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,+ allowEmpty: true, redirect: 'error',+ baseUrl: runtime.baseUrl, modelsUrl: fields.modelsUrl.trim() || runtime.modelsUrl, wireProtocol: runtime.wireProtocol ?? defaultWireFor(agent),+ 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' };+ })().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 }) => {+ if (!live || detectionContext.current.signature !== signature) return;+ if (catalog?.ok && catalog.models) {+ const first = !importedOnce.current.has(agent);+ importedOnce.current.add(agent);+ if (first) setRtSynced(prev => ({ ...prev, [agent]: { ...prev[agent], models: [+ ...prev[agent].models.filter(m => m.id.trim()),+ ...catalog.models!.filter(m => !prev[agent].models.some(row => row.id === m.id) && isAgentSelectableModel({ id: m.id, mode: m.discoveredMetadata?.mode })).map(m => ({+ id: m.id, name: m.name, discoveredMetadata: m.discoveredMetadata ?? { contextWindow: m.contextWindow }, discoveredCost: m.discoveredCost,+ })),+ ] } }));+ }+ 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);+ }, 1200);+ });+ }, 400);+ return () => {+ live = false;+ clearTimeout(timer);+ clearTimeout(jump);+ void window.electronAPI.maker.detectProvider?.({ requestId, cancel: true }).catch(() => undefined);+ };+ // A model selection/name change is not a new connection or a reason to restart detection.+ }, [detectionSignature, presets, editing, authMode, saving, dialog.open, !!onDetected, enterDetectedProvider, setRtSynced]);+// 编辑态:回填各已配置 runtime 的已存明文密钥(用户本机自己的 key)——// 让密钥框「能看」(eye 显形 / 可核对),而非空白遮罩;据此点亮「已保存」徽标。// 鉴权请求头是 main-only 密文,不回读进表单;未显式改动时由 main 侧 update 保留旧值。@@ -1369,7 +1507,11 @@ export function ProviderConnectionDialog({modelFetchInFlightRef.current = true;setFetchingModels((prev) => ({ ...prev, [agent]: true }));try {- const result = await window.electronAPI.maker.fetchProviderModels({+ const cached = !editing ? discoveryCache.current.get(agent) : undefined;+ const cachedResult = cached?.signature === `${agent}:${requestSig}` ? await cached.promise : undefined;+ if (providerModelFetchRequestSignature(rtRef.current[agent], authModeRef.current) !== requestSig) return;+ const result = cachedResult?.ok ? cachedResult : await window.electronAPI.maker.fetchProviderModels({+ allowEmpty: !editing,agent,baseUrl,authMethod: authMode,@@ -1383,7 +1525,8 @@ export function ProviderConnectionDialog({providerModelFetchRequestSignature(rtRef.current[agent], authModeRef.current) !== requestSig)return; // 过期响应,静默丢弃- if (result.ok && result.models && result.models.length > 0) {+ if (result.ok && result.models) {+ if (!editing) discoveryCache.current.set(agent, { signature: `${agent}:${requestSig}`, promise: Promise.resolve(result) });// 用**响应到达时**的最新表单行构建弹层(rtRef),不是请求发出时的 rf 快照。const current = rtRef.current[agent].models.map((m) => ({@@ -2104,6 +2247,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>+ )}{/* 显示名称(共享) */}<div className="flex flex-col gap-[7px]"><FormField@@ -2237,7 +2392,7 @@ export function ProviderConnectionDialog({})}/><span className="text-12 leading-snug text-[var(--text-tertiary)]">- {templateBound ? (boundPreset ? presetDisplayName(boundPreset, i18n.language) : name) : t(TAB_META[activeTab].helpKey)}+ {templateBound ? (boundPreset ? presetDisplayName(boundPreset, i18n.language) : name) : t(!editing && onDetected ? 'settings.providers.detection.hint' : TAB_META[activeTab].helpKey)}</span></div>@@ -2249,7 +2404,7 @@ export function ProviderConnectionDialog({border: '1px solid var(--settings-theme-card-border)',}}>- {!templateBound && (+ {(editing || !onDetected) && !templateBound && (<div className="flex flex-col gap-[7px]"><FieldLabel>{t('settings.providers.custom.fields.wireProtocol')}</FieldLabel><div className="flex flex-wrap gap-1.5">@@ -2337,7 +2492,7 @@ export function ProviderConnectionDialog({</div>{/* 精确推理路径:给非标准兼容端点使用;留空仍按所选协议推导。 */}- {!templateBound && activeTab !== 'pi' && f.wireProtocol !== 'google-generative-ai' && (+ {(editing || !onDetected) && !templateBound && activeTab !== 'pi' && f.wireProtocol !== 'google-generative-ai' && (<div className="flex flex-col gap-[7px]"><FormFieldid={fieldId(`${activeTab}:requestPath`)}diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsxindex 9d826d7a3f..17c62548bb 100644--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx@@ -91,6 +91,7 @@ import { useProviderSubscriptionCard } from './useProviderSubscriptionCard';import { QuotaHoverCard } from '../status/QuotaHoverCard';import { ProviderConnectionDialog } from './ProviderConnectionDialog';import { AddProviderWizard, type WizardEntry } from './AddProviderWizard';+import type { DetectedProviderDraft } from '../../../shared/providerDetection';import { OllamaProviderDetail } from './OllamaProviderDetail';import {OwnRemoteProviderDetail,@@ -2495,11 +2496,11 @@ export function ProvidersSection() {ids: Set<string>;}>({ dataOwnerId, ids: new Set<string>() });// 向导:null = 关;{ entry } = 打开(entry 指定直达的供应商,来自检测建议)。- const [wizard, setWizard] = useState<null | { entry?: WizardEntry }>(null);+ const [wizard, setWizard] = useState<null | { entry?: WizardEntry; detected?: DetectedProviderDraft }>(null);// 自定义供应商完整表单(编辑,或从向导「自定义端点」进入新建)。const [dialog, setDialog] = useState<| null- | { mode: 'create' }+ | { mode: 'create'; draft?: DetectedProviderDraft }| {mode: 'edit';config: CustomProviderConfig;@@ -3513,6 +3514,8 @@ export function ProvidersSection() {<AddProviderWizardproviders={providers}entry={wizard.entry}+ detected={wizard.detected}+ onReturnCustom={(draft) => { setWizard(null); setDialog({ mode: 'create', draft }); }}onOpenCustomForm={() => {setWizard(null);setDialog({ mode: 'create' });@@ -3528,6 +3531,8 @@ export function ProvidersSection() {{dialog && (<ProviderConnectionDialog+ draft={dialog.mode === 'create' ? dialog.draft : undefined}+ onDetected={(detected) => { setDialog(null); setWizard({ detected }); }}initial={dialog.mode === 'edit' ? dialog.config : undefined}catalogModels={dialog.mode === 'edit' ? providers.find(p =>p.source === 'user' && storedCustomProviderId(p.id) === dialog.config.id)?.models : undefined}diff --git a/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsxindex b2c6996929..3a6edd9bc6 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx@@ -2081,3 +2081,99 @@ it('main provider form contains Tab and blocks dismissal only during the actualawait waitFor(() => expect(onSaved).toHaveBeenCalledOnce());expect(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() {+ 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,+ 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: 'https://api.deepseek.com' } });+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder'), { target: { value: 'fake-key' } });+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });+ return { onDetected, fetchProviderModels };+ }+ it('waits 1.2 seconds and hands off the URL, key and selected models without saving', async () => {+ const { onDetected, fetchProviderModels } = await openIdentification();+ expect(onDetected).not.toHaveBeenCalled();+ await act(async () => { await vi.advanceTimersByTimeAsync(1199); });+ expect(onDetected).not.toHaveBeenCalled();+ await act(async () => { await vi.advanceTimersByTimeAsync(1); });+ 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('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()} />);+ 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' }));+ 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();+ 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();+ await act(async () => { await vi.advanceTimersByTimeAsync(1200); });+ 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('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).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');+ });+});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 8059012e83..97fece84f3 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3768,7 +3768,16 @@"pending": "Preparing credentials","unavailable": "Temporarily unavailable"},- "claudeAccountRetired": "Cindy no longer supports signing in to your subscription through this legacy Claude connection. Your Claude account and subscription are unaffected. Use “Sign in with Claude Code” to connect."+ "claudeAccountRetired": "Cindy no longer supports signing in to your subscription through this legacy Claude connection. Your Claude account and subscription are unaffected. Use “Sign in with Claude Code” to connect.",+ "detection": {+ "hint": "Enter the URL and API key to identify the provider. Protocol settings remain available when editing the saved connection.",+ "pending": "Identifying provider…",+ "matched": "Identified as {{name}}",+ "ambiguous": "Multiple configurations match. Continue with custom settings or choose a provider.",+ "custom": "Continue with custom settings. You can fetch models or add them manually.",+ "configure": "Configure provider",+ "keepCustom": "Continue with custom settings"+ }},"experimental": {"title": "Experimental",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex dfdc6ea1e0..18827d6469 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3737,7 +3737,16 @@"pending": "認証情報を準備中","unavailable": "一時的に利用できません"},- "claudeAccountRetired": "Cindy では、この旧式の Claude 接続を使ったサブスクリプションへのログインに対応していません。Claude アカウントとサブスクリプションには影響ありません。「Claude Code でログイン」から接続してください。"+ "claudeAccountRetired": "Cindy では、この旧式の Claude 接続を使ったサブスクリプションへのログインに対応していません。Claude アカウントとサブスクリプションには影響ありません。「Claude Code でログイン」から接続してください。",+ "detection": {+ "hint": "URL と API キーを入力するとプロバイダーを識別します。保存後、接続の編集でプロトコルを変更できます。",+ "pending": "プロバイダーを識別中…",+ "matched": "{{name}} として識別されました",+ "ambiguous": "複数の設定が一致しました。カスタム設定を続けるか、プロバイダーを選択してください。",+ "custom": "カスタム設定を続けます。モデル一覧を取得するか、手動で追加できます。",+ "configure": "設定に進む",+ "keepCustom": "カスタム設定を続ける"+ }},"experimental": {"title": "実験的機能",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex f06b817167..ec2998121e 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3737,7 +3737,16 @@"pending": "인증 정보 준비 중","unavailable": "일시적으로 사용할 수 없음"},- "claudeAccountRetired": "Cindy에서는 이 이전 Claude 연결 방식으로 구독에 로그인할 수 없습니다. Claude 계정과 구독에는 영향이 없습니다. ‘Claude Code로 로그인’을 사용해 구독을 연결하세요."+ "claudeAccountRetired": "Cindy에서는 이 이전 Claude 연결 방식으로 구독에 로그인할 수 없습니다. Claude 계정과 구독에는 영향이 없습니다. ‘Claude Code로 로그인’을 사용해 구독을 연결하세요.",+ "detection": {+ "hint": "URL과 API 키를 입력하면 제공자를 식별합니다. 저장한 연결을 편집하여 프로토콜을 변경할 수 있습니다.",+ "pending": "제공자 식별 중…",+ "matched": "{{name}}(으)로 식별됨",+ "ambiguous": "여러 설정이 일치합니다. 사용자 지정 설정을 계속하거나 제공자를 선택하세요.",+ "custom": "사용자 지정 설정을 계속합니다. 모델 목록을 가져오거나 직접 추가할 수 있습니다.",+ "configure": "설정으로 이동",+ "keepCustom": "사용자 지정 계속"+ }},"experimental": {"title": "실험적 기능",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 92263d3a19..2da9c5c92e 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3737,7 +3737,16 @@"pending": "凭据准备中","unavailable": "暂时不可用"},- "claudeAccountRetired": "Cindy 已不再支持通过这条旧版 Claude 连接登录订阅,不影响你的 Claude 账号和订阅。请改用「使用 Claude Code 登录」连接订阅"+ "claudeAccountRetired": "Cindy 已不再支持通过这条旧版 Claude 连接登录订阅,不影响你的 Claude 账号和订阅。请改用「使用 Claude Code 登录」连接订阅",+ "detection": {+ "hint": "填写地址和 API 密钥后自动识别供应商。保存后可在编辑连接中调整协议。",+ "pending": "正在识别供应商…",+ "matched": "已识别为 {{name}}",+ "ambiguous": "匹配到多个配置,请继续自定义或选择供应商。",+ "custom": "继续自定义配置,可获取模型列表或手动添加。",+ "configure": "前往配置",+ "keepCustom": "继续自定义"+ }},"experimental": {"title": "实验性功能",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 41c838463c..185ea1b479 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -3737,7 +3737,16 @@"pending": "憑證準備中","unavailable": "暫時無法使用"},- "claudeAccountRetired": "Cindy 已不再支援透過這筆舊版 Claude 連線登入訂閱,不影響你的 Claude 帳號和訂閱。請改用「使用 Claude Code 登入」連線訂閱"+ "claudeAccountRetired": "Cindy 已不再支援透過這筆舊版 Claude 連線登入訂閱,不影響你的 Claude 帳號和訂閱。請改用「使用 Claude Code 登入」連線訂閱",+ "detection": {+ "hint": "填寫網址和 API 金鑰後自動識別供應商。儲存後可在編輯連線中調整協定。",+ "pending": "正在識別供應商…",+ "matched": "已識別為 {{name}}",+ "ambiguous": "符合多個設定,請繼續自訂或選擇供應商。",+ "custom": "繼續自訂設定,可取得模型清單或手動新增。",+ "configure": "前往設定",+ "keepCustom": "繼續自訂"+ }},"experimental": {"title": "實驗性功能",diff --git a/apps/desktop/src/renderer/lib/providerModelFetch.ts b/apps/desktop/src/renderer/lib/providerModelFetch.tsindex aba9c5654b..fb6e5a811d 100644--- a/apps/desktop/src/renderer/lib/providerModelFetch.ts+++ b/apps/desktop/src/renderer/lib/providerModelFetch.ts@@ -17,6 +17,7 @@ import {export type CustomProviderAuthMode = 'apiKey' | 'oauth' | 'none';export interface ProviderModelFetchSignatureFields {+ wireProtocol?: ProviderWireProtocol;baseUrl: string;requestPath: string;modelsUrl: string;@@ -136,6 +137,7 @@ export function providerModelFetchRequestSignature(authMode,baseUrl: fields.baseUrl.trim(),requestPath: fields.requestPath.trim(),+ wireProtocol: fields.wireProtocol,modelsUrl: fields.modelsUrl.trim(),apiKey: authMode === 'apiKey' ? fields.apiKey.trim() : null,headers: Object.entries(effectiveHeaders).sort(([a], [b]) => a.localeCompare(b)),diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 9ea64823c7..8ef48d737a 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -5659,7 +5659,14 @@ interface ElectronAPI {detail?: string;}>;/** 供应商「获取模型列表」—— 表单值透传,结构化结果(code 走 providerError.* i18n)。 */+ detectProvider?: (input: ({ requestId: string; cancel: true } | {+ requestId: string; agent: 'claude-code' | 'codex' | 'pi'; baseUrl: string;+ authMethod: 'apiKey' | 'none'; apiKey?: string | null; headers?: Record<string, string>;+ wireProtocol?: import('@cindy/model-providers').ProviderWireProtocol;+ })) => Promise<import('../shared/providerDetection').DeploymentDetectionResult>;fetchProviderModels: (input: {+ allowEmpty?: boolean;+ redirect?: 'error';agent: 'claude-code' | 'codex' | 'pi';baseUrl: string;authMethod: 'apiKey' | 'oauth' | 'none';diff --git a/apps/desktop/src/shared/providerDetection.ts b/apps/desktop/src/shared/providerDetection.tsnew file mode 100644index 0000000000..32bf697f29--- /dev/null+++ b/apps/desktop/src/shared/providerDetection.ts@@ -0,0 +1,23 @@+import type { AgentKind, CustomProviderConfig, DeploymentProvider, DiscoveredModel, ProviderPreset } from '@cindy/model-providers';+import type { ProviderErrorCode } from './providerErrors.js';++export interface DetectionCatalog {+ ok: boolean;+ models?: DiscoveredModel[];+ code?: ProviderErrorCode;+ status?: number;+}+export interface DeploymentDetectionResult {+ candidates: DeploymentProvider[];+ reason: 'matched' | 'conflict' | 'insufficient_evidence' | 'budget_exhausted';+ catalog?: DetectionCatalog;+}+/** In-memory handoff only. Never persisted or logged. */+export interface DetectedProviderDraft {+ preset: ProviderPreset;+ agent: AgentKind;+ config: CustomProviderConfig;+ apiKey: string;+ keys?: Partial<Record<AgentKind, string>>;+ catalog?: DetectionCatalog;+}diff --git a/docs/product-rules/provider-auto-detection.md b/docs/product-rules/provider-auto-detection.mdnew file mode 100644index 0000000000..68312f9e80--- /dev/null+++ b/docs/product-rules/provider-auto-detection.md@@ -0,0 +1,104 @@+# 根据地址识别供应商并复用连接流程++适用:Desktop 新增自定义连接,Global / 中国大陆版、macOS / Windows 共用同一实现。+现有连接的编辑、订阅登录和保存格式保持原有合同。供应商名称遵循+[供应商设置](./provider-settings.md),模型覆盖顺序遵循+[模型目录维护](../dev-rules/model-catalog-maintenance.md)。++## 用户流程++1. 用户选择当前 Runtime,填写名称、基础 URL 和 API key;请求头仍可选填。+2. 输入稳定 400 ms 后,先按当前供应商目录匹配完整官方地址;未匹配时执行固定系统探测,+ 同时读取通用模型目录。名称、模型勾选变化不重新探测。+3. 只有唯一结果且该预设支持当前 Runtime 时显示“已识别为…”,保留 1200 ms,+ 然后进入已有供应商连接步骤。用户可以立即前往或继续自定义;不会自动保存。+4. 名称、URL、key、请求头、各 Runtime 草稿和模型选择随跳转保留。返回自定义后不再自动跳转。+ 用户打开模型选择等子弹层或正在保存时不强制跳转。+5. 未识别、证据冲突、当前 Runtime 不受支持时保留自定义。成功取得的模型首次直接加入模型区;+ 没有结果时由用户点击“获取模型列表”重试,也可手动添加。失败显示分类原因,不能据此断言站点不能调用。+6. “获取模型列表”优先使用当前输入的成功结果,保留完整勾选弹层。已有的选择、手动模型与显式能力配置优先;+ 后续获取出现的新模型不重新自动全选,已配置但目录不再返回的模型保留。+7. URL、key、请求头、协议或 Runtime 变化使旧结果过期;旧请求不得修改新输入的界面或触发跳转。+ 关闭弹窗、取消、新探测会取消对应的固定系统请求。官方模型读取沿用现有 IPC 的超时,界面丢弃迟到结果。++识别指选择兼容预设,不证明中转服务背后的真实上游厂商;模型目录也不证明每个模型都有调用权限。+本流程只读目录和服务信息,不自动生成内容或逐模型试调用。“测试连接”仍由用户明确点击。++## 地址匹配与绑定++- 遍历当前目录的预设(包括生成目录与已有官方 API 入口),不复制一份地区供应商白名单。+- 官方地址按规范化后的完整 origin/path 匹配,保留业务路径;同域不同路径不能混用。+- Azure 等受约束资源模板使用既有模板绑定;任意 `{endpoint}`、回环地址及端口不能作为身份依据。+- 同地址对应多个套餐时不任意挑选,提示存在多个匹配,允许用户通过已有模板菜单选择。+- 固定系统只有下面五类。用户部署地址替换预设端点,保留部署前缀和各模型路由;+ 不能把用户的地址替换成预设中的 localhost。只绑定当前 Runtime,不创建兄弟账号。+- Global 与中国大陆版仍使用原来的区域排序与可用目录,识别算法不按地区另写一套。++## 固定系统证据++规则版本:`2026-10-19`。所有条件均须满足,不根据 HTTP 200、普通模型 ID、网页标题或 key 前缀判定。+以下是兼容特征规则,不承诺所有历史版本、关闭诊断接口的部署都可识别。++| 系统 | 读取位置(相对部署根) | 充分条件 |+| --- | --- | --- |+| Sub2API | `/api/v1/settings/public`、`/v1/sub2api/billing` | 公开数据 `code=0`、非空版本与三个布尔设置字段;账单 `object=sub2api.key_billing`、`schema_version=1` |+| LiteLLM | `/health/readiness/details`、`/v1/model/info` | 非空 `litellm_version`、healthy、callbacks 数组;非空模型详情,每项有 `model_name`、`litellm_params`、`model_info` |+| LM Studio | `/lmstudio-greeting`、`/api/v1/models` | 原生 models 结构含 key/type/publisher/loaded_instances;非空原生列表,或合法空列表同时 greeting 的 `lmstudio=true` |+| llama.cpp | `/props`、`/v1/models` | generation settings、非负整数 slots、非空 build_info,以及合法模型目录(允许空) |+| vLLM | `/version`、`/v1/models` | 非空版本;非空列表每项 owned_by=vllm、非空 id/root、正整数 max_model_len |++LiteLLM 详情只按对外 `model_name` 关联已取得的账号模型;同别名多个后端只补全一致的能力。+LM Studio 详情按 key 或 loaded_instances.id 关联,不把本机所有已下载模型直接当成可调用列表。+缺失或禁止访问的诊断接口只使识别失败,不能丢弃已经成功取得的通用目录。+同时出现多个充分证据时回到自定义,不按探测完成顺序抢占结果。++## 请求边界++- 仅 http(s),不接受 URL 内嵌用户名/密码、片段、未绑定模板;有 query 或完整调用路径时不派生探测地址。+- 部署根只去掉末尾 `/v1`,不会从 `/team/relay/v1` 爬到域名根。所有探测禁止重定向。+- 公开诊断请求不带 key 或自定义请求头。需要认证的诊断使用用户提供的 Bearer key;+ 可选认证用于 LM Studio 原生目录和 llama.cpp props。不要求管理员 key。+- 最多八个身份请求,同时最多两个,每个 3 秒,总身份预算 8 秒,单响应不超过 1 MiB。+ 已得到充分证据后不再启动其他系统请求,但会收完已发出的请求以发现冲突。+- 通用模型目录使用现有解析器、认证、分页和超时机制,响应上限 8 MiB;它与身份预算分别计时。+- 返回 Renderer 的只有候选、模型元数据和分类错误,绝不返回账单、诊断原文或凭证。+- IPC 复用供应商配置的可信本机窗口校验,按真实 sender 隔离取消;页面销毁、账号代次变化后结果不可复用。+ 不扩大 device-link 的凭证通道。Mobile / 远程页面保持已有配置边界,不新增远程写密钥能力。+- 无鉴权模式保持现有 loopback-only 规则;不因自动识别放宽。++## 协议与保存++匹配后复用预设及 `providerInterfaceDefaultRoute`,再叠加用户显式配置和模型路由。+未匹配时沿用现有新增流程的默认值:Claude Code 为 Messages,Codex 为 Responses,Pi 为 Chat。+Pi 由保存流程写入协议,不把“运行时猜测”作为兜底。创建后仍可在编辑连接中调整协议和路径。++探测结果与凭证只在当前表单内存中传递,保存仍走原来的连接创建和密钥存储。+即使识别为 LM Studio,手工添加的远程地址也创建独立连接,不覆盖托管的本地 LM Studio。++## 验证与限制++自动化覆盖五种充分/不足/冲突证据、路径绑定、区域排序、鉴权隔离、超时/取消/超限响应、+模型别名补全、延迟跳转、取消跳转、陈旧响应、模型选择和返回草稿。+UI 单页夹具使用真实组件和模拟 Host,覆盖官方匹配、Sub2API 匹配、自定义目录成功、失败后手动添加。+浅色/深色、窄窗口、各语言及模拟 Windows 平台的结果随 PR 附证据。++模拟返回与单页检查不等于实站账号调用、Windows 原生运行或所有 Harness 端到端通过。+最终 PR 必须分别记录实测项目、未验证项目和原因;诊断关闭或版本结构变化时继续自定义,不扩大猜测范围。++### 接口规则的研究依据(2026-10-19)++以下来自需求讨论期间保存的独立部署研究记录,不是本 PR 的客户端端到端测试:++| 系统 | 研究样本 | 证据范围和缺口 |+| --- | --- | --- |+| Sub2API | 真实站点自报 0.2.17 | 公开设置和专用计费响应;不推广为全历史版本兼容 |+| LiteLLM | 1.106.0,本机真实代理,master key、无 DB、模拟上游 | 身份和模型详情结构;普通虚拟 key 的详情权限未实测 |+| LM Studio | 官方 llmster 0.0.25+1 | 真实模型列表和最小生成、部署前缀、诊断隐藏;原生 Token 权限未测,Bearer 覆盖来自代理 |+| llama.cpp | b11723,commit `31288c9c6` | 原生 key 的正确/错误/缺失、模型列表和最小生成 |+| vLLM | commit `a608b6e6e05f4b309f77981f010e93c2caa1c677`,macOS CPU | 嵌入/生成实例、原生 key、模型列表和最小生成;不是 GPU/Windows 认证 |++本 PR 用这些结构建立正反例测试;诊断权限不足时必须能够继续自定义,不能要求用户换管理员 key。+LM Studio、llama.cpp、vLLM 的研究使用独立探测脚本,不等同于 Cindy 的三个 Harness 已调用成功。+版本参考:[LM Studio headless](https://lmstudio.ai/docs/developer/core/headless)、+[llama.cpp b11723](https://github.com/ggml-org/llama.cpp/releases/tag/b11723)、+[vLLM 研究源码](https://github.com/vllm-project/vllm/tree/a608b6e6e05f4b309f77981f010e93c2caa1c677)。diff --git a/docs/product-rules/provider-settings.md b/docs/product-rules/provider-settings.mdindex 22ce47548c..d30353653e 100644--- a/docs/product-rules/provider-settings.md+++ b/docs/product-rules/provider-settings.md@@ -4,6 +4,9 @@API 接入、Cindy AI 与本地模型服务。本文定义统一合同;当前实现与验证边界见末节。视觉正本见 [DESIGN §4 Provider detail header](../design-rules/DESIGN.md#provider-detail-header)。+新增连接根据 URL 识别并进入已有配置步骤的规则见+[根据地址识别供应商](./provider-auto-detection.md)。+## 1. 一个连接,一套顶部供应商品牌与连接实例分开:同品牌的多个账号使用同一品牌图标,允许不同显示名。diff --git a/packages/model-providers/src/__tests__/providerDetection.test.ts b/packages/model-providers/src/__tests__/providerDetection.test.tsnew file mode 100644index 0000000000..69a7bd723d--- /dev/null+++ b/packages/model-providers/src/__tests__/providerDetection.test.ts@@ -0,0 +1,96 @@+import { describe, it, expect } from 'vitest';+import { BUNDLED_CATALOG, sortPresetsForRegion } from '../index.js';+import { bindDetectedProvider, classifyProviderAddress, detectDeploymentProviders, enrichDetectedModels, matchOfficialProviders, providerDeploymentRoot, type ProviderEvidence } from '../providerDetection.js';+// Contract: scheme 2 identifies configurations from combined evidence, never a port/model name.+// New production entry; previous catalog tests cover parsing, not identity/binding. Unit, no network.+const presets = BUNDLED_CATALOG.presets ?? [];+const models = { data: [{ id: 'alias', root: 'weights', owned_by: 'vllm', max_model_len: 8192 }] };+const evidence: ProviderEvidence = {+ subPublic: { code: 0, data: { version: '0.2.17', hide_ccs_import_button: false, backend_mode_enabled: true, subscription_enabled: false } },+ subBilling: { object: 'sub2api.key_billing', schema_version: 1 },+ liteReady: { litellm_version: '1.106.0', status: 'healthy', success_callbacks: [] },+ liteModels: { data: [{ model_name: 'alias', litellm_params: {}, model_info: {} }] },+ lmGreeting: { lmstudio: true }, lmModels: { models: [] },+ llamaProps: { default_generation_settings: {}, total_slots: 1, build_info: 'b11723' },+ vllmVersion: { version: '0.0.0+source.test' }, models,+};++describe('deployment evidence', () => {+ it.each([+ ['sub2api', ['subPublic', 'subBilling']], ['litellm', ['liteReady', 'liteModels']],+ ['lmstudio', ['lmGreeting', 'lmModels']], ['llamacpp', ['llamaProps', 'models']], ['vllm', ['vllmVersion', 'models']],+ ] as const)('requires combined evidence for %s', (id, keys) => {+ const input = Object.fromEntries(keys.map(k => [k, evidence[k]]));+ expect(detectDeploymentProviders(input)).toEqual([id]);+ for (const key of keys) expect(detectDeploymentProviders({ [key]: evidence[key] })).toEqual([]);+ });+ it('retains contradictory matches instead of choosing the first response', () => {+ expect(detectDeploymentProviders(evidence)).toEqual(['sub2api', 'litellm', 'lmstudio', 'llamacpp', 'vllm']);+ });+ it('rejects error bodies and coerced number/boolean fields', () => {+ expect(detectDeploymentProviders({ ...evidence, subPublic: { code: false, data: (evidence.subPublic as any).data }, subBilling: { object: 'sub2api.key_billing', schema_version: true },+ liteReady: { status: 'healthy' }, lmModels: { error: 'not found' }, llamaProps: { default_generation_settings: {}, total_slots: '1', build_info: 'x' }, models: { data: [{ id: 'alias', root: 'x', owned_by: 'vllm', max_model_len: true }] },+ })).toEqual([]);+ });+ it('accepts a nonempty native LM directory without the greeting, and rejects unknown types', () => {+ const native = { key: 'weights', type: 'embedding', publisher: 'test', loaded_instances: [] };+ expect(detectDeploymentProviders({ lmModels: { models: [native] } })).toEqual(['lmstudio']);+ expect(detectDeploymentProviders({ lmModels: { models: [{ ...native, type: 'unknown' }] } })).toEqual([]);+ });+ it('does not turn internal aliases into account-visible membership or maximize conflicting capabilities', () => {+ const result = enrichDetectedModels([{ id: 'public-alias', name: 'Alias' }], 'litellm', { liteModels: { data: [+ { model_name: 'public-alias', model_info: { id: 'deployment-1', max_input_tokens: 8192 } },+ { model_name: 'public-alias', model_info: { id: 'deployment-2', max_input_tokens: 32768 } },+ { model_name: 'hidden', model_info: {} },+ ] } });+ expect(result.map(m => m.id)).toEqual(['public-alias']);+ expect(result[0].discoveredMetadata?.contextWindow).toBeUndefined();+ });+ it('maps LM loaded instance aliases while retaining embedding type', () => {+ const result = enrichDetectedModels([{ id: 'friendly', name: 'Friendly' }], 'lmstudio', { lmModels: { models: [+ { key: 'file-name', type: 'embedding', publisher: 'test', loaded_instances: [{ id: 'friendly' }] },+ ] } });+ expect(result[0]).toMatchObject({ id: 'friendly', discoveredMetadata: { mode: 'embedding' } });+ });+});++describe('catalog mapping independent of desktop platform', () => {+ it.each(['cn', 'global'] as const)('classifies the entire active catalog without region filtering: %s', region => {+ expect(presets.length).toBeGreaterThan(28);+ for (const p of sortPresetsForRegion(presets, region)) {+ expect(['deployment', 'resource-template', 'official', 'manual']).toContain(classifyProviderAddress(p));+ if (classifyProviderAddress(p) !== 'official') continue;+ for (const runtime of Object.values(p.runtimes)) {+ if (runtime) expect(matchOfficialProviders(runtime.baseUrl, presets).map(p => p.id)).toContain(p.id);+ }+ }+ });+ it('matches exact official origin and business path, preserving multi-plan candidates', () => {+ const original = presets.find(p => p.id === 'deepseek')!;+ const url = original.runtimes.pi!.baseUrl;+ expect(matchOfficialProviders(url, [original, { ...original, id: 'same-address-plan' }])).toHaveLength(2);+ expect(matchOfficialProviders(url.replace('api.deepseek.com', 'api.deepseek.com.evil.test'), presets)).toEqual([]);+ expect(matchOfficialProviders(url + '/unregistered', presets)).toEqual([]);+ expect(matchOfficialProviders(url + '?token=fake', presets)).toEqual([]);+ });+ it('never identifies loopback ports or the generic endpoint template as a brand', () => {+ expect(matchOfficialProviders('http://127.0.0.1:1234/v1', presets)).toEqual([]);+ expect(matchOfficialProviders('https://unknown.example/team/v1', presets)).toEqual([]);+ });+ it.each(['sub2api', 'litellm', 'lmstudio', 'llamacpp', 'vllm'])('binds %s to the remote prefix, never localhost', id => {+ const preset = presets.find(p => p.id === id)!;+ for (const agent of ['claude-code', 'codex', 'pi'] as const) {+ const bound = bindDetectedProvider(preset, agent, 'https://relay.example/team/v1');+ if (!preset.runtimes[agent]) { expect(bound).toBeUndefined(); continue; }+ expect(bound).toBeDefined();+ expect(bound!.runtimes[agent]!.baseUrl).toMatch(/^https:\/\/relay\.example\/team(?:\/v1)?$/);+ expect(Object.keys(bound!.runtimes)).toEqual([agent]);+ if (bound!.runtimes[agent]!.modelsUrl) expect(bound!.runtimes[agent]!.modelsUrl).toMatch(/^https:\/\/relay\.example\/team\//);+ }+ });+ it('keeps business prefixes and rejects unsafe probe derivation', () => {+ expect(providerDeploymentRoot('https://EXAMPLE.com:443/team/v1/')).toBe('https://example.com/team');+ expect(providerDeploymentRoot('http://[::1]:8080/team')).toBe('http://[::1]:8080/team');+ for (const url of ['file:///tmp/x', 'https://user:[email protected]/v1', 'https://example.com/v1?token=fake', 'https://example.com/v1#x', 'https://example.com/v1/chat/completions']) expect(providerDeploymentRoot(url)).toBeUndefined();+ });+});diff --git a/packages/model-providers/src/index.ts b/packages/model-providers/src/index.tsindex ef7985cea3..c940f0b6bf 100644--- a/packages/model-providers/src/index.ts+++ b/packages/model-providers/src/index.ts@@ -334,3 +334,4 @@ export { providerSetupLink } from './providerSetupLinks.js';export { providerPresetOAuth, providerPresetOAuthRuntimes, providerOAuthContract } from './providerPresetOAuth.js';export { alignModelApiRoute, providerWireProtocolForApi, providerBaseUrlForApi } from "./providerInterfaceRoutes.js";+export * from './providerDetection.js';diff --git a/packages/model-providers/src/providerDetection.ts b/packages/model-providers/src/providerDetection.tsnew file mode 100644index 0000000000..7062ff7a76--- /dev/null+++ b/packages/model-providers/src/providerDetection.ts@@ -0,0 +1,149 @@+import type { AgentKind, ProviderPreset, ProviderPresetRuntime } from './types.js';+import { bindProviderPresetRuntime, providerEndpointBindings } from './providerEndpointTemplate.js';+import { providerInterfaceDefaultRoute } from './providerInterfaceRoutes.js';+import { parseModelsListResponse } from './modelDiscovery.js';+import type { DiscoveredModel, ModelMetadata } from './modelMetadataLayers.js';++/** Compatibility fingerprints, never an assertion about a model's upstream manufacturer. */+export const DETECTION_RULE_VERSION = '2026-10-19';+export const DEPLOYMENT_PROVIDERS = ['sub2api', 'litellm', 'lmstudio', 'llamacpp', 'vllm'] as const;+export type DeploymentProvider = typeof DEPLOYMENT_PROVIDERS[number];+export type ProviderEvidence = Partial<Record<'subPublic' | 'subBilling' | 'liteReady' | 'liteModels' | 'lmGreeting' | 'lmModels' | 'llamaProps' | 'vllmVersion' | 'models', unknown>>;+const object = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);+const text = (v: unknown): v is string => typeof v === 'string' && v.trim().length > 0;+const integer = (v: unknown): v is number => typeof v === 'number' && Number.isInteger(v);+const list = (v: unknown, key: string): unknown[] | undefined => object(v) && Array.isArray(v[key]) ? v[key] : undefined;++export function detectDeploymentProviders(e: ProviderEvidence): DeploymentProvider[] {+ const hits: DeploymentProvider[] = [];+ const pub = object(e.subPublic) ? e.subPublic : {};+ const data = object(pub.data) ? pub.data : {};+ const billing = object(e.subBilling) ? e.subBilling : {};+ if (pub.code === 0 && text(data.version)+ && ['hide_ccs_import_button', 'backend_mode_enabled', 'subscription_enabled'].every(k => typeof data[k] === 'boolean')+ && billing.object === 'sub2api.key_billing' && billing.schema_version === 1) hits.push('sub2api');+ const ready = object(e.liteReady) ? e.liteReady : {};+ const lite = list(e.liteModels, 'data');+ if (text(ready.litellm_version) && ready.status === 'healthy' && Array.isArray(ready.success_callbacks)+ && lite?.length && lite.every(m => object(m) && text(m.model_name) && object(m.litellm_params) && object(m.model_info))) hits.push('litellm');+ const lm = list(e.lmModels, 'models');+ const native = lm?.every(m => object(m) && text(m.key) && ['llm', 'embedding'].includes(String(m.type))+ && typeof m.publisher === 'string' && Array.isArray(m.loaded_instances));+ if (native && ((object(e.lmGreeting) && e.lmGreeting.lmstudio === true) || !!lm?.length)) hits.push('lmstudio');+ const models = list(e.models, 'data');+ const validModels = models?.every(m => object(m) && text(m.id));+ const props = object(e.llamaProps) ? e.llamaProps : {};+ if (object(props.default_generation_settings) && integer(props.total_slots) && props.total_slots >= 0+ && text(props.build_info) && validModels) hits.push('llamacpp');+ if (object(e.vllmVersion) && text(e.vllmVersion.version) && models?.length+ && models.every(m => object(m) && text(m.id) && text(m.root) && m.owned_by === 'vllm'+ && integer(m.max_model_len) && m.max_model_len > 0)) hits.push('vllm');+ return hits;+}++/** Details enrich account-visible IDs only. Deployment aliases never become new members. */+export function enrichDetectedModels(models: readonly DiscoveredModel[], system: DeploymentProvider, evidence: ProviderEvidence): DiscoveredModel[] {+ const entries = system === 'litellm' ? list(evidence.liteModels, 'data') : system === 'lmstudio' ? list(evidence.lmModels, 'models') : undefined;+ if (!entries) return [...models];+ return models.map(model => {+ const matches = entries.filter(entry => object(entry) && (system === 'litellm' ? entry.model_name === model.id+ : entry.key === model.id || (Array.isArray(entry.loaded_instances) && entry.loaded_instances.some(instance => object(instance) && instance.id === model.id))));+ if (!matches.length || (system === 'lmstudio' && matches.length !== 1)) return model;+ const metadata = matches.map(entry => {+ const record = entry as Record<string, unknown>;+ return parseModelsListResponse({ data: [{ ...record, id: model.id,+ ...(system === 'lmstudio' ? { mode: record.type === 'embedding' ? 'embedding' : 'chat' } : {}),+ }] })?.[0]?.discoveredMetadata ?? {};+ });+ // Multiple backends sharing an alias: only facts declared identically by every backend.+ const common = Object.fromEntries(Object.entries(metadata[0]).filter(([key, value]) =>+ metadata.every(m => JSON.stringify(m[key as keyof ModelMetadata]) === JSON.stringify(value)))) as ModelMetadata;+ return { ...model, discoveredMetadata: { ...common, ...model.discoveredMetadata } };+ });+}++export function detectionUrl(value: string): URL | undefined {+ try {+ const url = new URL(value);+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.hash || /[{}]/.test(value)) return;+ url.pathname = url.pathname.replace(/\/+$/, '') || '/';+ return url;+ } catch { return; }+}+const clean = (value: string) => value.replace(/\/+$/, '');++/** Never climb business prefixes or propagate query credentials into diagnostic endpoints. */+export function providerDeploymentRoot(value: string): string | undefined {+ const url = detectionUrl(value);+ if (!url || url.search || /\/(?:responses|completions|messages|models)$/.test(url.pathname)) return;+ url.pathname = url.pathname.replace(/\/v1$/, '') || '/';+ return clean(url.toString());+}++export type ProviderAddressClass = 'deployment' | 'resource-template' | 'official' | 'manual';+export function classifyProviderAddress(preset: ProviderPreset): ProviderAddressClass {+ if ((DEPLOYMENT_PROVIDERS as readonly string[]).includes(preset.id)) return 'deployment';+ const urls = Object.values(preset.runtimes).flatMap(rt => rt ? [rt.baseUrl] : []);+ if (!urls.length) return 'manual';+ if (urls.some(url => url.includes('{endpoint}') || /^http:\/\/(localhost|127\.|\[::1\])/.test(url))) return 'manual';+ if (urls.some(url => url.includes('{'))) return 'resource-template';+ return urls.every(url => detectionUrl(url)) ? 'official' : 'manual';+}++/** Exact official addresses; localhost and arbitrary endpoint templates are not identities. */+export function matchOfficialProviders(baseUrl: string, presets: readonly ProviderPreset[]): ProviderPreset[] {+ const url = detectionUrl(baseUrl);+ if (!url || url.search) return [];+ return presets.filter(preset => {+ const kind = classifyProviderAddress(preset);+ if (kind === 'deployment' || kind === 'manual') return false;+ return Object.values(preset.runtimes).some(rt => {+ if (!rt) return false;+ if (rt.baseUrl.includes('{')) return !!providerEndpointBindings(rt.baseUrl, clean(url.toString()));+ const declared = detectionUrl(rt.baseUrl);+ return declared && !declared.search && clean(declared.toString()) === clean(url.toString());+ });+ });+}++/** Bind only the selected harness. Do not create sibling accounts or inherit localhost. */+export function bindDetectedProvider(preset: ProviderPreset, agent: AgentKind, input: string): ProviderPreset | undefined {+ const original = preset.runtimes[agent];+ if (!original) return;+ let runtime: ProviderPresetRuntime;+ if (classifyProviderAddress(preset) === 'deployment') {+ const root = providerDeploymentRoot(input);+ if (!root) return;+ // Only the verified root / v1 relationship is portable to arbitrary deployments.+ const template = original.baseUrl.replace('https://{endpoint}', 'https://deployment.invalid');+ const base = detectionUrl(template);+ if (!base || !['/', '/v1'].includes(base.pathname)) return;+ const resolved = providerInterfaceDefaultRoute(preset.id, agent, original.baseUrl);+ const route = detectionUrl(resolved?.baseUrl ?? template);+ if (!route || !['/', '/v1'].includes(route.pathname)) return;+ const rebase = (value: string): string | undefined => {+ const u = detectionUrl(value.replace('https://{endpoint}', 'https://deployment.invalid'));+ if (!u || u.origin !== base.origin) return;+ return root + (u.pathname === '/' ? '' : u.pathname) + u.search;+ };+ const modelsUrl = original.modelsUrl ? rebase(original.modelsUrl) : undefined;+ if (original.modelsUrl && !modelsUrl) return;+ runtime = { ...original, baseUrl: root + (route.pathname === '/' ? '' : route.pathname),+ ...(resolved ? { wireProtocol: resolved.wireProtocol } : {}), modelsUrl,+ // Discovery/member defaults must not retain deployment-local routes.+ models: original.models.map(m => ({ ...m, ...(m.route ? { route: { ...m.route, baseUrl: rebase(m.route.baseUrl) ?? '' } } : {}) })),+ modelDiscovery: original.modelDiscovery?.map(s => ({ ...s, baseUrl: rebase(s.baseUrl) ?? '', modelsUrl: s.modelsUrl ? rebase(s.modelsUrl) : undefined })),+ };+ if (runtime.models.some(m => m.route && !m.route.baseUrl) || runtime.modelDiscovery?.some(s => !s.baseUrl)) return;+ } else {+ const source = Object.values(preset.runtimes).find(rt => rt && providerEndpointBindings(rt.baseUrl, input));+ const bindings = source && providerEndpointBindings(source.baseUrl, input);+ const target = original.baseUrl.includes('{') && bindings+ ? original.baseUrl.replace(/\{([^}]+)\}/g, (token, key: string) => bindings[key] ?? token) : original.baseUrl;+ runtime = bindProviderPresetRuntime(original, original.baseUrl.includes('{') && providerEndpointBindings(original.baseUrl, input) ? input : target);+ const resolved = providerInterfaceDefaultRoute(preset.id, agent, input);+ if (resolved) runtime = { ...runtime, ...resolved };+ if (!detectionUrl(runtime.baseUrl)) return;+ }+ return { ...preset, runtimes: { [agent]: { ...runtime, baseUrlEditable: true } } };+}