Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(providers): complete protocol detection and connection save regressions

xdec88e9c18ed3
diff --git a/apps/desktop/scripts/fixtures/provider-detection/provider-detection-fixture.tsx b/apps/desktop/scripts/fixtures/provider-detection/provider-detection-fixture.tsx
index 40a36bf13a..38ba18c9f4 100644
--- a/apps/desktop/scripts/fixtures/provider-detection/provider-detection-fixture.tsx
+++ b/apps/desktop/scripts/fixtures/provider-detection/provider-detection-fixture.tsx
@@ -6,8 +6,16 @@ import { AddProviderWizard } from '../../../src/renderer/components/settings/Add
import type { DetectedProviderDraft } from '../../../src/shared/providerDetection';
const models = ['example-chat', 'example-reasoning', 'example-vision', 'example-fast', 'example-long-context'].map(id => ({ id, name: id, discoveredMetadata: { mode: 'chat' as const } }));
-function Page() {
- const [identified, setIdentified] = useState<DetectedProviderDraft>();
+const evidence: { tests: unknown[]; saved?: unknown } = { tests: [] };
+Object.assign(window, { providerP1Evidence: evidence });
+const disabledDraft: DetectedProviderDraft = {
+ agent: 'pi', apiKey: 'fake-ui-key', keys: { pi: 'fake-ui-key' },
+ preset: { id: 'review-fixture', name: 'Review fixture', runtimes: { pi: { baseUrl: 'https://fixture.example/v1', wireProtocol: 'openai-chat', models: [] } } },
+ config: { id: 'draft', name: 'Selection fixture', runtimes: { pi: { baseUrl: 'https://fixture.example/v1', models: [{ id: 'disabled-model', name: 'disabled-model', defaultEnabled: false }] } } },
+ catalog: { ok: true, models: [{ id: 'disabled-model', name: 'disabled-model' }] },
+};
+function Page({ scenario }: { scenario: string }) {
+ const [identified, setIdentified] = useState<DetectedProviderDraft | undefined>(['reenable', 'return-reenable'].includes(scenario) ? disabledDraft : undefined);
const [draft, setDraft] = useState<DetectedProviderDraft>();
return identified ? <AddProviderWizard providers={[]} detected={identified}
onReturnCustom={value => { setDraft(value); setIdentified(undefined); }}
@@ -17,7 +25,11 @@ function Page() {
}
mountPage({
host: ctx => ({ maker: {
- listProviderPresets: async () => ({ presets: BUNDLED_CATALOG.presets }),
+ listProviderPresets: async () => ({ presets: [
+ ...(BUNDLED_CATALOG.presets ?? []),
+ ...(ctx.case === 'loopback-identity' ? [{ id: 'local-custom-brand', name: 'Local custom', runtimes: { pi: { baseUrl: 'https://localhost:1234/v1', models: [] } } }] : []),
+ ...(ctx.case === 'ambiguous-official' ? [{ ...BUNDLED_CATALOG.presets!.find(p => p.id === 'deepseek')!, id: 'same-address-plan' }] : []),
+ ] }),
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'] : ctx.case === 'litellm' ? ['litellm'] : [], reason: ['relay', 'litellm'].includes(ctx.case) ? 'matched' : 'insufficient_evidence',
@@ -25,8 +37,12 @@ mountPage({
localModelList: async () => ({ status: { kind: 'absent', appInstalled: false }, models: [], memoryGb: 0 }),
scanLocalCli: async () => ({ detections: [] }),
onProviderOAuthProgress: subscription('providerOAuthProgress'),
- createCustomProvider: forbid('createCustomProvider'),
- testProviderConnection: forbid('testProviderConnection'),
+ createCustomProvider: ctx.case.startsWith('cloudflare-') || ['local-noauth', 'reenable', 'return-reenable', 'custom-port'].includes(ctx.case)
+ ? async (config: unknown) => { evidence.saved = config; return { ok: true }; }
+ : forbid('createCustomProvider'),
+ testProviderConnection: ctx.case === 'local-noauth'
+ ? async (input: unknown) => { evidence.tests.push(input); return { ok: true, latencyMs: 1 }; }
+ : forbid('testProviderConnection'),
} }),
- render: () => <Page />,
+ render: ctx => <Page scenario={ctx.case} />,
});
diff --git a/apps/desktop/scripts/fixtures/provider-detection/ui-page.mjs b/apps/desktop/scripts/fixtures/provider-detection/ui-page.mjs
index 2b47664041..9877802875 100644
--- a/apps/desktop/scripts/fixtures/provider-detection/ui-page.mjs
+++ b/apps/desktop/scripts/fixtures/provider-detection/ui-page.mjs
@@ -5,6 +5,14 @@ export default {
real: 'ProviderConnectionDialog and AddProviderWizard, delayed handoff, model selection, translations and themes',
notCovered: 'Network/IPC logic has separate injected production-unit tests. Live credentials, persistence integration and actual harness calls are not covered here. Windows platform is simulated when requested.',
cases: {
+ 'loopback-identity': { about: 'HTTPS loopback address is not an official brand even if a catalog entry uses it' },
+ 'ambiguous-official': { about: 'Two official plans sharing an address do not choose a provider automatically' },
+ ...Object.fromEntries(['gateway', 'workers'].flatMap(kind => ['scheme', 'host', 'port'].map(variant =>
+ [`cloudflare-${kind}-${variant}`, { about: 'Normalized Cloudflare address enters its wizard and saves account-bound engine routes' }]))),
+ 'return-reenable': { about: 'Checked previously disabled model survives wizard back and custom save' },
+ 'custom-port': { about: 'Azure and Vertex custom ports stay custom and are saved unchanged' },
+ 'local-noauth': { about: 'Local empty key remains editable; key changes affect test auth and saving keeps no-auth' },
+ reenable: { about: 'A checked model with an old disabled draft is enabled in the saved payload' },
empty: { about: 'HTML design: one default connection, collapsed manual entry and bottom actions' },
return: { about: 'Return from the identified wizard with inputs preserved and no automatic navigation' },
default: { about: 'Official address matches DeepSeek and enters its existing connection step' },
@@ -16,6 +24,98 @@ export default {
},
async ready(page) { await page.getByRole('dialog').waitFor(); },
async check(page, ui) {
+ if (['loopback-identity', 'ambiguous-official'].includes(ui.case)) {
+ const address = ui.case === 'loopback-identity' ? 'https://localhost:1234/v1' : 'https://api.deepseek.com';
+ await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.apiKeyPlaceholder')).fill('fake-ui-key');
+ await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.baseUrlPlaceholder')).fill(address);
+ await page.getByText(await ui.t(ui.case === 'loopback-identity' ? 'settings.providers.detection.custom' : 'settings.providers.detection.ambiguous'), { exact: true }).waitFor();
+ await page.waitForTimeout(1500);
+ assert.equal(await page.getByRole('button', { name: await ui.t('settings.providers.detection.configure'), exact: true }).count(), 0);
+ assert.equal(await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.baseUrlPlaceholder')).inputValue(), address);
+ await ui.capture('stayed-custom');
+ return;
+ }
+ if (ui.case.startsWith('cloudflare-')) {
+ const [, kind, variant] = ui.case.split('-');
+ const canonical = kind === 'gateway' ? 'https://gateway.ai.cloudflare.com/v1/ReviewAccount/ReviewGateway/anthropic'
+ : 'https://api.cloudflare.com/client/v4/accounts/ReviewAccount/ai/v1';
+ const input = variant === 'scheme' ? canonical.replace('https:', 'HTTPS:')
+ : variant === 'host' ? canonical.replace(/^(https:\/\/)([^/]+)/, (_, scheme, host) => scheme + host.toUpperCase())
+ : canonical.replace(/^(https:\/\/)([^/]+)/, '$1$2:443');
+ await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.namePlaceholder')).fill('Cloudflare review');
+ await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.apiKeyPlaceholder')).fill('fake-ui-key');
+ await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.baseUrlPlaceholder')).fill(input);
+ await page.getByRole('button', { name: await ui.t('settings.providers.wizard.next'), exact: true }).waitFor();
+ await ui.capture('normalized-handoff');
+ 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 }).click();
+ await page.waitForFunction(() => window.providerP1Evidence?.saved);
+ const saved = await page.evaluate(() => window.providerP1Evidence.saved);
+ assert.equal(saved.name, 'Cloudflare review');
+ for (const agent of ['claude-code', 'codex', 'pi']) {
+ const runtime = saved.runtimes[agent];
+ assert.ok(runtime, agent);
+ assert.equal(runtime.catalogPresetId, kind === 'gateway' ? 'cloudflare-ai-gateway' : 'cloudflare-workers-ai');
+ assert.equal(new URL(runtime.baseUrl).hostname, new URL(canonical).hostname);
+ assert.equal(new URL(runtime.baseUrl).port, '');
+ assert.ok(runtime.baseUrl.includes('/ReviewAccount/'));
+ if (kind === 'gateway') assert.ok(runtime.baseUrl.includes('/ReviewGateway/'));
+ assert.ok(!runtime.baseUrl.includes('{'));
+ assert.ok(runtime.models.some(model => model.id === 'example-chat'));
+ }
+ return;
+ }
+ if (['reenable', 'return-reenable'].includes(ui.case)) {
+ await page.getByRole('button', { name: await ui.t('settings.providers.wizard.next'), exact: true }).click();
+ const finish = page.getByRole('button', { name: await ui.t('settings.providers.wizard.finish'), exact: true });
+ await finish.waitFor();
+ await ui.capture('checked-previously-disabled');
+ if (ui.case === 'return-reenable') {
+ const back = page.getByRole('button', { name: await ui.t('settings.providers.wizard.back'), exact: true });
+ await back.click(); await back.click();
+ await page.getByRole('button', { name: await ui.t('settings.providers.connection.saveProvider'), exact: true }).click();
+ } else await finish.click();
+ await page.waitForFunction(() => window.providerP1Evidence?.saved);
+ const saved = await page.evaluate(() => window.providerP1Evidence.saved);
+ assert.notEqual(saved.runtimes.pi.models[0].defaultEnabled, false);
+ return;
+ }
+ if (ui.case === 'custom-port') {
+ const address = page.getByPlaceholder(await ui.t('settings.providers.custom.fields.baseUrlPlaceholder'));
+ await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.namePlaceholder')).fill('Port fixture');
+ await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.apiKeyPlaceholder')).fill('fake-ui-key');
+ for (const input of ['https://reviewaccount.openai.azure.com:9443/openai/v1', 'https://us-central1-aiplatform.googleapis.com:9443']) {
+ await address.fill(input);
+ await page.getByText(await ui.t('settings.providers.detection.custom'), { exact: true }).waitFor();
+ await page.waitForTimeout(1400);
+ assert.equal(await address.inputValue(), input);
+ assert.equal(await page.getByRole('button', { name: await ui.t('settings.providers.detection.configure'), exact: true }).count(), 0);
+ }
+ await ui.capture('custom-port-preserved');
+ await page.getByRole('button', { name: await ui.t('settings.providers.connection.saveProvider'), exact: true }).click();
+ await page.waitForFunction(() => window.providerP1Evidence?.saved);
+ assert.equal(new URL(await page.evaluate(() => window.providerP1Evidence.saved.runtimes.pi.baseUrl)).port, '9443');
+ return;
+ }
+ if (ui.case === 'local-noauth') {
+ await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.namePlaceholder')).fill('Local fixture');
+ await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.baseUrlPlaceholder')).fill('http://127.0.0.1:1234/v1');
+ await page.getByText('example-chat', { exact: false }).first().waitFor();
+ const key = page.getByPlaceholder(await ui.t('settings.providers.custom.fields.apiKeyPlaceholder'));
+ const test = page.getByRole('button', { name: await ui.t('settings.providers.custom.test.button'), exact: true });
+ for (const [value, method] of [['', 'none'], ['fake-ui-key', 'apiKey'], ['', 'none']]) {
+ await key.fill(value);
+ const before = await page.evaluate(() => window.providerP1Evidence.tests.length);
+ await test.click();
+ await page.waitForFunction(count => window.providerP1Evidence.tests.length > count, before);
+ assert.equal(await page.evaluate(() => window.providerP1Evidence.tests.at(-1).spec.authMethod), method);
+ }
+ await ui.capture('local-noauth-tested');
+ await page.getByRole('button', { name: await ui.t('settings.providers.connection.saveProvider'), exact: true }).click();
+ await page.waitForFunction(() => window.providerP1Evidence?.saved);
+ assert.equal(await page.evaluate(() => window.providerP1Evidence.saved.auth.method), 'none');
+ return;
+ }
if (ui.case === 'empty') {
assert.equal(await page.getByRole('tablist').count(), 0);
assert.equal(await page.getByLabel(await ui.t('settings.providers.connection.manualId'), { exact: true }).count(), 0);
@@ -43,7 +143,9 @@ export default {
await page.getByRole('button', { name: await ui.t('settings.providers.wizard.finish'), exact: true }).waitFor();
await ui.capture('models', { locator: page.getByRole('dialog') });
} else {
- await page.getByText(await ui.t('settings.providers.detection.custom'), { exact: true }).waitFor();
+ // Authentication rejection has its own field error; generic fallback copy is intentionally absent.
+ await page.getByText(await ui.t(ui.case === 'failed'
+ ? 'settings.providers.detection.authRejected' : 'settings.providers.detection.custom'), { exact: true }).waitFor();
if (['custom', 'manual-fetch'].includes(ui.case)) {
await ui.capture('custom-model-list', { locator: page.getByRole('dialog') });
await page.getByRole('button', { name: await ui.t('settings.providers.custom.fetch.button'), exact: true }).scrollIntoViewIfNeeded();
diff --git a/apps/desktop/scripts/fixtures/provider-template-catalog/cases.ts b/apps/desktop/scripts/fixtures/provider-template-catalog/cases.ts
new file mode 100644
index 0000000000..d437919065
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/provider-template-catalog/cases.ts
@@ -0,0 +1,16 @@
+import { BUNDLED_CATALOG } from '@cindy/model-providers';
+// Enumerate the live bundled catalog; adding a template automatically adds browser cases.
+export const presets = BUNDLED_CATALOG.presets ?? [];
+export const deployments = ['sub2api', 'litellm', 'lmstudio', 'llamacpp', 'vllm'];
+export const bindInput = (url: string) => url.replace(/\{([^}]+)\}/g, (_, key) => key === 'location' ? 'us-central1' : key === 'endpoint' ? 'relay.example/team' : 'ReviewAccount');
+export const cases = presets.flatMap(p => {
+ const urls = [...new Set(Object.values(p.runtimes).flatMap(rt => rt ? [bindInput(rt.baseUrl)] : []))];
+ return [
+ { id: `wizard-${p.id}`, kind: 'wizard', providerId: p.id, address: '', expectedIds: [p.id] },
+ ...urls.map((address, i) => ({ id: `address-${p.id}-${i}`, kind: 'address', providerId: p.id, address,
+ // Expected ambiguity comes from declared catalog addresses, not the matcher under test.
+ expectedIds: deployments.includes(p.id) ? [p.id] : presets.filter(other => !deployments.includes(other.id)
+ && Object.values(other.runtimes).some(rt => rt && bindInput(rt.baseUrl) === address)).map(other => other.id),
+ })),
+ ];
+});
diff --git a/apps/desktop/scripts/fixtures/provider-template-catalog/fixture.tsx b/apps/desktop/scripts/fixtures/provider-template-catalog/fixture.tsx
new file mode 100644
index 0000000000..de3f5efe25
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/provider-template-catalog/fixture.tsx
@@ -0,0 +1,35 @@
+import { useState } from 'react';
+import { mountPage, forbid, subscription } from '../../ui-page/harness';
+import { ProviderConnectionDialog } from '../../../src/renderer/components/settings/ProviderConnectionDialog';
+import { AddProviderWizard } from '../../../src/renderer/components/settings/AddProviderWizard';
+import type { DetectedProviderDraft } from '../../../src/shared/providerDetection';
+import { cases, presets, deployments } from './cases';
+const evidence: { saved?: unknown; handoff?: DetectedProviderDraft; fetches: unknown[] } = { fetches: [] };
+Object.assign(window, { templateEvidence: evidence, templateIds: presets.map(p => p.id) });
+function Page({ scenario }: { scenario: string }) {
+ const item = cases.find(c => c.id === scenario) ?? cases[0];
+ const [detected, setDetected] = useState<DetectedProviderDraft>();
+ const [draft, setDraft] = useState<DetectedProviderDraft>();
+ return item.kind === 'wizard' || detected ? <AddProviderWizard providers={[]}
+ entry={item.kind === 'wizard' ? { kind: 'preset', presetId: item.providerId } : undefined}
+ detected={detected} onClose={() => undefined} onDone={() => undefined} onOpenCustomForm={() => undefined}
+ onReturnCustom={value => { setDraft(value); setDetected(undefined); }} />
+ : <ProviderConnectionDialog draft={draft} onDetected={value => { evidence.handoff = value; setDetected(value); }} onClose={() => undefined} onSaved={() => undefined} />;
+}
+const models = [{ id: 'ui-catalog-probe', name: 'UI catalog probe', discoveredMetadata: { mode: 'chat' as const } }];
+mountPage({
+ host: ctx => {
+ const item = cases.find(c => c.id === ctx.case) ?? cases[0];
+ return { maker: {
+ listProviderPresets: async () => ({ presets }),
+ fetchProviderModels: async (input: unknown) => { evidence.fetches.push(input); return { ok: true, models }; },
+ detectProvider: async (input: { cancel?: boolean }) => ({ candidates: !input.cancel && deployments.includes(item.providerId) ? [item.providerId] : [], reason: 'matched', catalog: { ok: true, models } }),
+ localModelList: async () => ({ status: { kind: 'absent', appInstalled: false }, models: [], memoryGb: 0 }),
+ scanLocalCli: async () => ({ detections: [] }),
+ onProviderOAuthProgress: subscription('providerOAuthProgress'),
+ createCustomProvider: async (config: unknown) => { evidence.saved = config; return { ok: true }; },
+ testProviderConnection: forbid('testProviderConnection'),
+ } };
+ },
+ render: ctx => <Page scenario={ctx.case} />,
+});
diff --git a/apps/desktop/scripts/fixtures/provider-template-catalog/ui-page.mjs b/apps/desktop/scripts/fixtures/provider-template-catalog/ui-page.mjs
new file mode 100644
index 0000000000..ff832fb2e3
--- /dev/null
+++ b/apps/desktop/scripts/fixtures/provider-template-catalog/ui-page.mjs
@@ -0,0 +1,75 @@
+import assert from 'node:assert/strict';
+import { build } from 'esbuild';
+import { fileURLToPath } from 'node:url';
+// Load the same production catalog in Node and in the browser, without a stale ID snapshot.
+const bundled = await build({ entryPoints: [fileURLToPath(new URL('./cases.ts', import.meta.url))], bundle: true, platform: 'node', format: 'esm', write: false });
+const { cases, presets, bindInput } = await import(`data:text/javascript;base64,${Buffer.from(bundled.outputFiles[0].text).toString('base64')}`);
+export default {
+ name: 'provider-template-catalog', entry: './fixture.tsx', viewport: { width: 1000, height: 900 },
+ real: 'Every bundled preset, real custom dialog and wizard, simulated clicks through identification and save',
+ notCovered: 'Discovery and saving are fake host interfaces. No real keys, OAuth, network, disk persistence or model generation.',
+ cases: { default: { about: 'Catalog completeness smoke' }, ...Object.fromEntries(cases.map(c => [c.id, { about: `${c.kind}: ${c.providerId} ${c.address}` }])) },
+ async ready(page) { await page.getByRole('dialog').waitFor(); },
+ async check(page, ui) {
+ assert.deepEqual(await page.evaluate(() => window.templateIds), presets.map(p => p.id));
+ const item = cases.find(c => c.id === ui.case) ?? cases[0];
+ const preset = presets.find(p => p.id === item.providerId);
+ if (item.kind === 'address') {
+ await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.namePlaceholder')).fill(`Review ${item.providerId}`);
+ await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.apiKeyPlaceholder')).fill('fake-ui-key');
+ await page.getByPlaceholder(await ui.t('settings.providers.custom.fields.baseUrlPlaceholder')).fill(item.address);
+ if (item.expectedIds.length !== 1) {
+ await page.getByText(await ui.t('settings.providers.detection.ambiguous'), { exact: true }).waitFor();
+ await page.waitForTimeout(1400);
+ assert.equal(await page.getByRole('button', { name: await ui.t('settings.providers.detection.configure'), exact: true }).count(), 0);
+ assert.equal(await page.evaluate(() => window.templateEvidence.handoff), undefined);
+ await ui.capture('ambiguous-stayed-custom');
+ return;
+ }
+ await page.getByRole('button', { name: await ui.t('settings.providers.wizard.next'), exact: true }).waitFor();
+ assert.equal(await page.evaluate(() => window.templateEvidence.handoff.preset.id), item.providerId);
+ }
+ const apiKeyChoice = page.getByRole('button', { name: await ui.t('settings.providers.wizard.useApiKey'), exact: true });
+ if (await apiKeyChoice.count()) await apiKeyChoice.click();
+ // Direct wizard cases cover each template even when its address is shared by plans.
+ const key = page.locator('input[type=password]');
+ if (await key.count()) await key.fill(preset.id.startsWith('xiaomi') && preset.id.includes('token-plan') ? 'tp-ui-fixture' : 'fake-ui-key');
+ for (const runtime of Object.values(preset.runtimes)) {
+ if (!runtime?.baseUrl.includes('{')) continue;
+ const inputs = page.locator('input');
+ for (let i = 0; i < await inputs.count(); i++) if (await inputs.nth(i).inputValue() === runtime.baseUrl) await inputs.nth(i).fill(bindInput(runtime.baseUrl));
+ }
+ await ui.capture('connection');
+ await page.getByRole('button', { name: await ui.t('settings.providers.wizard.next'), exact: true }).click();
+ const finish = page.getByRole('button', { name: await ui.t('settings.providers.wizard.finish'), exact: true });
+ await finish.waitFor();
+ // The catalog response is fixed; selecting it uses the real model picker, not state injection.
+ let selectedModelId = 'ui-catalog-probe';
+ if (item.kind === 'wizard' && preset.id === 'opencode-go') {
+ // Go retains its curated plan members; arbitrary discovered IDs are not plan models.
+ const model = preset.runtimes.pi.models.find(m => Object.values(preset.runtimes).every(rt => rt.models.some(row => row.id === m.id)));
+ assert.ok(model);
+ selectedModelId = model.id;
+ const row = page.getByText(model.name, { exact: true });
+ await row.click(); await row.click(); // Exercise selection, then restore the recommended row.
+ } else if (item.kind === 'wizard') await page.getByText('UI catalog probe', { exact: true }).click();
+ await ui.capture('models');
+ await finish.click();
+ await page.waitForFunction(() => window.templateEvidence.saved);
+ const saved = await page.evaluate(() => window.templateEvidence.saved);
+ assert.deepEqual(Object.keys(saved.runtimes).sort(), Object.keys(preset.runtimes).sort());
+ for (const [agent, runtime] of Object.entries(saved.runtimes)) {
+ assert.ok(preset.runtimes[agent], `unexpected engine ${agent}`);
+ assert.equal(runtime.catalogPresetId, preset.id);
+ assert.ok(runtime.baseUrl && !runtime.baseUrl.includes('{'));
+ for (const [header, value] of Object.entries(preset.runtimes[agent].headers ?? {})) assert.equal(runtime.headers?.[header], value);
+ if (item.kind === 'address') {
+ const handed = await page.evaluate(agent => window.templateEvidence.handoff.preset.runtimes[agent], agent);
+ assert.equal(runtime.baseUrl, handed.baseUrl);
+ if (handed.wireProtocol) assert.equal(runtime.wireProtocol, handed.wireProtocol);
+ }
+ assert.ok(runtime.models.some(m => m.id === selectedModelId), `missing selected model ${agent}`);
+ }
+ assert.ok(Object.keys(saved.runtimes).length);
+ },
+};
diff --git a/apps/desktop/scripts/provider-protocol-e2e.mjs b/apps/desktop/scripts/provider-protocol-e2e.mjs
new file mode 100644
index 0000000000..32f045a63d
--- /dev/null
+++ b/apps/desktop/scripts/provider-protocol-e2e.mjs
@@ -0,0 +1,117 @@
+// Black-box real Desktop IPC -> native adapters -> loopback HTTP fault injection.
+// No database writes, host mocks, SDK mocks, real keys or paid upstreams.
+import assert from 'node:assert/strict';
+import http from 'node:http';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { chromium } from 'playwright-core';
+const out = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-protocol-e2e-'));
+const wires = ['openai-chat', 'openai-responses', 'anthropic-messages', 'google-generative-ai'];
+const model = 'e2e-protocol-model';
+const records = [];
+let active;
+function frames(wire) {
+ const events = wire === 'openai-responses' ? [
+ { type: 'response.created', response: { id: 'reply' } },
+ { type: 'response.output_item.added', output_index: 0, item: { id: 'msg', type: 'message', role: 'assistant', content: [] } },
+ { type: 'response.output_text.delta', output_index: 0, content_index: 0, delta: 'OK' },
+ { type: 'response.completed', response: { id: 'reply', status: 'completed', output: [], usage: { input_tokens: 1, output_tokens: 1 } } },
+ ] : wire === 'anthropic-messages' ? [
+ { type: 'message_start', message: { id: 'reply', model, role: 'assistant', type: 'message', content: [], usage: { input_tokens: 1, output_tokens: 0 } } },
+ { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
+ { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'OK' } },
+ { type: 'content_block_stop', index: 0 },
+ { type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 1 } },
+ { type: 'message_stop' },
+ ] : wire === 'google-generative-ai' ? [{ candidates: [{ content: { parts: [{ text: 'OK' }] }, finishReason: 'STOP' }] }] : [{ id: 'reply', object: 'chat.completion.chunk', choices: [{ index: 0, delta: { role: 'assistant', content: 'OK' } }] },
+ { id: 'reply', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage: { prompt_tokens: 1, completion_tokens: 1 } }];
+ return events;
+}
+const encode = events => events.map(e => `${e.type ? `event: ${e.type}\n` : ''}data: ${JSON.stringify(e)}\n\n`).join('');
+const server = http.createServer(async (req, res) => {
+ const chunks = []; for await (const c of req) chunks.push(c);
+ const url = new URL(req.url, 'http://fixture');
+ const wire = url.pathname.endsWith('/chat/completions') ? wires[0] : url.pathname.endsWith('/responses') ? wires[1]
+ : url.pathname.endsWith('/messages') ? wires[2] : url.pathname.includes(':streamGenerateContent') ? wires[3] : 'unknown';
+ active.requests.push({ method: req.method, path: url.pathname, wire });
+ const json = (status, body) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(body)); };
+ if (active.kind === 'success' && wire !== active.wire || active.kind === 'unsupported') return json(active.status ?? 400, { error: { code: 'unsupported_protocol', message: 'protocol not supported' } });
+ if (active.kind === 'http') return json(active.status, { error: { message: active.message } });
+ if (active.kind === 'disconnect') return req.socket.destroy();
+ if (active.kind === 'timeout') return; // Real 8-second candidate deadline.
+ if (active.kind === 'overall') return setTimeout(() => {
+ if (!res.destroyed) json(400, { error: { code: 'unsupported_protocol', message: 'protocol not supported' } });
+ }, 6000);
+ if (active.kind === 'redirect') { res.writeHead(307, { location: '/redirect-target' }); return res.end(); }
+ if (active.kind === 'html') { res.writeHead(200, { 'content-type': 'text/html' }); return res.end('<html>Login</html>'); }
+ res.writeHead(200, { 'content-type': 'text/event-stream' });
+ if (active.kind === 'empty') return res.end('data: [DONE]\n\n');
+ if (active.kind === 'malformed') return res.end('data: {broken}\n\n');
+ if (active.kind === 'stream-error') return res.end(encode([{ error: { type: 'authentication_error', message: 'invalid api key' } }]));
+ const events = frames(wire);
+ if (active.kind === 'partial-end' || active.kind === 'partial-reset') {
+ const partial = wire === wires[3] ? [{ candidates: [{ content: { parts: [{ text: 'partial' }] } }] }] : events.slice(0, wire === wires[0] ? 1 : 3);
+ res.write(encode(partial));
+ if (active.kind === 'partial-end') return res.end();
+ return setTimeout(() => res.destroy(), 80);
+ }
+ res.end(encode(events));
+});
+await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+const baseUrl = `http://127.0.0.1:${server.address().port}/team/v1`;
+let browser;
+try {
+ browser = await chromium.connectOverCDP(process.env.E2E_CDP_URL ?? 'http://127.0.0.1:19427');
+ const page = browser.contexts()[0].pages().find(p => /localhost:\d+\/#\/settings/.test(p.url()));
+ assert.ok(page, 'An isolated Desktop settings window must be open');
+ const cases = wires.map((wire, i) => ({ kind: 'success', wire, count: i + 1 }));
+ for (const wire of wires) cases.push(...[
+ { kind: 'http', status: 401, message: 'invalid api key', code: 'AUTH_INVALID' },
+ { kind: 'http', status: 403, message: 'forbidden', code: 'AUTH_FORBIDDEN' },
+ { kind: 'http', status: 402, message: 'insufficient_quota', code: 'QUOTA_EXCEEDED' },
+ { kind: 'http', status: 429, message: 'rate limit unsupported_protocol', code: 'RATE_LIMITED' },
+ { kind: 'http', status: 400, message: 'invalid request parameter' },
+ { kind: 'http', status: 404, message: 'not found' },
+ { kind: 'http', status: 503, message: 'unsupported_protocol' },
+ { kind: 'disconnect' }, { kind: 'partial-end' }, { kind: 'partial-reset' },
+ { kind: 'empty' }, { kind: 'malformed' }, { kind: 'html' }, { kind: 'redirect' },
+ { kind: 'stream-error' }, { kind: 'timeout', code: 'TIMEOUT' },
+ ].map(c => ({ ...c, wire, count: 1, preferred: wire })));
+ for (const status of [400, 404, 405, 415, 422]) cases.push({ kind: 'unsupported', status, count: 4 });
+ cases.push({ kind: 'overall', count: 3, code: 'TIMEOUT' });
+ for (const c of cases) {
+ active = { ...c, requests: [] };
+ const input = { kind: 'adhoc', strategy: 'auto', requestId: `matrix-${Date.now()}-${records.length}`,
+ spec: { agent: 'pi', baseUrl, modelId: model, authMethod: 'apiKey', apiKey: 'fake-e2e-not-a-real-key',
+ ...(c.preferred ? { wireProtocol: c.preferred } : {}) } };
+ const start = Date.now();
+ const result = await page.evaluate(input => window.electronAPI.maker.testProviderConnection(input), input);
+ const row = { ...c, elapsedMs: Date.now() - start, result, requests: active.requests };
+ records.push(row);
+ await fs.writeFile(path.join(out, 'results.json'), JSON.stringify(records, null, 2));
+ assert.equal(result.ok, c.kind === 'success', JSON.stringify(row));
+ assert.equal(active.requests.length, c.count, JSON.stringify(row));
+ assert.equal(result.attempts.length, c.count, JSON.stringify(row));
+ if (c.kind === 'success') {
+ assert.equal(result.selected.wireProtocol, c.wire);
+ assert.deepEqual(active.requests.map(r => r.wire), wires.slice(0, c.count));
+ } else if (c.kind === 'unsupported' || c.kind === 'overall') assert.deepEqual(active.requests.map(r => r.wire), wires.slice(0, c.count));
+ else { assert.equal(active.requests[0].wire, c.wire); assert.notEqual(result.decision, 'next'); }
+ if (c.code) assert.equal(result.code, c.code, JSON.stringify(row));
+ if (c.kind === 'timeout') assert.ok(row.elapsedMs >= 7500 && row.elapsedMs < 12000, JSON.stringify(row));
+ if (c.kind === 'overall') assert.ok(row.elapsedMs >= 14500 && row.elapsedMs < 19000, JSON.stringify(row));
+ row.pass = true;
+ await fs.writeFile(path.join(out, 'results.json'), JSON.stringify(records, null, 2));
+ console.log(`PASS ${c.kind} ${c.wire ?? ''} ${c.status ?? ''} requests=${c.count}`);
+ }
+} catch (error) {
+ console.error(error);
+ await fs.writeFile(path.join(out, 'failure.txt'), String(error.stack));
+ process.exitCode = 1;
+} finally {
+ await browser?.close();
+ server.closeAllConnections();
+ await new Promise(resolve => server.close(resolve));
+ console.log(`REPORT=${out}`);
+}
diff --git a/apps/desktop/scripts/provider-save-e2e.mjs b/apps/desktop/scripts/provider-save-e2e.mjs
new file mode 100644
index 0000000000..6f5267c784
--- /dev/null
+++ b/apps/desktop/scripts/provider-save-e2e.mjs
@@ -0,0 +1,178 @@
+// Real isolated Desktop IPC + persistence + loopback HTTP. No host mocks or real keys.
+// Start with XDT_CDP_PORT=19427 pnpm restart:desktop:remote --region=global --isolated=@worktree --passive
+import assert from 'node:assert/strict';
+import http from 'node:http';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { createRequire } from 'node:module';
+import { chromium } from 'playwright-core';
+
+const require = createRequire(import.meta.url);
+const Database = require('better-sqlite3');
+const dbFile = process.env.E2E_DB;
+assert.ok(dbFile && /CindyGlobal-dev2-provider-auto-detection-[^/]+\/cindy-local-v1\.db$/.test(dbFile),
+ 'E2E_DB must name this worktree isolated local database; never use a real profile');
+const disk = new Database(dbFile, { readonly: true });
+const out = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-provider-save-e2e-'));
+const results = [];
+const requests = [];
+let scenario;
+const model = 'e2e-fixture-chat';
+const key = 'fake-e2e-not-a-real-key';
+const server = http.createServer(async (req, res) => {
+ const chunks = [];
+ for await (const chunk of req) chunks.push(chunk);
+ const body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString()) : undefined;
+ const url = new URL(req.url, 'http://fixture');
+ requests.push({ scenario: scenario?.name, method: req.method, path: url.pathname,
+ model: body?.model, authMatches: req.headers.authorization === `Bearer ${key}`,
+ apiKeyMatches: req.headers['x-api-key'] === key, marker: req.headers['x-e2e-marker'] });
+ const json = (value, status = 200) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(value)); };
+ const prefix = scenario?.prefix ?? '';
+ if (!url.pathname.startsWith(prefix + '/')) return json({ error: 'wrong prefix' }, 404);
+ const route = url.pathname.slice(prefix.length);
+ if (req.method === 'GET') {
+ if (route === '/v1/models') return json({ data: [{ id: model, owned_by: scenario.system === 'vllm' ? 'vllm' : 'fixture', root: model, max_model_len: 8192 }] });
+ const fixtures = {
+ sub2api: { '/api/v1/settings/public': { code: 0, data: { version: 'fixture', hide_ccs_import_button: false, backend_mode_enabled: true, subscription_enabled: false } }, '/v1/sub2api/billing': { object: 'sub2api.key_billing', schema_version: 1 } },
+ litellm: { '/health/readiness/details': { litellm_version: 'fixture', status: 'healthy', success_callbacks: [] }, '/v1/model/info': { data: [{ model_name: model, litellm_params: {}, model_info: {} }] } },
+ lmstudio: { '/lmstudio-greeting': { lmstudio: true }, '/api/v1/models': { models: [{ key: model, type: 'llm', publisher: 'fixture', loaded_instances: [] }] } },
+ llamacpp: { '/props': { default_generation_settings: {}, total_slots: 1, build_info: 'fixture' } },
+ vllm: { '/version': { version: 'fixture' } },
+ };
+ return fixtures[scenario.system]?.[route] ? json(fixtures[scenario.system][route]) : json({ error: 'not found' }, 404);
+ }
+ if (!['/v1/chat/completions', '/v1/responses', '/v1/messages'].includes(route)) return json({ error: 'unsupported endpoint' }, 404);
+ if (body?.model !== model) return json({ error: 'wrong model' }, 400);
+ if (scenario.reject) return json({ error: { message: 'invalid fixture key', type: 'authentication_error' } }, 401);
+ res.writeHead(200, { 'content-type': 'text/event-stream' });
+ const events = route.endsWith('/responses') ? [
+ { type: 'response.created', response: { id: 'reply' } },
+ { type: 'response.output_item.added', output_index: 0, item: { id: 'msg', type: 'message', role: 'assistant', content: [] } },
+ { type: 'response.output_text.delta', output_index: 0, content_index: 0, delta: 'OK' },
+ { type: 'response.completed', response: { id: 'reply', status: 'completed', output: [], usage: { input_tokens: 1, output_tokens: 1 } } },
+ ] : route.endsWith('/messages') ? [
+ { type: 'message_start', message: { id: 'reply', model, role: 'assistant', type: 'message', content: [], usage: { input_tokens: 1, output_tokens: 0 } } },
+ { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
+ { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'OK' } },
+ { type: 'content_block_stop', index: 0 },
+ { type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 1 } },
+ { type: 'message_stop' },
+ ] : [{ id: 'reply', object: 'chat.completion.chunk', choices: [{ index: 0, delta: { role: 'assistant', content: 'OK' } }] },
+ { id: 'reply', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage: { prompt_tokens: 1, completion_tokens: 1 } }];
+ res.end(events.map(e => `${e.type ? `event: ${e.type}\n` : ''}data: ${JSON.stringify(e)}\n\n`).join('') + (route.endsWith('/completions') ? 'data: [DONE]\n\n' : ''));
+});
+await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+const origin = `http://127.0.0.1:${server.address().port}`;
+let browser;
+let page;
+const created = [];
+try {
+ browser = await chromium.connectOverCDP(process.env.E2E_CDP_URL ?? 'http://127.0.0.1:19427');
+ page = browser.contexts()[0].pages().find(p => /\/#\/settings/.test(p.url()));
+ assert.ok(page, 'Open the isolated Desktop Settings / Providers page first');
+ page.setDefaultTimeout(20000);
+ const presets = await page.evaluate(async () => (await window.electronAPI.maker.listProviderPresets()).presets);
+ if (await page.getByRole('dialog').count()) {
+ await page.getByRole('dialog').getByRole('button', { name: '取消', exact: true }).click();
+ await page.getByRole('dialog').waitFor({ state: 'hidden' });
+ }
+ for (const item of [
+ { system: 'sub2api', prefix: '' }, { system: 'sub2api', prefix: '/team', back: true },
+ { system: 'litellm', prefix: '/team' }, { system: 'lmstudio', prefix: '/team' },
+ { system: 'llamacpp', prefix: '/team' }, { system: 'vllm', prefix: '/team' },
+ ]) {
+ scenario = { ...item, name: `E2E ${item.system} ${item.back ? 'return' : 'save'} ${Date.now()}` };
+ if (!await page.getByPlaceholder('我的 AI 供应商').count()) {
+ await page.getByRole('button', { name: '添加供应商', exact: true }).click();
+ await page.getByText('自定义端点', { exact: true }).click();
+ }
+ await page.getByPlaceholder('我的 AI 供应商').fill(scenario.name);
+ await page.getByPlaceholder('API 密钥', { exact: true }).fill(key);
+ await page.getByRole('button', { name: '添加请求头', exact: true }).click();
+ await page.getByPlaceholder('Header-Name').first().fill('X-E2E-Marker');
+ await page.getByPlaceholder('value', { exact: true }).first().fill('preserved-through-wizard');
+ await page.getByPlaceholder('https://api.myprovider.com/v1').fill(origin + item.prefix + '/v1');
+ const next = page.getByRole('button', { name: '下一步', exact: true });
+ await next.waitFor();
+ await page.screenshot({ path: path.join(out, `${results.length}-handoff.png`) });
+ await next.click();
+ const finish = page.getByRole('button', { name: '完成添加', exact: true });
+ await finish.waitFor();
+ if (item.back) {
+ await page.getByRole('button', { name: '← 上一步', exact: true }).click();
+ await page.getByRole('button', { name: '← 上一步', exact: true }).click();
+ await page.getByRole('button', { name: '保存供应商', exact: true }).click();
+ } else await finish.click();
+ await page.waitForFunction(async name => (await window.electronAPI.maker.listProviders()).providers.some(p => p.name === name), scenario.name);
+ const saved = await page.evaluate(async name => (await window.electronAPI.maker.listProviders()).providers.find(p => p.name === name), scenario.name);
+ created.push(saved.id);
+ const row = disk.prepare('SELECT * FROM custom_providers WHERE id = ?').get(saved.id.replace(/^custom:/, ''));
+ assert.ok(row, 'Real save must create a SQLite row');
+ const stored = JSON.parse(row.runtimes);
+ const preset = presets.find(p => p.id === item.system);
+ assert.ok(preset);
+ const expectedAgents = item.back ? ['pi'] : Object.keys(preset.runtimes);
+ assert.deepEqual(Object.keys(saved.routing).sort(), expectedAgents.sort());
+ assert.deepEqual(Object.keys(stored).sort(), expectedAgents.sort());
+ assert.equal(stored.pi.baseUrl, origin + item.prefix + '/v1');
+ assert.ok(stored.pi.models.some(m => m.id === model && m.defaultEnabled !== false));
+ assert.equal(saved.source, 'user');
+ assert.ok(saved.models.pi.some(m => m.id === model));
+ assert.equal(new URL(saved.routing.pi.upstream).port, String(server.address().port));
+ assert.equal(saved.routing.pi.upstream, origin + item.prefix + '/v1');
+ const start = requests.length;
+ const probes = {};
+ for (const agent of Object.keys(saved.routing)) {
+ const probe = await page.evaluate(input => window.electronAPI.maker.testProviderConnection(input), { kind: 'saved', providerId: saved.id, agent });
+ probes[agent] = probe;
+ assert.equal(probe.ok, true, JSON.stringify({ system: item.system, agent, probe }));
+ }
+ const posts = requests.slice(start).filter(r => r.method === 'POST');
+ assert.equal(posts.length, Object.keys(saved.routing).length);
+ assert.ok(posts.every(r => r.model === model && (r.authMatches || r.apiKeyMatches)));
+ assert.ok(posts.every(r => r.marker === 'preserved-through-wizard'));
+ assert.ok(posts.every(r => r.path.startsWith(item.prefix + '/v1/')));
+ const expectedPaths = expectedAgents.map(agent => {
+ // The existing provider interface audit overrides LM Studio's Codex
+ // catalog default to Responses (providerInterfaceRoutes.ts).
+ const wire = item.back ? 'openai-chat' : item.system === 'lmstudio' && agent === 'codex' ? 'openai-responses'
+ : preset.runtimes[agent].wireProtocol ?? (agent === 'claude-code' ? 'anthropic-messages' : agent === 'codex' ? 'openai-responses' : 'openai-chat');
+ assert.equal(stored[agent].wireProtocol ?? (agent === 'claude-code' ? 'anthropic-messages' : agent === 'codex' ? 'openai-responses' : 'openai-chat'), wire);
+ return item.prefix + '/v1/' + ({ 'openai-chat': 'chat/completions', 'openai-responses': 'responses', 'anthropic-messages': 'messages' })[wire];
+ }).sort();
+ assert.deepEqual(posts.map(r => r.path).sort(), expectedPaths);
+ await page.reload();
+ await page.getByRole('button', { name: '添加供应商', exact: true }).waitFor();
+ const reread = await page.evaluate(async id => (await window.electronAPI.maker.listProviders()).providers.find(p => p.id === id), saved.id);
+ assert.deepEqual(reread.routing, saved.routing);
+ const again = await page.evaluate(id => window.electronAPI.maker.testProviderConnection({ kind: 'saved', providerId: id, agent: 'pi' }), saved.id);
+ assert.equal(again.ok, true);
+ scenario.reject = true;
+ const beforeReject = requests.length;
+ const rejected = await page.evaluate(id => window.electronAPI.maker.testProviderConnection({ kind: 'saved', providerId: id, agent: 'pi' }), saved.id);
+ assert.equal(rejected.ok, false);
+ assert.equal(rejected.status, 401);
+ assert.equal(requests.slice(beforeReject).filter(r => r.method === 'POST').length, 1, '401 must not retry another protocol');
+ assert.deepEqual(disk.prepare('SELECT * FROM custom_providers WHERE id = ?').get(row.id), row, 'Probe must not mutate saved config');
+ results.push({ system: item.system, prefix: item.prefix, returned: !!item.back, saved, stored, probes, posts, reread: true, diskVerified: true, reloadedProbe: again, rejected });
+ console.log(`PASS ${item.system} ${item.back ? 'return' : 'save'}`);
+ }
+} catch (error) {
+ console.error(error);
+ if (page) { await page.screenshot({ path: path.join(out, 'failure.png') }).catch(() => {}); console.error((await page.getByRole('dialog').innerText().catch(() => '')).slice(0,2200)); }
+ results.push({ error: error.message });
+ process.exitCode = 1;
+} finally {
+ if (page) for (const id of created) await page.evaluate(async providerId => {
+ const { dataOwnerId, ownerGeneration } = await window.electronAPI.maker.listProviders();
+ await window.electronAPI.maker.deleteCustomProvider(providerId.replace(/^custom:/, ''), { dataOwnerId, ownerGeneration });
+ }, id).catch(e => { console.error('Cleanup failed', e.message); process.exitCode = 1; });
+ for (const id of created) assert.equal(disk.prepare('SELECT id FROM custom_providers WHERE id = ?').get(id.replace(/^custom:/, '')), undefined, 'Fixture cleanup must remove disk row');
+ disk.close();
+ await fs.writeFile(path.join(out, 'results.json'), JSON.stringify({ results, requests }, null, 2));
+ console.log(`REPORT=${out}`);
+ await browser?.close();
+ await new Promise(resolve => server.close(resolve));
+}
diff --git a/apps/desktop/scripts/provider-ui-lifecycle-e2e.mjs b/apps/desktop/scripts/provider-ui-lifecycle-e2e.mjs
new file mode 100644
index 0000000000..74800c4e71
--- /dev/null
+++ b/apps/desktop/scripts/provider-ui-lifecycle-e2e.mjs
@@ -0,0 +1,127 @@
+// Real Desktop UI, IPC, SQLite and loopback server; fake keys only.
+import assert from 'node:assert/strict';
+import http from 'node:http';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import {createRequire} from 'node:module';
+import {chromium} from 'playwright-core';
+const require=createRequire(import.meta.url);
+assert.ok(/CindyGlobal-dev2-provider-auto-detection-[^/]+\/cindy-local-v1\.db$/.test(process.env.E2E_DB??''));
+const db=new (require('better-sqlite3'))(process.env.E2E_DB,{readonly:true});
+const out=await fs.mkdtemp(path.join(os.tmpdir(),'cindy-provider-ui-lifecycle-'));
+const wires=['openai-chat','openai-responses','anthropic-messages','google-generative-ai'];
+const model='e2e-lifecycle-model';
+const records=[],created=[],requests=[],held=[];
+let desired=wires[0],hold=false,reject=false;
+function frames(wire) {
+ const events = wire === 'openai-responses' ? [
+ { type: 'response.created', response: { id: 'reply' } },
+ { type: 'response.output_item.added', output_index: 0, item: { id: 'msg', type: 'message', role: 'assistant', content: [] } },
+ { type: 'response.output_text.delta', output_index: 0, content_index: 0, delta: 'OK' },
+ { type: 'response.completed', response: { id: 'reply', status: 'completed', output: [], usage: { input_tokens: 1, output_tokens: 1 } } },
+ ] : wire === 'anthropic-messages' ? [
+ { type: 'message_start', message: { id: 'reply', model, role: 'assistant', type: 'message', content: [], usage: { input_tokens: 1, output_tokens: 0 } } },
+ { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
+ { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'OK' } },
+ { type: 'content_block_stop', index: 0 },
+ { type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 1 } },
+ { type: 'message_stop' },
+ ] : wire === 'google-generative-ai' ? [{ candidates: [{ content: { parts: [{ text: 'OK' }] }, finishReason: 'STOP' }] }] : [{ id: 'reply', object: 'chat.completion.chunk', choices: [{ index: 0, delta: { role: 'assistant', content: 'OK' } }] },
+ { id: 'reply', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage: { prompt_tokens: 1, completion_tokens: 1 } }];
+ return events;
+}
+const encode = events => events.map(e => `${e.type ? `event: ${e.type}\n` : ''}data: ${JSON.stringify(e)}\n\n`).join('');
+
+const server=http.createServer(async(req,res)=>{
+ const parts=[];for await(const p of req)parts.push(p);
+ const url=new URL(req.url,'http://fixture');
+ const json=(body,status=200)=>{res.writeHead(status,{'content-type':'application/json'});res.end(JSON.stringify(body))};
+ if(req.method==='GET')return url.pathname.endsWith('/models')?json({data:[{id:model}]}):json({error:'not found'},404);
+ const wire=url.pathname.endsWith('/chat/completions')?wires[0]:url.pathname.endsWith('/responses')?wires[1]:url.pathname.endsWith('/messages')?wires[2]:wires[3];
+ const requestModel=JSON.parse(Buffer.concat(parts).toString()||'{}').model??decodeURIComponent(url.pathname.split('/models/')[1]?.split(':')[0]??'');
+ if(requestModel!==model)return json({error:'unexpected model'},400);
+ const row={path:url.pathname,wire,model:requestModel,engine:req.headers['x-e2e-engine'],closed:false,key:req.headers.authorization??req.headers['x-api-key']??req.headers['x-goog-api-key']};
+ requests.push(row);res.on('close',()=>{row.closed=true});
+ const respond=()=>{if(res.destroyed)return;if(reject||wire!==desired)return json({error:{code:'unsupported_protocol',message:'protocol not supported'}},400);res.writeHead(200,{'content-type':'text/event-stream'});res.end(encode(frames(wire)))};
+ if(hold)held.push(respond);else respond();
+});
+await new Promise(r=>server.listen(0,'127.0.0.1',r));
+const origin=`http://127.0.0.1:${server.address().port}`;
+let browser,page;
+const row=id=>db.prepare('SELECT * FROM custom_providers WHERE id=?').get(id.replace(/^custom:/,''));
+const persist=async()=>fs.writeFile(path.join(out,'results.json'),JSON.stringify({records,created,requests},null,2));
+async function record(name,details={}){records.push({name,pass:true,...details});await persist();if(await page.getByRole('dialog').count())await page.getByRole('dialog').screenshot({path:path.join(out,name+'.png')});console.log('PASS',name)}
+async function closeDialog(){if(await page.getByRole('dialog').count()){await page.getByRole('dialog').getByRole('button',{name:'取消',exact:true}).click();await page.getByRole('dialog').waitFor({state:'hidden'})}}
+async function open(name,base=origin+'/team/v1'){
+ await closeDialog();await page.getByRole('button',{name:'添加供应商',exact:true}).click();await page.getByText('自定义端点',{exact:true}).click();
+ await page.getByPlaceholder('我的 AI 供应商').fill(name);await page.getByPlaceholder('API 密钥',{exact:true}).fill('fake-lifecycle-key');await page.getByPlaceholder('https://api.myprovider.com/v1').fill(base);
+ await page.getByText(model+' 自动识别',{exact:true}).waitFor();
+}
+async function success(){await page.getByText(/^连接成功(/).waitFor()}
+async function test(){await page.getByRole('dialog').getByRole('button',{name:'测试连接',exact:true}).click()}
+async function save(name){await page.getByRole('button',{name:'保存供应商',exact:true}).click();await page.getByRole('dialog').waitFor({state:'hidden'});
+ const provider=await page.evaluate(async name=>(await window.electronAPI.maker.listProviders()).providers.find(p=>p.name===name),name);assert.ok(provider);created.push(provider.id);await persist();return provider}
+async function edit(name){await page.getByRole('button').filter({hasText:name}).first().click();await page.getByRole('button',{name:'更多操作',exact:true}).click();await page.getByRole('menuitem',{name:'编辑连接设置',exact:true}).click();await page.getByPlaceholder('我的 AI 供应商').waitFor()}
+try{
+ browser=await chromium.connectOverCDP('http://127.0.0.1:19427');page=browser.contexts()[0].pages().find(p=>p.url().includes('/#/settings'));assert.ok(page);page.setDefaultTimeout(15000);
+ for(const action of ['legacy','id'].includes(process.env.E2E_ONLY)?[]:['stop','close','address','key']){
+ await open('E2E lifecycle '+action);desired=wires[0];hold=true;const start=requests.length;await test();
+ while(requests.length===start)await page.waitForTimeout(20);
+ if(action==='stop')await page.getByRole('button',{name:'停止测试',exact:true}).click();
+ if(action==='close')await closeDialog();
+ if(action==='address')await page.getByPlaceholder('https://api.myprovider.com/v1').fill(origin+'/new/v1');
+ if(action==='key')await page.getByPlaceholder('API 密钥',{exact:true}).fill('fake-new-key');
+ await page.waitForTimeout(250);assert.equal(requests[start].closed,true,'old request must be aborted');
+ hold=false;
+ if(action==='close')await open('E2E lifecycle reopen');
+ await test();await success();const before=await page.getByPlaceholder('https://api.myprovider.com/v1').inputValue();
+ for(const release of held.splice(0))release();await page.waitForTimeout(300);
+ assert.equal(await page.getByPlaceholder('https://api.myprovider.com/v1').inputValue(),before);await success();
+ assert.equal(requests.length-start,2);if(action==='key')assert.equal(requests.at(-1).key,'Bearer fake-new-key');if(action==='address')assert.equal(requests.at(-1).path,'/new/v1/chat/completions');await record('cancel-'+action,{requests:requests.slice(start)});
+ }
+ for(const wire of ['legacy','id'].includes(process.env.E2E_ONLY)?[]:wires){
+ desired=wire;const name='E2E auto '+wires.indexOf(wire)+' '+Date.now();await open(name);const start=requests.length;await test();await success();
+ assert.deepEqual(requests.slice(start).map(r=>r.wire),wires.slice(0,wires.indexOf(wire)+1));
+ const base=await page.getByPlaceholder('https://api.myprovider.com/v1').inputValue();const again=requests.length;await test();await success();assert.equal(requests.length-again,1);assert.equal(requests.at(-1).wire,wire);
+ const p=await save(name);const stored=JSON.parse(row(p.id).runtimes);assert.equal(stored.pi.wireProtocol,wire);assert.equal(stored.pi.baseUrl,base);assert.equal(stored.pi.models[0].route.wireProtocol,wire);
+ await page.reload();await page.getByRole('button',{name:'添加供应商',exact:true}).waitFor();await edit(name);assert.equal(await page.getByPlaceholder('https://api.myprovider.com/v1').inputValue(),base);
+ const last=requests.length;await test();await success();assert.equal(requests.length-last,1);assert.equal(requests.at(-1).wire,wire);await closeDialog();
+ const result=await page.evaluate(id=>window.electronAPI.maker.testProviderConnection({kind:'saved',providerId:id,agent:'pi'}),p.id);assert.equal(result.ok,true,JSON.stringify(result));assert.equal(requests.at(-1).wire,wire);
+ await record('auto-save-reopen-call-'+wire,{base,stored});
+ }
+ if(!['legacy','id'].includes(process.env.E2E_ONLY)){desired=wires[0];const manual='E2E manual '+Date.now();await open(manual);const count=requests.length;const manualProvider=await save(manual);assert.equal(requests.length,count);assert.equal(JSON.parse(row(manualProvider.id).runtimes).pi.wireProtocol,wires[0]);await record('manual-save-without-probe');}
+ if(!process.env.E2E_ONLY||process.env.E2E_ONLY==='id'){
+ desired=wires[0];
+ const prefix=('E2E long '+Date.now()+' ').padEnd(40,'a');
+ for(const ending of ['', ' first', ' second']){
+ const name=prefix+ending;await open(name);const p=await save(name);
+ assert.ok(p.id.length<=40);assert.equal(row(p.id).name,name);
+ await page.reload();await page.getByRole('button',{name:'添加供应商',exact:true}).waitFor();await edit(name);
+ assert.equal(await page.getByPlaceholder('我的 AI 供应商').inputValue(),name);
+ await page.getByRole('button',{name:'保存',exact:true}).click();await page.getByRole('dialog').waitFor({state:'hidden'});
+ assert.equal(row(p.id).name,name,'editing preserves the ID and display name');
+ const result=await page.evaluate(id=>window.electronAPI.maker.testProviderConnection({kind:'saved',providerId:id,agent:'pi'}),p.id);assert.equal(result.ok,true);
+ await record('long-id-save-'+(ending.trim()||'boundary'),{id:p.id,name});
+ }
+ assert.equal(new Set(created).size,created.length);
+ }
+ if(process.env.E2E_ONLY!=='id'){
+ // Existing multi-engine connection is seeded through the real create IPC.
+ const id='e2e-independent-'+Date.now(),name='E2E independent '+Date.now();
+ const config={id,name,auth:{method:'apiKey'},runtimes:Object.fromEntries(['claude-code','codex','pi'].map(agent=>[agent,{baseUrl:origin+'/'+agent+'/v1',wireProtocol:'openai-chat',headers:{'X-E2E-Engine':agent},models:[{id:model,name:model}]}]))};
+ await page.evaluate(({config})=>window.electronAPI.maker.createCustomProvider(config,{'claude-code':'fake-claude','codex':'fake-codex','pi':'fake-pi'}),{config});created.push(id);await persist();
+ await page.reload();await page.getByRole('button',{name:'添加供应商',exact:true}).waitFor();await edit(name);
+ await page.getByRole('tab',{name:'Pi',exact:true}).click();
+ const before=JSON.parse(row(id).runtimes);reject=true;const prior=requests.length;await test();await page.getByRole('button',{name:'测试连接',exact:true}).waitFor();await page.waitForTimeout(300);assert.equal(requests.length-prior,1,'legacy edit probe must not enumerate protocols');reject=false;
+ await page.getByPlaceholder('https://api.myprovider.com/v1').fill(origin+'/changed-pi/v1');await page.getByPlaceholder('API 密钥',{exact:true}).fill('fake-pi-edited');
+ await page.getByRole('button',{name:'保存',exact:true}).click();await page.getByRole('dialog').waitFor({state:'hidden'});
+ const after=JSON.parse(row(id).runtimes);assert.deepEqual(after['claude-code'],before['claude-code']);assert.deepEqual(after.codex,before.codex);assert.equal(after.pi.baseUrl,origin+'/changed-pi/v1');
+ for(const agent of ['claude-code','codex','pi']){const result=await page.evaluate(({id,agent})=>window.electronAPI.maker.testProviderConnection({kind:'saved',providerId:id,agent}),{id,agent});assert.equal(result.ok,true);assert.equal(requests.at(-1).engine,agent==='pi'?undefined:agent);assert.equal(requests.at(-1).path,'/'+(agent==='pi'?'changed-pi':agent)+'/v1/chat/completions');assert.equal(requests.at(-1).key,'Bearer '+(agent==='pi'?'fake-pi-edited':agent==='codex'?'fake-codex':'fake-claude'))}
+ await record('edit-old-connection-preserves-independent-engines',{before,after});
+ }
+}catch(e){console.error(e);records.push({error:e.message});process.exitCode=1;if(page)console.error(await page.getByRole('dialog').innerText().catch(()=>''))}
+finally{
+ if(page){await closeDialog().catch(()=>{});for(const id of created){await page.evaluate(async id=>{const {dataOwnerId,ownerGeneration}=await window.electronAPI.maker.listProviders();await window.electronAPI.maker.deleteCustomProvider(id.replace(/^custom:/,''),{dataOwnerId,ownerGeneration})},id).catch(e=>{records.push({cleanupError:e.message});process.exitCode=1})}}
+ await persist();db.close();await browser?.close();server.closeAllConnections();await new Promise(r=>server.close(r));console.log('REPORT='+out);
+}
diff --git a/apps/desktop/src/main/maker-host/__tests__/piProviderTransport.test.ts b/apps/desktop/src/main/maker-host/__tests__/piProviderTransport.test.ts
index 3ad1dd234a..af6f493b68 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piProviderTransport.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piProviderTransport.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import * as openaiCompletions from '@earendil-works/pi-ai/api/openai-completions';
import { PROVIDER_MODEL_CATALOG, BUNDLED_CATALOG, buildUserProvider, parseModelsListResponse, mergeDiscoveredRuntimeModels } from '@cindy/model-providers';
-import { createPiProviderFetch, hostCredentialEndpointAllowed, invocationModelRecord, nativeBridgeApiKey, NATIVE_ADAPTER_ERROR_BODY_LIMIT, NATIVE_BRIDGE_SESSION_HEADER, readBoundedResponseText } from '../pi-provider-transport.js';
+import { probePiProvider, createPiProviderFetch, hostCredentialEndpointAllowed, invocationModelRecord, nativeBridgeApiKey, NATIVE_ADAPTER_ERROR_BODY_LIMIT, NATIVE_BRIDGE_SESSION_HEADER, readBoundedResponseText } from '../pi-provider-transport.js';
vi.mock('@earendil-works/pi-ai/api/openai-completions', async (importOriginal) => ({
...await importOriginal<typeof import('@earendil-works/pi-ai/api/openai-completions')>(),
@@ -560,3 +560,22 @@ describe('OpenCode Go session header on the native transport (#5325)', () => {
expect(seen[2]!.get('x-opencode-session')).not.toBe(seen[1]!.get('x-opencode-session'));
});
});
+
+// The new protocol probe may opt into a larger reasoning budget; old callers must not change.
+it.each([undefined, 256])('keeps legacy probe options isolated from automatic probes: %s', async budget => {
+ const upstream = 'https://fixture.example/v1';
+ const provider = buildUserProvider({ id: 'probe-scope', name: 'Probe scope', runtimes: {
+ pi: { baseUrl: upstream, wireProtocol: 'openai-chat', models: [{ id: 'scope-model', name: 'Scope', reasoning: true, reasoningEfforts: ['low', 'high'] }] },
+ } });
+ const row = invocationModelRecord(provider.models.pi![0], upstream, 'openai-completions')!;
+ const stream = vi.spyOn(openaiCompletions, 'streamSimple');
+ try {
+ await probePiProvider({ row, providerId: provider.id, upstream, apiKey: 'fixture-key',
+ fetchImpl: async () => new Response(reply, { headers: { 'content-type': 'text/event-stream' } }),
+ }, new AbortController().signal, budget);
+ const options = stream.mock.calls.at(-1)![2];
+ expect(options?.maxTokens).toBe(budget ?? 16);
+ if (budget === undefined) expect(options).not.toHaveProperty('reasoning');
+ else expect(options).toHaveProperty('reasoning');
+ } finally { stream.mockRestore(); }
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.ts
index f5d13851fc..4dde377e5f 100644
--- a/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.ts
@@ -27,6 +27,7 @@ import {
setDiagnosticsOAuthTokenReader,
testProviderConnection,
} from '../provider-diagnostics.js';
+import { probeProviderProtocols } from '../provider-protocol-probe.js';
import { setCustomProviders } from '../active-catalog.js';
afterEach(() => {
@@ -1019,3 +1020,232 @@ it('does not replace an explicit Chat probe with the preset’s Google SDK', asy
catalogPresetId: 'google-vertex', wireProtocol: 'openai-chat', apiKey: 'fixture-key' }, fetcher)).toMatchObject({ ok: true });
expect(fetcher).toHaveBeenCalledOnce();
});
+
+/** Auto-probe unit tier: real Pi serializers/parsers with injected network responses.
+ * Protects one-click fallback and non-replay after ambiguous execution; legacy single-probe
+ * tests above do not cover sequencing or truncated native streams. Minimal regression:
+ * a valid content delta without finish must never trigger a second paid request.
+ */
+describe('automatic Pi protocol connection test', () => {
+ const spec = { agent: 'pi' as const, baseUrl: 'https://relay.example/v1', modelId: 'test-model',
+ authMethod: 'apiKey' as const, apiKey: 'fake-test-key' };
+ const sse = (events: unknown[]) => new Response(events.map(value => 'data: ' + JSON.stringify(value) + '\n\n').join(''), {
+ headers: { 'content-type': 'text/event-stream' },
+ });
+ const chat = () => sse([
+ { id: 'chat-test', object: 'chat.completion.chunk', choices: [{ index: 0, delta: { role: 'assistant', content: 'OK' }, finish_reason: null }] },
+ { id: 'chat-test', object: 'chat.completion.chunk', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] },
+ ]);
+ const unsupported = () => new Response(JSON.stringify({ error: { code: 'unsupported_protocol', message: 'protocol not supported' } }), { status: 400, headers: { 'content-type': 'application/json' } });
+
+ it('uses native streaming and stops on the first successful generation', async () => {
+ const fetcher = vi.fn<typeof fetch>(async () => chat());
+ const result = await probeProviderProtocols(spec, true, fetcher);
+ expect(result).toMatchObject({ ok: true, decision: 'success', selected: { baseUrl: spec.baseUrl, wireProtocol: 'openai-chat' } });
+ expect(fetcher).toHaveBeenCalledOnce();
+ expect(String(fetcher.mock.calls[0]?.[0])).toContain('/v1/chat/completions');
+ expect(fetcher.mock.calls[0]?.[1]).toMatchObject({ redirect: 'error' });
+ });
+
+ it('keeps preset and legacy single-probe callers on their existing route', async () => {
+ const fetcher = vi.fn<typeof fetch>(async () => new Response('data: [DONE]\n\n', { headers: { 'content-type': 'text/event-stream' } }));
+ for (const request of [
+ { kind: 'adhoc' as const, spec: { ...spec, wireProtocol: 'openai-chat' as const } },
+ { kind: 'adhoc' as const, requestId: 'preset-probe', spec: { ...spec, wireProtocol: 'openai-chat' as const, catalogPresetId: 'deepseek' } },
+ ]) {
+ const result = await testProviderConnection(request, fetcher);
+ expect(result.ok).toBe(true);
+ expect(result.attempts).toBeUndefined();
+ }
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ });
+
+ it.each(['openai-responses', 'anthropic-messages'] as const)('uses the real %s adapter and terminates fallback on success', async wire => {
+ const events = wire === 'openai-responses' ? [
+ { type: 'response.created', response: { id: 'reply' } },
+ { type: 'response.output_item.added', output_index: 0, item: { id: 'msg', type: 'message', role: 'assistant', content: [] } },
+ { type: 'response.output_text.delta', output_index: 0, content_index: 0, delta: 'OK' },
+ { type: 'response.completed', response: { id: 'reply', status: 'completed', output: [], usage: { input_tokens: 1, output_tokens: 1 } } },
+ ] : [
+ { type: 'message_start', message: { id: 'reply', model: 'test-model', role: 'assistant', type: 'message', content: [], usage: { input_tokens: 1, output_tokens: 0 } } },
+ { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
+ { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'OK' } },
+ { type: 'content_block_stop', index: 0 },
+ { type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 1 } },
+ { type: 'message_stop' },
+ ];
+ // Anthropic's native decoder requires event names in addition to data fields.
+ const response = () => wire === 'anthropic-messages'
+ ? new Response(events.map(value => 'event: ' + value.type + '\ndata: ' + JSON.stringify(value) + '\n\n').join(''), { headers: { 'content-type': 'text/event-stream' } }) : sse(events);
+ const fetcher = vi.fn<typeof fetch>(async url => new URL(String(url)).pathname.endsWith(wire === 'openai-responses' ? '/responses' : '/v1/messages') ? response() : unsupported());
+ const result = await probeProviderProtocols(spec, true, fetcher);
+ expect(result).toMatchObject({ ok: true, selected: { wireProtocol: wire } });
+ expect(fetcher).toHaveBeenCalledTimes(wire === 'openai-responses' ? 2 : 3);
+ });
+
+ it('exhausts at most four explicit rejections and returns one aggregate', async () => {
+ const fetcher = vi.fn<typeof fetch>(async () => unsupported());
+ const result = await probeProviderProtocols(spec, true, fetcher);
+ expect(result).toMatchObject({ ok: false, decision: 'next' });
+ expect(result.attempts).toHaveLength(4);
+ expect(fetcher).toHaveBeenCalledTimes(4);
+ expect(new Set(result.attempts?.map(item => item.wireProtocol)).size).toBe(4);
+ });
+
+ it('can select Google after three explicit rejections without following redirects', async () => {
+ const fetcher = vi.fn<typeof fetch>(async (url: Parameters<typeof fetch>[0]) => String(url).includes(':streamGenerateContent')
+ ? sse([{ candidates: [{ content: { parts: [{ text: 'OK' }] }, finishReason: 'STOP' }] }]) : unsupported());
+ const result = await probeProviderProtocols(spec, true, fetcher);
+ expect(result).toMatchObject({ ok: true, selected: { wireProtocol: 'google-generative-ai', baseUrl: spec.baseUrl } });
+ expect(fetcher).toHaveBeenCalledTimes(4);
+ });
+
+ it.each([
+ [401, { error: { message: 'invalid api key' } }, 'AUTH_INVALID'],
+ [402, { error: { message: 'insufficient_quota' } }, 'QUOTA_EXCEEDED'],
+ [429, { error: { message: 'rate limit' } }, 'RATE_LIMITED'],
+ [404, { error: { code: 'model_not_found', message: 'model not found' } }, 'MODEL_NOT_FOUND'],
+ ])('stops on actionable upstream error %i', async (status, body, code) => {
+ const fetcher = vi.fn<typeof fetch>(async () => new Response(JSON.stringify(body), { status }));
+ expect(await probeProviderProtocols(spec, true, fetcher)).toMatchObject({ ok: false, decision: 'blocked', code });
+ expect(fetcher).toHaveBeenCalledOnce();
+ });
+
+ it.each([
+ () => new Response('not found', { status: 404 }),
+ () => new Response('unexpected stream_options parameter', { status: 400 }),
+ () => new Response('<html>login</html>', { headers: { 'content-type': 'text/html' } }),
+ () => sse([]),
+ () => sse([{ choices: [{ index: 0, delta: { content: 'OK' }, finish_reason: null }] }]),
+ () => sse([{ choices: [{ index: 0, delta: { content: 'OK' } }] }, { error: { type: 'server_error', message: 'disconnected' } }]),
+ () => new Response('unavailable', { status: 503 }),
+ ])('does not replay an ambiguous or partially accepted request', async response => {
+ const fetcher = vi.fn<typeof fetch>(async () => response());
+ expect(await probeProviderProtocols(spec, true, fetcher)).toMatchObject({ ok: false, decision: 'inconclusive' });
+ expect(fetcher).toHaveBeenCalledOnce();
+ });
+
+ it('does not attempt candidates after cancellation', async () => {
+ const controller = new AbortController();
+ const fetcher = vi.fn<typeof fetch>(async () => { controller.abort(); return unsupported(); });
+ expect(await probeProviderProtocols(spec, true, fetcher, controller.signal)).toMatchObject({ ok: false, decision: 'cancelled' });
+ expect(fetcher).toHaveBeenCalledOnce();
+ });
+
+ it('does not replay a timed-out request', async () => {
+ const fetcher = vi.fn<typeof fetch>(async () => { throw new DOMException('timed out', 'TimeoutError'); });
+ expect(await probeProviderProtocols(spec, true, fetcher)).toMatchObject({ ok: false, decision: 'inconclusive', code: 'TIMEOUT' });
+ expect(fetcher).toHaveBeenCalledOnce();
+ });
+
+ it('no-auth local probes cannot transmit leftover credentials or the SDK placeholder', async () => {
+ const fetcher = vi.fn<typeof fetch>(async () => chat());
+ await probeProviderProtocols({ ...spec, authMethod: 'none', baseUrl: 'http://127.0.0.1:4000/v1',
+ headers: { Authorization: 'Bearer private-leftover', 'X-API-Key': 'leftover' } }, true, fetcher);
+ const headers = new Headers(fetcher.mock.calls[0]?.[1]?.headers);
+ expect(headers.has('authorization')).toBe(false);
+ expect(headers.has('x-api-key')).toBe(false);
+ });
+
+ // Protect the real abort path: native SDKs may resolve an error message instead of rejecting.
+ it('classifies the candidate deadline even when the native SDK consumes the abort', async () => {
+ const deadline = new AbortController();
+ const timeout = vi.spyOn(AbortSignal, 'timeout').mockImplementation(ms => ms === 8_000
+ ? deadline.signal : new AbortController().signal);
+ const fetcher = vi.fn<typeof fetch>(async (_input, init) => {
+ deadline.abort(new DOMException('deadline reached', 'TimeoutError'));
+ throw init!.signal!.reason;
+ });
+ try {
+ expect(await probeProviderProtocols(spec, true, fetcher)).toMatchObject({
+ ok: false, decision: 'inconclusive', code: 'TIMEOUT',
+ });
+ expect(fetcher).toHaveBeenCalledOnce();
+ } finally { timeout.mockRestore(); }
+ });
+
+ it('caps cumulative auto-detection at 15 seconds across candidates', async () => {
+ vi.useFakeTimers();
+ const timeout = vi.spyOn(AbortSignal, 'timeout').mockImplementation(ms => {
+ const controller = new AbortController();
+ setTimeout(() => controller.abort(new DOMException('deadline', 'TimeoutError')), ms);
+ return controller.signal;
+ });
+ const fetcher = vi.fn<typeof fetch>((_input, init) => new Promise((resolve, reject) => {
+ const timer = setTimeout(() => resolve(unsupported()), 6_000);
+ init!.signal!.addEventListener('abort', () => {
+ clearTimeout(timer); reject(init!.signal!.reason);
+ }, { once: true });
+ }));
+ try {
+ const pending = probeProviderProtocols(spec, true, fetcher);
+ await vi.advanceTimersByTimeAsync(15_000);
+ const result = await pending;
+ expect(result).toMatchObject({ ok: false, decision: 'inconclusive', code: 'TIMEOUT', latencyMs: 15_000 });
+ expect(result.attempts).toHaveLength(3);
+ expect(fetcher).toHaveBeenCalledTimes(3);
+ expect(timeout).toHaveBeenCalledWith(15_000);
+ expect(timeout).toHaveBeenCalledWith(8_000);
+ } finally { timeout.mockRestore(); vi.useRealTimers(); }
+ });
+
+ it('keeps explicit single-route tests on their existing time budgets', async () => {
+ const timeout = vi.spyOn(AbortSignal, 'timeout');
+ try {
+ expect(await probeProviderProtocols(spec, false, async () => chat())).toMatchObject({ ok: true });
+ expect(timeout).toHaveBeenCalledWith(60_000);
+ expect(timeout).toHaveBeenCalledWith(20_000);
+ expect(timeout).not.toHaveBeenCalledWith(15_000);
+ expect(timeout).not.toHaveBeenCalledWith(8_000);
+ } finally { timeout.mockRestore(); }
+ });
+
+ it('does not open a connection when cancelled before the first candidate', async () => {
+ const controller = new AbortController(); controller.abort();
+ const fetcher = vi.fn<typeof fetch>();
+ expect(await probeProviderProtocols(spec, true, fetcher, controller.signal)).toMatchObject({
+ ok: false, decision: 'cancelled', attempts: [],
+ });
+ expect(fetcher).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [403, 'unsupported_protocol', 'blocked', 1],
+ [429, 'unsupported_protocol', 'blocked', 1],
+ [500, 'unsupported_protocol', 'inconclusive', 1],
+ [422, 'insufficient_quota unsupported_protocol', 'blocked', 1],
+ [400, 'model not found unsupported_protocol', 'blocked', 1],
+ [400, 'invalid api key unsupported_protocol', 'blocked', 1],
+ [405, 'method not allowed', 'inconclusive', 1],
+ [415, 'unsupported media type', 'inconclusive', 1],
+ [422, 'invalid request', 'inconclusive', 1],
+ [405, 'endpoint is not supported', 'next', 4],
+ [415, 'unsupported_protocol', 'next', 4],
+ [422, 'route_not_found', 'next', 4],
+ ] as const)('prioritizes terminal errors over protocol wording: %s %s', async (status, message, decision, count) => {
+ const fetcher = vi.fn<typeof fetch>(async () => new Response(JSON.stringify({ error: { message } }), { status }));
+ const result = await probeProviderProtocols(spec, true, fetcher);
+ expect(result).toMatchObject({ ok: false, decision });
+ expect(result.attempts).toHaveLength(count);
+ expect(fetcher).toHaveBeenCalledTimes(count);
+ });
+
+ it.each([
+ 'data: {broken}\n\n',
+ 'data: [DONE]\n\n',
+ 'data: ' + JSON.stringify({ choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] }) + '\n\n',
+ 'data: ' + JSON.stringify({ value: 'x'.repeat(1024 * 1024 + 1) }) + '\n\n',
+ ])('does not replay malformed, empty or oversized accepted streams', async body => {
+ const fetcher = vi.fn<typeof fetch>(async () => new Response(body, { headers: { 'content-type': 'text/event-stream' } }));
+ expect(await probeProviderProtocols(spec, true, fetcher)).toMatchObject({ ok: false, decision: 'inconclusive' });
+ expect(fetcher).toHaveBeenCalledOnce();
+ });
+
+ it('keeps credentials and upstream diagnostics out of the result envelope', async () => {
+ const secret = 'fake-secret-that-must-not-be-echoed';
+ const fetcher = vi.fn<typeof fetch>(async () => new Response(JSON.stringify({ error: { message: 'invalid api key ' + secret } }), { status: 401 }));
+ const result = await probeProviderProtocols({ ...spec, apiKey: secret }, true, fetcher);
+ expect(result).toMatchObject({ ok: false, code: 'AUTH_INVALID' });
+ expect(JSON.stringify(result)).not.toContain(secret);
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/pi-provider-transport.ts b/apps/desktop/src/main/maker-host/pi-provider-transport.ts
index 26ac03210a..496919d26a 100644
--- a/apps/desktop/src/main/maker-host/pi-provider-transport.ts
+++ b/apps/desktop/src/main/maker-host/pi-provider-transport.ts
@@ -221,7 +221,7 @@ function nativeInvocationModel(options: PiProviderTransportOptions, modelId: str
}
/** Use the same SDK, model identity and destination as chat, with a bounded probe. */
-export async function probePiProvider(options: PiProviderTransportOptions, signal: AbortSignal): Promise<AssistantMessage> {
+export async function probePiProvider(options: PiProviderTransportOptions, signal: AbortSignal, maxTokens?: number): Promise<AssistantMessage> {
const model = nativeInvocationModel(options, options.row.id);
const adapter = adapters[model.api];
if (!adapter) throw new Error('Native API is not supported by the bundled Pi adapter');
@@ -232,7 +232,8 @@ export async function probePiProvider(options: PiProviderTransportOptions, signa
headers: cloudflare ? cloudflareGatewayHeaders(options.apiKey, options.headers) : options.headers,
...(!['google-generative-ai', 'google-vertex', 'bedrock-converse-stream'].includes(model.api)
? { fetch: options.fetchImpl } : {}),
- signal, maxRetries: 0, maxTokens: Math.min(16, model.maxTokens),
+ signal, maxRetries: 0, maxTokens: Math.min(maxTokens ?? 16, model.maxTokens),
+ ...(maxTokens !== undefined ? { reasoning: nativeThinkingLevel(undefined, options.row, model) } : {}),
}).result();
}
diff --git a/apps/desktop/src/main/maker-host/provider-diagnostics.ts b/apps/desktop/src/main/maker-host/provider-diagnostics.ts
index 542403d146..3714650376 100644
--- a/apps/desktop/src/main/maker-host/provider-diagnostics.ts
+++ b/apps/desktop/src/main/maker-host/provider-diagnostics.ts
@@ -40,6 +40,9 @@ import { outboundFetch } from './outbound-fetch.js';
import { hostCredentialEndpointAllowed, invocationModelRecord, probePiProvider, requiresNativeProviderAuth } from './pi-provider-transport.js';
import { buildRouteDecision, providerRoutingForModel } from './provider-route.js';
+import type { ProviderConnectionTestInput, ProviderConnectionTestResult } from '../../shared/providerConnectionTest.js';
+import { probeProviderProtocols } from './provider-protocol-probe.js';
+
const log = createMakerLogger('provider-probe');
/** 探测请求超时。 */
@@ -70,21 +73,8 @@ export interface ProviderProbeSpec {
}
/** 测试入参:已保存供应商(key 从 safeStorage 读)或表单态 adhoc。 */
-export type ProviderTestInput =
- | { kind: 'saved'; providerId: string; agent: AgentKind }
- | { kind: 'adhoc'; spec: ProviderProbeSpec };
-
-/** 结构化测试结果(查询型返回:renderer 需要 code 渲染分类文案,不走 throwIpcError)。 */
-export interface ProviderTestResult {
- ok: boolean;
- /** 失败分类码(ok=true 时缺省)。 */
- code?: ProviderErrorCode;
- /** HTTP 状态码(网络层失败时缺省)。 */
- status?: number;
- latencyMs: number;
- /** 上游原始信息摘要(详情展开用,UI 主文案走 i18n)。 */
- detail?: string;
-}
+export type ProviderTestInput = ProviderConnectionTestInput;
+export type ProviderTestResult = ProviderConnectionTestResult;
// ── key 读取注入(同 provider-route 模式,避免纯逻辑单测触电 safeStorage)─────────
type KeyReader = (providerId: string, agent: AgentKind) => string | null;
@@ -563,8 +553,14 @@ export function setDiagnosticsOAuthTokenReader(reader: OAuthProbeTokenReader): v
export async function testProviderConnection(
input: ProviderTestInput,
fetchImpl: typeof fetch = outboundFetch,
+ signal?: AbortSignal,
): Promise<ProviderTestResult> {
const spec =
input.kind === 'saved' ? resolveSavedProbeSpec(input.providerId, input.agent) : input.spec;
+ const portable = !spec.api || ['openai-completions', 'openai-responses', 'anthropic-messages', 'google-generative-ai'].includes(spec.api);
+ // Keep preset/saved SDK-specific authentication and legacy callers on their existing path.
+ if (input.kind === 'adhoc' && input.requestId && spec.agent === 'pi' && portable && !spec.catalogPresetId) {
+ return logProbeFailure(spec, await probeProviderProtocols(spec, input.strategy === 'auto' && !spec.catalogPresetId && !spec.api && !spec.requestPath, fetchImpl, signal));
+ }
return runProviderProbe(spec, fetchImpl);
}
diff --git a/apps/desktop/src/main/maker-host/provider-protocol-probe.ts b/apps/desktop/src/main/maker-host/provider-protocol-probe.ts
new file mode 100644
index 0000000000..4c5c4b1b47
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/provider-protocol-probe.ts
@@ -0,0 +1,215 @@
+import {
+ appendProviderRequestPath, isLoopbackProviderUrl, providerProtocolCandidates,
+ providerModelRecord, providerPresetModelRecord,
+ type PiModelApi, type ProviderProtocolCandidate, type ProviderModelRecord,
+} from '@cindy/model-providers';
+import type { ProviderConnectionProbeSpec, ProviderConnectionTestResult, ProtocolProbeDecision } from '../../shared/providerConnectionTest.js';
+import { classifyProviderError } from '../../shared/providerErrors.js';
+import { invocationModelRecord, probePiProvider, readBoundedResponseText } from './pi-provider-transport.js';
+import { withOpenCodeGoSessionHeader } from './opencode-go-session.js';
+
+type ProbeSpec = ProviderConnectionProbeSpec & { nativeModel?: ProviderModelRecord };
+
+const API: Record<ProviderProtocolCandidate['wireProtocol'], PiModelApi> = {
+ 'openai-chat': 'openai-completions', 'openai-responses': 'openai-responses',
+ 'anthropic-messages': 'anthropic-messages', 'google-generative-ai': 'google-generative-ai',
+};
+const BLOCKED = new Set(['AUTH_INVALID', 'AUTH_FORBIDDEN', 'QUOTA_EXCEEDED', 'RATE_LIMITED', 'MODEL_NOT_FOUND']);
+
+/** Only explicit pre-generation protocol/route rejections permit another paid request. */
+function failure(status: number | undefined, bodyText: string, accepted: boolean): ProviderConnectionTestResult {
+ if (accepted && bodyText) {
+ try {
+ const error = JSON.parse(bodyText);
+ const type = String(error.type ?? error.code ?? '');
+ status = typeof error.status === 'number' ? error.status
+ : /auth|invalid_api_key/.test(type) ? 401 : /quota|balance/.test(type) ? 402
+ : /rate_limit/.test(type) ? 429 : /model_not_found/.test(type) ? 404 : 400;
+ } catch { /* Unstructured streamed errors remain inconclusive. */ }
+ }
+ const cls = classifyProviderError({ status, bodyText });
+ let decision: ProtocolProbeDecision = BLOCKED.has(cls.code) ? 'blocked' : 'inconclusive';
+ if (!accepted && [400, 404, 405, 415, 422].includes(status ?? 0)
+ && !BLOCKED.has(cls.code)
+ && /unsupported_protocol|unsupported_endpoint|route_not_found|(?:protocol|endpoint|route) (?:is )?(?:not supported|not found)/i.test(bodyText)) {
+ decision = 'next';
+ }
+ return { ok: false, code: decision === 'next' && cls.code === 'UNKNOWN' ? 'WIRE_INCOMPATIBLE' : cls.code,
+ status, latencyMs: 0, decision };
+}
+
+/** Observe protocol termination as well as SDK parsing: empty or truncated streams cannot pass. */
+function observeSse(wire: ProviderProtocolCandidate['wireProtocol']) {
+ let buffer = '';
+ let bytes = 0;
+ const decoder = new TextDecoder();
+ const state = { terminal: false, generated: false, error: '' };
+ const frame = (text: string) => {
+ const data = text.split('\n').filter(line => line.startsWith('data:')).map(line => line.slice(5).trimStart()).join('\n');
+ if (!data || data === '[DONE]') return;
+ const value = JSON.parse(data);
+ if (value.error) { state.error = JSON.stringify(value.error); return; }
+ if (wire === 'openai-chat') {
+ for (const choice of value.choices ?? []) {
+ if (choice.delta?.content || choice.delta?.reasoning_content) state.generated = true;
+ if (choice.finish_reason === 'stop' || choice.finish_reason === 'length') state.terminal = true;
+ }
+ } else if (wire === 'openai-responses') {
+ if (value.type === 'response.output_text.delta' || value.type === 'response.reasoning_text.delta') state.generated = true;
+ if (value.type === 'response.completed' || (value.type === 'response.incomplete'
+ && value.response?.incomplete_details?.reason === 'max_output_tokens')) state.terminal = true;
+ if (value.type === 'response.failed' || value.type === 'error') state.error = JSON.stringify(value);
+ } else if (wire === 'anthropic-messages') {
+ if (value.type === 'content_block_delta' && (value.delta?.text || value.delta?.thinking)) state.generated = true;
+ if (value.type === 'message_stop') state.terminal = true;
+ } else {
+ for (const candidate of value.candidates ?? []) {
+ if (candidate.content?.parts?.some((part: { text?: string }) => part.text)) state.generated = true;
+ if (['STOP', 'MAX_TOKENS'].includes(candidate.finishReason)) state.terminal = true;
+ }
+ }
+ };
+ const consume = (chunk: Uint8Array, final = false) => {
+ bytes += chunk.byteLength;
+ if (bytes > 1024 * 1024) throw new Error('probe response exceeds diagnostic budget');
+ buffer += decoder.decode(chunk, { stream: !final });
+ buffer = buffer.replace(/\r\n/g, '\n');
+ let end: number;
+ while ((end = buffer.indexOf('\n\n')) >= 0) {
+ frame(buffer.slice(0, end)); buffer = buffer.slice(end + 2);
+ }
+ if (buffer.length > 64 * 1024) throw new Error('probe SSE frame exceeds diagnostic budget');
+ if (final && buffer.trim()) frame(buffer);
+ };
+ const transform = new TransformStream<Uint8Array, Uint8Array>({
+ transform(chunk, controller) { consume(chunk); controller.enqueue(chunk); },
+ flush() { consume(new Uint8Array(), true); },
+ });
+ return { state, transform };
+}
+
+/** Native adapters own payloads. Google needs bounded HTTP because its SDK rejects injected
+ * fetch; it uses the same native base, auth and streaming endpoint. */
+async function attempt(
+ spec: ProbeSpec, candidate: ProviderProtocolCandidate,
+ fetchImpl: typeof fetch, signal: AbortSignal,
+): Promise<ProviderConnectionTestResult> {
+ let accepted = false;
+ let rejected: ProviderConnectionTestResult | undefined;
+ let networkCode: string | undefined;
+ const observer = observeSse(candidate.wireProtocol);
+ const guardedFetch: typeof fetch = async (input, init) => {
+ const target = new URL(input instanceof Request ? input.url : String(input));
+ if (target.origin !== new URL(candidate.baseUrl).origin) throw new Error('probe destination changed');
+ let response: Response;
+ const requestHeaders = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
+ const credentialNames = ['authorization', 'x-api-key', 'x-goog-api-key'];
+ if (!spec.apiKey || spec.authMethod === 'none') {
+ for (const name of credentialNames) requestHeaders.delete(name);
+ if (spec.authMethod !== 'none') {
+ const originalHeaders = new Headers(spec.headers);
+ for (const name of credentialNames) {
+ const value = originalHeaders.get(name);
+ if (value) requestHeaders.set(name, value);
+ }
+ }
+ }
+ for (const name of ['authorization', 'x-api-key']) {
+ if (requestHeaders.get(name)?.includes('cindy-probe-header-auth')) requestHeaders.delete(name);
+ }
+ try { response = await fetchImpl(input, { ...init, headers: requestHeaders, redirect: 'error', signal }); }
+ catch (error) {
+ networkCode = (error as { cause?: { code?: string }; name?: string }).cause?.code
+ ?? (error as { name?: string }).name;
+ throw error;
+ }
+ if (!response.ok) {
+ const text = await readBoundedResponseText(response);
+ rejected = failure(response.status, text, accepted);
+ return new Response(text, { status: response.status, headers: response.headers });
+ }
+ accepted = true;
+ if (!response.headers.get('content-type')?.toLowerCase().startsWith('text/event-stream') || !response.body) {
+ void response.body?.cancel().catch(() => undefined);
+ throw new Error('expected a native event stream');
+ }
+ return new Response(response.body.pipeThrough(observer.transform), { status: response.status, headers: response.headers });
+ };
+ try {
+ const api = API[candidate.wireProtocol];
+ const known = providerModelRecord(spec.modelId, candidate.baseUrl, api)
+ ?? providerPresetModelRecord(spec.catalogPresetId, spec.modelId, api);
+ const row = spec.nativeModel ?? known ?? invocationModelRecord({ id: spec.modelId, name: spec.modelId, group: 'custom',
+ contextWindow: 4096, maxOutput: 256, efforts: [], defaultEffort: null, api }, candidate.baseUrl)!;
+ const headers = withOpenCodeGoSessionHeader(Object.fromEntries(Object.entries(spec.headers ?? {}).filter(([name]) =>
+ !(spec.apiKey || spec.authMethod === 'none') || !['authorization', 'x-api-key', 'x-goog-api-key'].includes(name.toLowerCase()))),
+ { providerId: spec.catalogPresetId ?? '', catalogPresetId: spec.catalogPresetId, upstream: candidate.baseUrl }) ?? {};
+ const key = spec.authMethod === 'none' ? 'cindy-local-provider' : spec.apiKey
+ ?? new Headers(headers).get('authorization')?.replace(/^Bearer /i, '')
+ ?? new Headers(headers).get('x-api-key') ?? new Headers(headers).get('x-goog-api-key')
+ ?? (Object.keys(headers).length ? 'cindy-probe-header-auth' : '');
+ if (!key && spec.authMethod !== 'none') return { ok: false, code: 'AUTH_INVALID', latencyMs: 0, decision: 'blocked' };
+ let nativeOk = true;
+ let nativeGenerated = false;
+ if (api === 'google-generative-ai') {
+ const response = await guardedFetch(appendProviderRequestPath(candidate.baseUrl,
+ '/models/' + encodeURIComponent(spec.modelId.replace(/^models\//, '')) + ':streamGenerateContent?alt=sse'), {
+ method: 'POST', headers: { ...headers, 'content-type': 'application/json',
+ ...(spec.authMethod !== 'none' && key ? { 'x-goog-api-key': key } : {}) },
+ body: JSON.stringify({ contents: [{ role: 'user', parts: [{ text: 'Reply OK.' }] }],
+ generationConfig: { maxOutputTokens: Math.min(256, row.maxOutput ?? 256) } }),
+ });
+ if (response.ok && response.body) {
+ const reader = response.body.getReader();
+ try { while (!(await reader.read()).done) { /* observer validates every frame */ } }
+ finally { reader.releaseLock(); }
+ }
+ } else {
+ const result = await probePiProvider({ row, providerId: spec.catalogPresetId ?? 'custom-probe', upstream: candidate.baseUrl,
+ apiKey: key, headers, fetchImpl: guardedFetch }, signal, 256);
+ nativeOk = result.stopReason === 'stop' || result.stopReason === 'length';
+ nativeGenerated = result.content.some(block => (block.type === 'text' && Boolean(block.text))
+ || (block.type === 'thinking' && Boolean(block.thinking)));
+ }
+ if (signal.aborted) return { ok: false, code: 'TIMEOUT', latencyMs: 0, decision: 'inconclusive' };
+ if (rejected) return rejected;
+ if (!accepted && networkCode) {
+ return { ok: false, code: classifyProviderError({ networkErrorCode: networkCode }).code, latencyMs: 0, decision: 'inconclusive' };
+ }
+ if (nativeOk && observer.state.terminal && (observer.state.generated || nativeGenerated) && !observer.state.error) {
+ return { ok: true, latencyMs: 0, decision: 'success', selected: candidate };
+ }
+ return failure(accepted ? 200 : undefined, observer.state.error, accepted);
+ } catch {
+ if (rejected) return rejected;
+ const cls = classifyProviderError({ networkErrorCode: signal.aborted ? 'TimeoutError' : networkCode ?? 'UNKNOWN' });
+ return { ok: false, code: cls.code, latencyMs: 0, decision: 'inconclusive' };
+ }
+}
+
+/** One bounded operation: no parallel candidates, SDK retry, or retry after ambiguous execution. */
+export async function probeProviderProtocols(
+ spec: ProbeSpec, auto: boolean, fetchImpl: typeof fetch, signal?: AbortSignal,
+): Promise<ProviderConnectionTestResult> {
+ const start = Date.now();
+ if (spec.authMethod === 'none' && !isLoopbackProviderUrl(spec.baseUrl)) throw new TypeError('no-auth probe requires loopback');
+ let candidates: ProviderProtocolCandidate[];
+ try {
+ candidates = auto ? providerProtocolCandidates(spec.baseUrl, spec.wireProtocol)
+ : [{ baseUrl: spec.baseUrl, wireProtocol: spec.wireProtocol ?? 'openai-chat' }];
+ } catch { return { ok: false, code: 'ENDPOINT_NOT_FOUND', latencyMs: 0, decision: 'inconclusive' }; }
+ // Bound interactive auto-detection without shortening explicit single-route tests.
+ const overall = AbortSignal.any([AbortSignal.timeout(auto ? 15_000 : 60_000), ...(signal ? [signal] : [])]);
+ const attempts: NonNullable<ProviderConnectionTestResult['attempts']> = [];
+ let result: ProviderConnectionTestResult = { ok: false, code: 'UNKNOWN', latencyMs: 0, decision: 'inconclusive' };
+ for (const candidate of candidates) {
+ if (overall.aborted) break;
+ const current = AbortSignal.any([overall, AbortSignal.timeout(auto ? 8_000 : 20_000)]);
+ result = await attempt(spec, candidate, fetchImpl, current);
+ attempts.push({ ...candidate, decision: result.decision!, code: result.code, status: result.status });
+ if (result.decision !== 'next') break;
+ }
+ if (signal?.aborted) result = { ok: false, latencyMs: 0, decision: 'cancelled' };
+ else if (overall.aborted) result = { ok: false, code: 'TIMEOUT', latencyMs: 0, decision: 'inconclusive' };
+ return { ...result, latencyMs: Date.now() - start, attempts };
+}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
index 2ccff3b1f7..7cf1770bae 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
@@ -4684,6 +4684,24 @@ describe('provider detection drafts', () => {
}
expect(detectProvider).not.toHaveBeenCalled();
});
+ it('discards a replaced result without deleting the newer detection operation', async () => {
+ const harness = new IpcHarness();
+ const pending: { signal: AbortSignal; finish: (value: any) => void }[] = [];
+ registerProviderHandlers(harness, makeDeps({ detectProvider: (_spec, signal) => new Promise(resolve => {
+ pending.push({ signal, finish: resolve });
+ }) }));
+ const first = harness.invokeFrom(1, MAKER_INVOKE.PROVIDER_DETECT, input);
+ const second = harness.invokeFrom(1, MAKER_INVOKE.PROVIDER_DETECT, { ...input, requestId: 'draft-2' });
+ expect(pending[0].signal.aborted).toBe(true);
+ pending[0].finish({ candidates: ['sub2api'], reason: 'matched' });
+ expect(await first).toEqual({ candidates: [], reason: 'insufficient_evidence' });
+ await harness.invokeFrom(1, MAKER_INVOKE.PROVIDER_DETECT, { requestId: 'draft-1', cancel: true });
+ expect(pending[1].signal.aborted).toBe(false);
+ await harness.invokeFrom(1, MAKER_INVOKE.PROVIDER_DETECT, { requestId: 'draft-2', cancel: true });
+ expect(pending[1].signal.aborted).toBe(true);
+ pending[1].finish({ candidates: ['litellm'], reason: 'matched' });
+ expect(await second).toEqual({ candidates: [], reason: 'insufficient_evidence' });
+ });
it('isolates cancellations by sender and request, and cancels destroyed windows', async () => {
const harness = new IpcHarness();
const signals: AbortSignal[] = [];
@@ -4703,3 +4721,53 @@ describe('provider detection drafts', () => {
expect(signals[1].aborted).toBe(true);
});
});
+
+// New probe lifecycle shares the existing IPC, with sender-owned cancellation and no secret echo.
+describe('one-click protocol test ownership', () => {
+ const request = { kind: 'adhoc', requestId: 'probe-test', strategy: 'auto', spec: {
+ agent: 'pi', authMethod: 'apiKey', baseUrl: 'https://relay.example/v1', modelId: 'test', apiKey: 'fake-key',
+ } };
+ it('forwards the automatic strategy and cancels only the owning renderer operation', async () => {
+ const harness = new IpcHarness();
+ let signal!: AbortSignal;
+ let finish!: (result: { ok: boolean; latencyMs: number }) => void;
+ const testConnection = vi.fn((_input: unknown, current?: AbortSignal) => { signal = current!; return new Promise<{ ok: boolean; latencyMs: number }>(resolve => { finish = resolve; }); });
+ registerProviderHandlers(harness, makeDeps({ testConnection }));
+ const pending = harness.invokeFrom(7, MAKER_INVOKE.PROVIDER_TEST_CONNECTION, request);
+ await harness.invokeFrom(8, MAKER_INVOKE.PROVIDER_TEST_CONNECTION, { kind: 'cancel', requestId: request.requestId });
+ expect(signal.aborted).toBe(false);
+ await expect(harness.invokeFrom(7, MAKER_INVOKE.PROVIDER_TEST_CONNECTION, request)).rejects.toThrow(/PRECONDITION_FAILED/);
+ await harness.invokeFrom(7, MAKER_INVOKE.PROVIDER_TEST_CONNECTION, { kind: 'cancel', requestId: request.requestId });
+ expect(signal.aborted).toBe(true);
+ finish({ ok: true, latencyMs: 1 });
+ expect(await pending).toMatchObject({ ok: false, decision: 'cancelled' });
+ expect(testConnection).toHaveBeenCalledOnce();
+ expect(testConnection.mock.calls[0][0]).toMatchObject(request);
+ });
+ it.each([
+ { ...request, spec: { ...request.spec, agent: 'codex' } },
+ { ...request, spec: { ...request.spec, catalogPresetId: 'google-gemini-api' } },
+ { ...request, spec: { ...request.spec, api: 'google-vertex' } },
+ { ...request, spec: { ...request.spec, baseUrl: 'https://user:[email protected]/v1' } },
+ { ...request, requestId: '../bad' },
+ ])('rejects unsupported strategy or credential binding before executing', async input => {
+ const harness = new IpcHarness();
+ const deps = makeDeps();
+ registerProviderHandlers(harness, deps);
+ await expect(harness.invokeFrom(7, MAKER_INVOKE.PROVIDER_TEST_CONNECTION, input)).rejects.toThrow(/INVALID_PARAMS/);
+ expect(deps.testConnection).not.toHaveBeenCalled();
+ });
+ it('aborts the operation when its renderer is destroyed', async () => {
+ const harness = new IpcHarness();
+ let signal!: AbortSignal;
+ const testConnection = vi.fn((_input: unknown, current?: AbortSignal) => {
+ signal = current!;
+ return new Promise<{ ok: boolean; latencyMs: number }>(resolve => current!.addEventListener('abort', () => resolve({ ok: false, latencyMs: 0 }), { once: true }));
+ });
+ registerProviderHandlers(harness, makeDeps({ testConnection }));
+ const pending = harness.invokeFrom(7, MAKER_INVOKE.PROVIDER_TEST_CONNECTION, request);
+ harness.destroySender(7);
+ expect(signal.aborted).toBe(true);
+ expect(await pending).toMatchObject({ decision: 'cancelled' });
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
index 5122edb74d..9feb40edc7 100644
--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
@@ -317,7 +317,7 @@ export interface ProviderHandlerDeps {
/** 目录 presets 段(生产 = () => getActiveCatalog().presets ?? [])。 */
listPresets(): ProviderPreset[];
/** 测试连接(生产 = testProviderConnection;单测注入 stub 不联网)。 */
- testConnection(input: ProviderTestInput): Promise<ProviderTestResult>;
+ testConnection(input: ProviderTestInput, signal?: AbortSignal): Promise<ProviderTestResult>;
/** 获取模型列表(生产 = fetchProviderModels;单测注入 stub 不联网)。 */
fetchModels(spec: ProviderModelsFetchSpec): Promise<ProviderModelsFetchResult>;
detectProvider?(spec: ProviderModelsFetchSpec, signal: AbortSignal): Promise<DeploymentDetectionResult>;
@@ -475,10 +475,14 @@ export interface ModelContextLimitView {
function parseTestInput(input: unknown): ProviderTestInput | null {
if (!input || typeof input !== 'object') return null;
const i = input as Record<string, unknown>;
+ if (i.requestId !== undefined && (typeof i.requestId !== 'string' || !/^[a-zA-Z0-9_-]{1,100}$/.test(i.requestId))) return null;
+ if (i.strategy !== undefined && i.strategy !== 'auto') return null;
+ const options = { ...(i.requestId ? { requestId: i.requestId as string } : {}), ...(i.strategy === 'auto' ? { strategy: 'auto' as const } : {}) };
+ if (i.strategy === 'auto' && (!i.requestId || i.kind !== 'adhoc')) return null;
if (i.kind === 'saved') {
if (typeof i.providerId !== 'string' || i.providerId.length === 0) return null;
if (typeof i.agent !== 'string' || !VALID_AGENTS.includes(i.agent)) return null;
- return { kind: 'saved', providerId: i.providerId, agent: i.agent as AgentKind };
+ return { kind: 'saved', providerId: i.providerId, agent: i.agent as AgentKind, ...options };
}
if (i.kind === 'adhoc') {
const s = i.spec;
@@ -487,10 +491,10 @@ function parseTestInput(input: unknown): ProviderTestInput | 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;
- if (typeof spec.baseUrl !== 'string' || spec.baseUrl.length === 0) return null;
+ if (typeof spec.baseUrl !== 'string' || spec.baseUrl.length === 0 || spec.baseUrl.length > 4096) return null;
try {
const u = new URL(spec.baseUrl);
- if (u.protocol !== 'http:' && u.protocol !== 'https:') return null;
+ if ((u.protocol !== 'http:' && u.protocol !== 'https:') || u.username || u.password) return null;
} catch {
return null;
}
@@ -513,8 +517,12 @@ function parseTestInput(input: unknown): ProviderTestInput | null {
if (spec.api !== undefined && (typeof spec.api !== 'string' || !(PI_MODEL_APIS as readonly string[]).includes(spec.api))) return null;
if (spec.catalogPresetId !== undefined && typeof spec.catalogPresetId !== 'string') return null;
if (spec.requestPath !== undefined && !isProviderRequestPath(spec.requestPath)) return null;
+ if ((typeof spec.apiKey === 'string' && spec.apiKey.length > 16384) || (spec.modelId as string).length > 1024
+ || Object.keys(spec.headers ?? {}).length > 64
+ || Object.entries(spec.headers ?? {}).some(([k, v]) => k.length > 256 || (v as string).length > 16384)) return null;
+ if (i.strategy === 'auto' && (spec.agent !== 'pi' || spec.catalogPresetId || spec.api || spec.requestPath || spec.authMethod === 'oauth')) return null;
return {
- kind: 'adhoc',
+ kind: 'adhoc', ...options,
spec: {
agent: spec.agent as AgentKind,
baseUrl: spec.baseUrl,
@@ -2316,14 +2324,40 @@ export function registerProviderHandlers(
// 测试连接:查询型结构化返回(规则 13 例外条款——renderer 需要 code 渲染分类文案)。
// 入参非法 / saved 解析失败(供应商不存在等)仍走 throwIpcError。
- registry.handle(MAKER_INVOKE.PROVIDER_TEST_CONNECTION, async (_event, input: unknown) => {
+ const connectionTests = new Map<ProviderOAuthRendererSender, { id: string; controller: AbortController }>();
+ registry.handle(MAKER_INVOKE.PROVIDER_TEST_CONNECTION, async (event, input: unknown) => {
+ assertTrustedProviderMutationSender(event);
+ const sender = providerOAuthRendererSender(event);
+ const value = input as Record<string, unknown> | null;
+ if (value?.kind === 'cancel') {
+ if (!sender || typeof value.requestId !== 'string' || !/^[a-zA-Z0-9_-]{1,100}$/.test(value.requestId)) throwIpcError('INVALID_PARAMS', 'invalid test cancellation');
+ const previous = connectionTests.get(sender);
+ if (previous?.id === value.requestId) previous.controller.abort();
+ return { ok: false, latencyMs: 0, decision: 'cancelled' };
+ }
const parsed = parseTestInput(input);
if (!parsed) throwIpcError('INVALID_PARAMS', 'invalid test-connection input');
+ // Old callers retain their single-test contract; new operations are owned by the sender.
+ if (!parsed.requestId) {
+ try { return await deps.testConnection(parsed); }
+ catch { throwIpcError('INVALID_PARAMS', 'invalid saved provider connection'); }
+ }
+ if (!sender) throwIpcError('INVALID_PARAMS', 'missing test owner');
+ if (connectionTests.has(sender)) throwIpcError('PRECONDITION_FAILED', 'connection test already running');
+ const controller = new AbortController();
+ const operation = { id: parsed.requestId, controller };
+ connectionTests.set(sender, operation);
+ const owner = captureProviderOwnerSession();
+ const abort = () => controller.abort();
+ sender.once?.('destroyed', abort);
try {
- return await deps.testConnection(parsed);
- } catch (err) {
- // resolveSavedProbeSpec 的解析错误(provider 不存在 / 无该 runtime)→ INVALID_PARAMS。
- throwIpcError('INVALID_PARAMS', err instanceof Error ? err.message : String(err));
+ const result = await deps.testConnection(parsed, controller.signal);
+ if (controller.signal.aborted || !providerMutationOwnerMatches(owner)) return { ok: false, latencyMs: 0, decision: 'cancelled' };
+ return result;
+ } catch { throwIpcError('INVALID_PARAMS', 'invalid provider connection test'); }
+ finally {
+ sender.removeListener?.('destroyed', abort);
+ if (connectionTests.get(sender) === operation) connectionTests.delete(sender);
}
});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 3611536c71..0637037e95 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -6781,7 +6781,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
setProviderOrder: (providerIds) => setProviderOrder(providerIds),
getProviderOrder: () => readProviderOrder(),
listPresets: () => getActiveCatalog().presets ?? [],
- testConnection: (input) => testProviderConnection(input),
+ testConnection: (input, signal) => testProviderConnection(input, undefined, signal),
detectProvider: detectProviderDeployment,
fetchModels: async (spec) => {
if (spec.savedProviderId && subscriptionAccountKind(spec.savedProviderId)) {
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index fe78243106..1c70d8e54b 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -6319,30 +6319,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
* saved: 已保存供应商(key main 侧从 safeStorage 读);adhoc: 表单未保存值(key 仅内存透传)。
*/
testProviderConnection: (
- input:
- | { kind: 'saved'; providerId: string; agent: 'claude-code' | 'codex' | 'pi' }
- | {
- kind: 'adhoc';
- spec: {
- agent: 'claude-code' | 'codex' | 'pi';
- baseUrl: string;
- modelId: string;
- authMethod: 'apiKey' | 'oauth' | 'none';
- wireProtocol?: import('@cindy/model-providers').ProviderWireProtocol;
- api?: import('@cindy/model-providers').PiModelApi;
- catalogPresetId?: string;
- requestPath?: string;
- apiKey?: string | null;
- headers?: Record<string, string>;
- };
- },
- ): Promise<{
- ok: boolean;
- code?: import('../shared/providerErrors').ProviderErrorCode;
- status?: number;
- latencyMs: number;
- detail?: string;
- }> => ipcRenderer.invoke('maker:provider:test-connection', input),
+ input: import('../shared/providerConnectionTest').ProviderConnectionTestRequest,
+ ): Promise<import('../shared/providerConnectionTest').ProviderConnectionTestResult> =>
+ ipcRenderer.invoke('maker:provider:test-connection', input),
/**
* 供应商「获取模型列表」—— 用表单值 GET 该供应商的列模型端点(key 仅内存透传)。
* 结构化结果:ok=true 带 models;失败 code 走 providerError.* i18n。
diff --git a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx
index e828f9b251..ddcce6c00f 100644
--- a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx
@@ -1526,6 +1526,42 @@ describe('identified provider handoff', () => {
expect(config.runtimes.pi!.models.find(m => m.id === 'unselected')?.defaultEnabled).toBe(false);
expect(keys).toEqual({ pi: 'fake-key' });
});
+ it.each([true, false])('current checkbox overrides an old disabled draft: checked=%s', async checked => {
+ const handoff = { ...detected, config: { ...detected.config, runtimes: { pi: {
+ ...detected.config.runtimes.pi, models: [{ ...model, defaultEnabled: false }, { id: 'keep', name: 'Keep' }],
+ } } } };
+ 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));
+ if (!checked) fireEvent.click(screen.getByText('Upstream name'));
+ fireEvent.click(finish);
+ await waitFor(() => expect(createCustomProvider).toHaveBeenCalledOnce());
+ const saved = vi.mocked(createCustomProvider).mock.calls[0][0].runtimes.pi!.models.find(m => m.id === model.id)!;
+ expect(saved.defaultEnabled).toBe(checked ? undefined : false);
+ expect(saved).toMatchObject({ contextWindow: model.contextWindow, route: model.route });
+ });
+ it.each([true, false])('returns the current selection without reviving disabled flags: %s', async checked => {
+ const handoff = { ...detected, config: { ...detected.config, runtimes: { pi: {
+ ...detected.config.runtimes.pi, models: [{ ...model, defaultEnabled: false }, { id: 'keep', name: 'Keep' }],
+ } } } };
+ const onReturnCustom = vi.fn();
+ render(<AddProviderWizard providers={[]} detected={handoff} onReturnCustom={onReturnCustom} onClose={vi.fn()} onDone={vi.fn()} onOpenCustomForm={vi.fn()} />);
+ fireEvent.click(await screen.findByRole('button', { name: 'settings.providers.wizard.next' }));
+ const finish = await screen.findByRole('button', { name: 'settings.providers.wizard.finish' });
+ await waitFor(() => expect(finish.hasAttribute('disabled')).toBe(false));
+ if (!checked) fireEvent.click(screen.getByText('Upstream name'));
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.wizard.back' }));
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.wizard.back' }));
+ const models = onReturnCustom.mock.calls[0][0].config.runtimes.pi.models;
+ const returned = models.find((m: { id: string }) => m.id === model.id);
+ if (checked) {
+ expect(returned.defaultEnabled).toBeUndefined();
+ expect(returned).toMatchObject({ contextWindow: model.contextWindow, route: model.route });
+ } else expect(returned).toBeUndefined();
+ expect(models.some((m: { id: string }) => m.id === 'keep')).toBe(true);
+ expect(createCustomProvider).not.toHaveBeenCalled();
+ });
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' },
diff --git a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
index 2d6629d576..ec418b5bc7 100644
--- a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
+++ b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
@@ -1362,8 +1362,12 @@ export function AddProviderWizard({
const presetModel = rt.models.find((candidate) => candidate.id === m.id);
// Only interface facts belong to discovery. Preset defaults follow a live reference.
const discoveredMetadata = m.discoveredMetadata?.[agent] ?? {};
+ // Current picks own visibility; an old disabled draft must not override
+ // a checked row. Leave checked models on the existing default contract.
+ const { defaultEnabled: _oldEnabled, ...draftModel } =
+ detected?.config.runtimes[agent]?.models.find(model => model.id === m.id) ?? {};
return {
- ...(detected?.config.runtimes[agent]?.models.find(model => model.id === m.id) ?? {}),
+ ...draftModel,
id: m.id,
name: m.name,
// Selecting a model follows native-engine defaults; it is not an
@@ -2245,7 +2249,10 @@ export function AddProviderWizard({
.filter(([, model]) => model.checked && model.agents.includes(target))
.map(([id, model]) => {
const saved = original.models.find(row => row.id === id);
- return { ...saved, id, name: model.name,
+ // Only checked rows return to the custom form. Do not
+ // resurrect an older disabled flag on this second save path.
+ const { defaultEnabled: _oldEnabled, ...selectedModel } = saved ?? {};
+ return { ...selectedModel, id, name: model.name,
discoveredMetadata: model.discoveredMetadata?.[target] ?? saved?.discoveredMetadata,
...(saved?.route ?? model.routes?.[target] ? { route: saved?.route ?? model.routes?.[target] } : {}),
};
diff --git a/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx b/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx
index 2ca441389c..a90880e673 100644
--- a/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx
+++ b/apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx
@@ -1,7 +1,8 @@
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 { matchOfficialProviders, bindDetectedProvider, isAgentSelectableModel, isLoopbackProviderUrl } from '@cindy/model-providers';
+import type { ProviderConnectionTestResult } from '../../../shared/providerConnectionTest';
import type { DetectedProviderDraft, DetectionCatalog } from '../../../shared/providerDetection';
import { OFFICIAL_API_PRESETS } from './AddProviderWizard';
let detectionRequestSequence = 0;
@@ -279,6 +280,8 @@ interface TestState {
/** 失败分类码(providerError.<code> i18n 键)。 */
code?: string;
latencyMs?: number;
+ decision?: ProviderConnectionTestResult['decision'];
+ attempts?: ProviderConnectionTestResult['attempts'];
}
const IDLE_TEST: TestState = { status: 'idle' };
@@ -519,14 +522,25 @@ export function ProviderConnectionDialog({
const [imageGenerationReloadConfirmation, setImageGenerationReloadConfirmation] =
useState<ImageGenerationReloadConfirmation | null>(null);
// 鉴权形态:API key(默认)/ OAuth / 无鉴权(本机或受信自托管代理)。
- const [authMode, setAuthModeState] = useState<CustomProviderAuthMode>(
+ const [selectedAuthMode, setAuthModeState] = useState<CustomProviderAuthMode>(
initial?.auth?.method === 'oauth'
? 'oauth'
: (initial ?? draft?.config)?.auth?.method === 'none'
? 'none'
: 'apiKey',
);
+ // The simplified add form has no auth selector. Infer no-auth only for an
+ // entirely local, credential-free draft; independent engines must not lose auth.
+ // Keep the key input visible so adding credentials switches back to API-key mode.
+ const authMode: CustomProviderAuthMode = simpleAdding && selectedAuthMode !== 'oauth'
+ ? rt[activeTab].baseUrl.trim() && Object.values(rt).every(fields =>
+ !fields.apiKey.trim() && !fields.headers.some(header => header.name.trim()) &&
+ (!fields.baseUrl.trim() || isLoopbackProviderUrl(fields.baseUrl.trim())) &&
+ (!fields.modelsUrl.trim() || isLoopbackProviderUrl(fields.modelsUrl.trim())))
+ ? 'none' : 'apiKey'
+ : selectedAuthMode;
const authModeRef = useRef(authMode);
+ authModeRef.current = authMode;
const setAuthMode = useCallback((mode: CustomProviderAuthMode) => {
authModeRef.current = mode;
setAuthModeState(mode);
@@ -968,7 +982,7 @@ export function ProviderConnectionDialog({
detectionContext.current = { name, activeTab, onDetected, signature: detectionSignature };
const enterDetectedProvider = useCallback((preset: ProviderPreset) => {
- if (savingRef.current || childLayerRef.current || runtimeFillRef.current) return;
+ if (savingRef.current || childLayerRef.current || runtimeFillRef.current || connectionTestRef.current) return;
const context = detectionContext.current;
const sourceAgent = context.activeTab;
const fields = rtRef.current[sourceAgent];
@@ -1428,7 +1442,25 @@ export function ProviderConnectionDialog({
return !template?.includes('{') || providerEndpointBindings(template, fields.baseUrl.trim()) !== null;
}, [presets]);
+ const connectionTestRef = useRef<{ id: string; agent: DialogAgentKind; signature: string } | null>(null);
+ const connectionSignature = providerConnectionTestRequestSignature(runtimeProbeFields(activeTab, rt[activeTab], catalogModels?.[activeTab]), authMode);
+ const cancelConnectionTest = useCallback(() => {
+ const current = connectionTestRef.current;
+ if (!current) return;
+ connectionTestRef.current = null;
+ void window.electronAPI.maker.testProviderConnection({ kind: 'cancel', requestId: current.id }).catch(() => undefined);
+ }, []);
+ useLayoutEffect(() => {
+ const current = connectionTestRef.current;
+ if (current && (!dialog.open || current.agent !== activeTab || current.signature !== connectionSignature)) {
+ cancelConnectionTest();
+ setTest(previous => ({ ...previous, [current.agent]: IDLE_TEST }));
+ }
+ }, [activeTab, connectionSignature, dialog.open, cancelConnectionTest]);
+ useEffect(() => () => cancelConnectionTest(), [cancelConnectionTest]);
+
const handleTest = useCallback(async () => {
+ if (connectionTestRef.current || modelFetchInFlightRef.current || picker) return;
const agent = activeTab;
const rf = rt[agent];
const probeFields = runtimeProbeFields(agent, rf, catalogModels?.[agent]);
@@ -1478,6 +1510,15 @@ export function ProviderConnectionDialog({
savedBaseline &&
connectionTestCanUseSaved(probeFields, savedBaseline, authMode),
);
+ const originalModel = draft?.config.runtimes[agent]?.models.find(model => model.id.trim() === firstModel);
+ const automatic = simpleAdding && agent === 'pi' && !rf.catalogPresetId && !rf.requestPath
+ && !originalModel?.api && !originalModel?.piApi && !originalModel?.route;
+ const cancellable = simpleAdding && agent === 'pi' && !rf.catalogPresetId
+ && (!probeRoute.api || ['openai-completions', 'openai-responses', 'anthropic-messages', 'google-generative-ai'].includes(probeRoute.api));
+ const requestId = cancellable ? 'connection-' + Date.now() + '-' + (++detectionRequestSequence) : undefined;
+ if (requestId) {
+ connectionTestRef.current = { id: requestId, agent, signature: requestSig };
+ }
setTest((prev) => ({ ...prev, [agent]: { status: 'testing' } }));
try {
const result = await window.electronAPI.maker.testProviderConnection(
@@ -1485,13 +1526,14 @@ export function ProviderConnectionDialog({
? { kind: 'saved', providerId: initial!.id, agent }
: {
kind: 'adhoc',
+ ...(requestId ? { requestId, ...(automatic ? { strategy: 'auto' as const } : {}) } : {}),
spec: {
agent,
baseUrl,
modelId: firstModel,
authMethod: authMode,
wireProtocol: probeWireProtocol,
- ...(probeRoute.api ? { api: probeRoute.api } : {}),
+ ...(!automatic && probeRoute.api ? { api: probeRoute.api } : {}),
...(rf.catalogPresetId ? { catalogPresetId: rf.catalogPresetId } : {}),
...(probeRequestPath ? { requestPath: probeRequestPath } : {}),
apiKey: authMode === 'apiKey' && canSendApiKey ? rf.apiKey.trim() || null : null,
@@ -1499,6 +1541,7 @@ export function ProviderConnectionDialog({
},
},
);
+ if (requestId && connectionTestRef.current?.id !== requestId) return;
if (
providerConnectionTestRequestSignature(
runtimeProbeFields(agent, rtRef.current[agent], catalogModelsRef.current?.[agent]),
@@ -1506,13 +1549,28 @@ export function ProviderConnectionDialog({
) !== requestSig
)
return;
+ if (requestId) connectionTestRef.current = null;
+ if (result.decision === 'cancelled') {
+ setTest(previous => ({ ...previous, [agent]: IDLE_TEST }));
+ return;
+ }
+ if (automatic && result.ok && result.selected) {
+ const selected = result.selected;
+ const api = selected.wireProtocol === 'openai-chat' ? 'openai-completions' as const : selected.wireProtocol;
+ setRtSynced(previous => ({ ...previous, [agent]: { ...previous[agent],
+ baseUrl: selected.baseUrl, modelRouteBaseUrl: selected.baseUrl, wireProtocol: selected.wireProtocol, requestPath: '',
+ models: previous[agent].models.map(model => model.id.trim() === firstModel
+ ? { ...model, api, piApi: api, route: { baseUrl: selected.baseUrl, wireProtocol: selected.wireProtocol } } : model),
+ } }));
+ }
setTest((prev) => ({
...prev,
[agent]: result.ok
? { status: 'ok', latencyMs: result.latencyMs }
- : { status: 'fail', code: result.code ?? 'UNKNOWN' },
+ : { status: 'fail', code: result.code ?? 'UNKNOWN', decision: result.decision, attempts: result.attempts },
}));
} catch (e) {
+ if (requestId && connectionTestRef.current?.id !== requestId) return;
if (
providerConnectionTestRequestSignature(
runtimeProbeFields(agent, rtRef.current[agent], catalogModelsRef.current?.[agent]),
@@ -1520,11 +1578,12 @@ export function ProviderConnectionDialog({
) !== requestSig
)
return;
+ if (requestId) connectionTestRef.current = null;
const ipc = extractIpcError(e);
setTest((prev) => ({ ...prev, [agent]: { status: 'fail', code: 'UNKNOWN' } }));
if (ipc?.message) toast.error(ipc.message);
}
- }, [activeTab, authMode, rt, t, savedBaselineFor, initial, presets, matchesEndpointTemplate, catalogModels]);
+ }, [activeTab, authMode, rt, t, savedBaselineFor, initial, presets, matchesEndpointTemplate, catalogModels, simpleAdding, setRtSynced, picker, draft]);
// 拉取单飞:任一 runtime(含 Pi)在途时所有 Tab 的拉取按钮都禁用——两个并发请求会竞争
// 同一个勾选弹层(后到的覆盖先开的、确认还会写进另一个 runtime),单飞直接消掉这类竞态。
@@ -1797,7 +1856,7 @@ export function ProviderConnectionDialog({
}, [picker, patch]);
const handleSave = useCallback(async () => {
- if (savingRef.current) return;
+ if (savingRef.current || connectionTestRef.current) return;
setFieldError(null);
const trimmedName = name.trim();
if (!trimmedName) {
@@ -1838,6 +1897,8 @@ export function ProviderConnectionDialog({
const keys: RuntimeKeys = {};
for (const a of VISIBLE_AGENTS) {
const rf = rt[a];
+ if (simpleAdding && activeTab === 'pi' && !rt.pi.catalogPresetId && a !== 'pi'
+ && (!draft?.config.runtimes[a] || followsDefaultConnection(a, rf, rt.pi))) continue;
if (!rf.baseUrl.trim()) continue; // 该 runtime 未配置
try {
const u = new URL(rf.baseUrl.trim());
@@ -2093,6 +2154,8 @@ export function ProviderConnectionDialog({
}, [
name,
activeTab,
+ simpleAdding,
+ draft,
rowId,
reportFieldError,
keyHydrationReady,
@@ -2152,6 +2215,10 @@ export function ProviderConnectionDialog({
[editing, onSaved, t],
);
+ const detectionAuthFailed = !editing && detection?.signature === detectionSignature &&
+ authMode === 'apiKey' && detection.code === 'AUTH_INVALID';
+ const detectionKeyMissing = detectionAuthFailed && !f.apiKey.trim();
+
const activeSavedBaseline = savedBaselineFor(activeTab);
// 共享判据:当前表单的端点相对已存基线是否未变。密钥与请求头都只在
// 端点未变时继续有效——main 侧改端点后会清掉已存头,renderer 的徽标
@@ -2581,13 +2648,13 @@ export function ProviderConnectionDialog({
)}
{/* API 密钥(OAuth 形态隐藏——鉴权走 Runner 的 Bearer,不收集 key) */}
- {authMode === 'apiKey' && (
+ {(simpleAdding || authMode === 'apiKey') && (
<div className="flex flex-col gap-[7px]">
<FormField
id={fieldId(`${activeTab}:apiKey`)}
label={t('settings.providers.custom.fields.apiKey')}
- error={errorFor(`${activeTab}:apiKey`)}
- hint={simpleAdding ? undefined : t('settings.providers.custom.fields.apiKeyHelp')}
+ error={errorFor(`${activeTab}:apiKey`) ?? (detectionAuthFailed && !detectionKeyMissing ? t('settings.providers.detection.authRejected') : undefined)}
+ hint={detectionKeyMissing ? t('settings.providers.detection.keyRequired') : simpleAdding ? undefined : t('settings.providers.custom.fields.apiKeyHelp')}
labelAction={
activeKeyCanRemainSaved &&
f.apiKey.trim() && (
@@ -2625,12 +2692,12 @@ export function ProviderConnectionDialog({
</div>
)}
- {!editing && detection?.signature === detectionSignature && (
+ {!editing && detection?.signature === detectionSignature && (!detectionAuthFailed || detection.preset) && (
<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.code && !detectionAuthFailed && <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>
@@ -3061,7 +3128,7 @@ export function ProviderConnectionDialog({
loading={test[activeTab].status === 'testing'}
type="button"
onClick={() => void handleTest()}
- disabled={test[activeTab].status === 'testing'}
+ disabled={Object.values(test).some(value => value.status === 'testing')}
>
<Plug size={13} />
{t('settings.providers.custom.test.button')}
@@ -3092,9 +3159,33 @@ export function ProviderConnectionDialog({
)}
{!mediaOnly && test[activeTab].status === 'fail' && (
<span className="text-12 text-[var(--error-fg)]">
- {t(`providerError.${test[activeTab].code ?? 'UNKNOWN'}`)}
+ {test[activeTab].decision === 'inconclusive'
+ ? t('settings.providers.custom.test.inconclusive')
+ : test[activeTab].decision === 'next'
+ ? t('settings.providers.custom.test.exhausted')
+ : t(`providerError.${test[activeTab].code ?? 'UNKNOWN'}`)}
</span>
)}
+ {!mediaOnly && test[activeTab].status === 'testing' && (
+ <span role="status" className="text-12 text-[var(--text-secondary)]">{t('settings.providers.custom.test.testing')}</span>
+ )}
+ {!mediaOnly && test[activeTab].status === 'testing' && connectionTestRef.current && (
+ <Button variant="secondary" size="sm" compact type="button" onClick={() => {
+ cancelConnectionTest();
+ setTest(previous => ({ ...previous, [activeTab]: IDLE_TEST }));
+ }}>{t('settings.providers.custom.test.stop')}</Button>
+ )}
+ {!mediaOnly && simpleAdding && (
+ <span className="w-full text-12 text-[var(--text-secondary)]">{t('settings.providers.custom.test.costHint')}</span>
+ )}
+ {!mediaOnly && test[activeTab].status === 'fail' && Boolean(test[activeTab].attempts?.length) && (
+ <details className="w-full text-12 text-[var(--text-secondary)]">
+ <summary>{t('settings.providers.custom.test.details')}</summary>
+ <ul>{test[activeTab].attempts?.map(attempt => <li key={attempt.wireProtocol}>
+ {attempt.wireProtocol}: {t('providerError.' + (attempt.code ?? 'UNKNOWN'))}
+ </li>)}</ul>
+ </details>
+ )}
{mediaOnly && (
<span className="w-full text-12 text-[var(--text-secondary)]">
{t('settings.providers.connection.mediaOnlyTestHint')}
@@ -3124,6 +3215,7 @@ export function ProviderConnectionDialog({
variant={simpleAdding ? 'cta' : 'primary'}
size="lg"
loading={saving}
+ disabled={Object.values(test).some(value => value.status === 'testing')}
onClick={() => void handleSave()}
palette={simpleAdding ? 'default' : 'confirmation'}
className="min-w-[96px]"
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx
index 9eb50cfc33..f72ae18629 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx
@@ -3,7 +3,7 @@ import { useRef, useState } from 'react';
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
-import { buildUserProvider, type CustomProviderConfig, type ProviderPreset, type ModelRegistry } from '@cindy/model-providers';
+import { BUNDLED_CATALOG, buildUserProvider, type CustomProviderConfig, type ProviderPreset, type ModelRegistry } from '@cindy/model-providers';
import { customProviderModelConfigFromCatalogModel } from '@/lib/customProviders';
import { ProviderConnectionDialog } from '../ProviderConnectionDialog';
@@ -2087,7 +2087,7 @@ it('main provider form contains Tab and blocks dismissal only during the actual
describe('new-connection identification', () => {
afterEach(() => { cleanup(); vi.useRealTimers(); });
const preset = { id: 'deepseek', name: 'DeepSeek', runtimes: { pi: { baseUrl: 'https://api.deepseek.com', wireProtocol: 'openai-chat' as const, models: [] } } };
- async function openIdentification(available: ProviderPreset = preset) {
+ async function openIdentification(available: ProviderPreset = preset, url = 'https://api.deepseek.com', apiKey = 'fake-key') {
vi.useFakeTimers();
const fetchProviderModels = vi.fn(async () => ({ ok: true, models: [{ id: 'private-model', name: 'Model' }] }));
Object.assign(window.electronAPI.maker, {
@@ -2097,11 +2097,129 @@ describe('new-connection identification', () => {
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' } });
+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: url } });
+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder'), { target: { value: apiKey } });
await act(async () => { await vi.advanceTimersByTimeAsync(400); });
return { onDetected, fetchProviderModels };
}
+ it.each([
+ ['http://127.0.0.1:1234/v1', '', 'none'],
+ ['http://localhost:1234/v1', '', 'none'],
+ ['http://[::1]:1234/v1', '', 'none'],
+ ['https://remote.example/v1', '', 'apiKey'],
+ ['https://localhost.example/v1', '', 'apiKey'],
+ ['http://127.0.0.1:1234/v1', 'fake-key', 'apiKey'],
+ ])('keeps discovery, testing and saving on the same add-form auth: %s / %s', async (url, key, method) => {
+ await openIdentification(preset, url, key);
+ const testConnection = vi.fn(async () => ({ ok: true, latencyMs: 1 }));
+ window.electronAPI.maker.testProviderConnection = testConnection;
+ expect(window.electronAPI.maker.detectProvider).toHaveBeenCalledWith(expect.objectContaining({ authMethod: method }));
+ // Local inference must never hide the input needed to add authentication later.
+ expect(screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));
+ await act(async () => {});
+ expect(testConnection).toHaveBeenCalledWith(expect.objectContaining({ spec: expect.objectContaining({ authMethod: method, apiKey: key || null }) }));
+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.namePlaceholder'), { target: { value: 'Auth regression' } });
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.connection.saveProvider' }));
+ await act(async () => {});
+ const [config, keys] = customProviderMocks.createCustomProvider.mock.calls[0];
+ expect(config.auth?.method ?? 'apiKey').toBe(method);
+ expect(keys).toEqual(key ? { pi: key } : {});
+ });
+ it('invalidates inferred no-auth when key or destination changes', async () => {
+ await openIdentification(preset, 'http://127.0.0.1:1234/v1', '');
+ const testConnection = vi.fn(async () => ({ ok: true, latencyMs: 1 }));
+ window.electronAPI.maker.testProviderConnection = testConnection;
+ const key = screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder');
+ for (const [value, method] of [['fake-key', 'apiKey'], ['', 'none']] as const) {
+ fireEvent.change(key, { target: { value } });
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));
+ await act(async () => {});
+ expect(testConnection).toHaveBeenLastCalledWith(expect.objectContaining({ spec: expect.objectContaining({ authMethod: method }) }));
+ }
+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: 'https://remote.example/v1' } });
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));
+ await act(async () => {});
+ expect(testConnection).toHaveBeenLastCalledWith(expect.objectContaining({ spec: expect.objectContaining({ authMethod: 'apiKey' }) }));
+ });
+ it.each(['remote-engine', 'independent-key', 'remote-directory'])('does not infer global no-auth across a %s draft', async variant => {
+ vi.useFakeTimers();
+ const local = { baseUrl: 'http://127.0.0.1:1234/v1', models: [{ id: 'local-model', name: 'Local' }] };
+ const own = { ...local, baseUrl: variant === 'remote-engine' ? 'https://remote.example/v1' : local.baseUrl,
+ ...(variant === 'remote-directory' ? { modelsUrl: 'https://remote.example/v1/models' } : {}) };
+ const testConnection = vi.fn(async () => ({ ok: true, latencyMs: 1 }));
+ Object.assign(window.electronAPI.maker, { listProviderPresets: vi.fn(async () => ({ presets: [] })), testProviderConnection: testConnection });
+ render(<ProviderConnectionDialog onDetected={vi.fn()} onClose={vi.fn()} onSaved={vi.fn()} draft={{
+ preset, agent: 'pi', apiKey: '', keys: { pi: '', codex: variant === 'independent-key' ? 'own-key' : '' },
+ config: { id: 'draft', name: 'Local with independent runtime', runtimes: { pi: local, codex: own } },
+ }} />);
+ await act(async () => {});
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));
+ await act(async () => {});
+ expect(testConnection).toHaveBeenCalledWith(expect.objectContaining({ spec: expect.objectContaining({ authMethod: 'apiKey' }) }));
+ });
+ it('preserves header-only credentials on a local new connection', async () => {
+ await openIdentification(preset, 'http://127.0.0.1:1234/v1', '');
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.fields.addHeader' }));
+ // Header input labels are shared by the existing form; use its placeholders.
+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.headerNamePlaceholder'), { target: { value: 'Authorization' } });
+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.headerValuePlaceholder'), { target: { value: 'Bearer fake-header' } });
+ const testConnection = vi.fn(async () => ({ ok: true, latencyMs: 1 }));
+ window.electronAPI.maker.testProviderConnection = testConnection;
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));
+ await act(async () => {});
+ expect(testConnection).toHaveBeenCalledWith(expect.objectContaining({ spec: expect.objectContaining({ authMethod: 'apiKey', headers: { Authorization: 'Bearer fake-header' } }) }));
+ });
+ // Empty-key GUI regressions: address identification must survive a 401 from
+ // model discovery and reach the wizard without saving an account. Unit.
+ it.each([
+ ['https://ark.cn-beijing.volces.com/api/v3', 'volcengine-api'],
+ ['https://api.siliconflow.cn/v1', 'siliconflow-cn'],
+ ['https://api.siliconflow.com/v1', 'siliconflow-global'],
+ ['https://api.mistral.ai/v1', 'mistral'],
+ ['https://api.together.xyz/v1', 'together'],
+ ['https://api.fireworks.ai/inference/v1', 'fireworks'],
+ ])('hands off %s with an empty key even when discovery requires authentication', async (url, id) => {
+ const available = BUNDLED_CATALOG.presets!.find(p => p.id === id)!;
+ const { onDetected, fetchProviderModels } = await openIdentification(available, '', '');
+ fetchProviderModels.mockResolvedValue({ ok: false, code: 'AUTH_INVALID' } as any);
+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: url } });
+ await act(async () => { await vi.advanceTimersByTimeAsync(1600); });
+ expect(onDetected).toHaveBeenCalledOnce();
+ expect(onDetected.mock.calls[0][0]).toMatchObject({ apiKey: '', preset: { id }, agent: 'pi' });
+ expect(fetchProviderModels).toHaveBeenCalledWith(expect.objectContaining({ apiKey: null }));
+ expect(customProviderMocks.createCustomProvider).not.toHaveBeenCalled();
+ });
+ it('shows missing-key guidance instead of an expired-key error, and clears stale authentication feedback on edit', async () => {
+ await openIdentification();
+ Object.assign(window.electronAPI.maker, {
+ detectProvider: vi.fn(async () => ({ candidates: [], reason: 'insufficient_evidence', catalog: { ok: false, code: 'AUTH_INVALID' } })),
+ });
+ const key = screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder');
+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: 'https://relay.example/v1' } });
+ fireEvent.change(key, { target: { value: '' } });
+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });
+ expect(screen.getByText('settings.providers.detection.keyRequired')).toBeTruthy();
+ expect(key.getAttribute('aria-invalid')).not.toBe('true');
+ expect(screen.queryByText('providerError.AUTH_INVALID')).toBeNull();
+ expect(screen.queryByText('settings.providers.detection.custom')).toBeNull();
+ fireEvent.change(key, { target: { value: 'rejected-test-key' } });
+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });
+ expect(screen.getByText('settings.providers.detection.authRejected')).toBeTruthy();
+ expect(key.getAttribute('aria-invalid')).toBe('true');
+ fireEvent.change(key, { target: { value: 'replacement-test-key' } });
+ expect(screen.queryByText('settings.providers.detection.authRejected')).toBeNull();
+ expect(key.getAttribute('aria-invalid')).not.toBe('true');
+ });
+ it('still accepts a successful directory response from a service with an empty key', async () => {
+ await openIdentification();
+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: 'http://localhost:1234/v1' } });
+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder'), { target: { value: '' } });
+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });
+ expect(window.electronAPI.maker.detectProvider).toHaveBeenCalledWith(expect.objectContaining({ baseUrl: 'http://localhost:1234/v1', apiKey: null }));
+ expect(screen.queryByText('settings.providers.detection.keyRequired')).toBeNull();
+ expect(screen.getByText('settings.providers.detection.custom')).toBeTruthy();
+ });
it('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();
@@ -2113,7 +2231,7 @@ describe('new-connection identification', () => {
expect(fetchProviderModels).toHaveBeenCalledOnce();
expect(customProviderMocks.createCustomProvider).not.toHaveBeenCalled();
});
- it('uses the HTML add layout and saves the shared connection with each engine default', async () => {
+ it('uses the HTML add layout and saves only Pi for the shared custom connection', async () => {
await openIdentification();
expect(screen.queryByRole('tablist')).toBeNull();
expect(screen.queryByText('settings.providers.custom.authMode.label')).toBeNull();
@@ -2131,11 +2249,59 @@ describe('new-connection identification', () => {
await act(async () => {});
expect(customProviderMocks.createCustomProvider).toHaveBeenCalledOnce();
const [config, keys] = customProviderMocks.createCustomProvider.mock.calls[0];
- for (const [agent, protocol] of [['claude-code', 'anthropic-messages'], ['codex', 'openai-responses'], ['pi', 'openai-chat']]) {
- expect(config.runtimes[agent]).toMatchObject({ baseUrl: 'https://api.deepseek.com', models: [{ id: 'my-model' }] });
- expect(config.runtimes[agent].wireProtocol).toBe(agent === 'pi' ? protocol : undefined);
- expect(keys[agent]).toBe('fake-key');
+ expect(Object.keys(config.runtimes)).toEqual(['pi']);
+ expect(config.runtimes.pi).toMatchObject({ baseUrl: 'https://api.deepseek.com', wireProtocol: 'openai-chat', models: [{ id: 'my-model' }] });
+ expect(keys).toEqual({ pi: 'fake-key' });
+ });
+ // New one-click connection contract: real form actions must preserve the successful
+ // route through Save; changed inputs must invalidate an in-flight paid probe (unit tier).
+ it('applies an automatically verified protocol and saves the same Pi model route', async () => {
+ await openIdentification();
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.detection.keepCustom' }));
+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: 'https://unknown.example/team/v1' } });
+ window.electronAPI.maker.testProviderConnection = vi.fn(async () => ({ ok: true, latencyMs: 3, decision: 'success' as const,
+ selected: { baseUrl: 'https://unknown.example/team', wireProtocol: 'anthropic-messages' as const } }));
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));
+ await act(async () => {});
+ expect(window.electronAPI.maker.testProviderConnection).toHaveBeenCalledWith(expect.objectContaining({
+ requestId: expect.any(String), strategy: 'auto', kind: 'adhoc',
+ spec: expect.objectContaining({ agent: 'pi', baseUrl: 'https://unknown.example/team/v1', modelId: 'private-model' }),
+ }));
+ expect(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder')).toHaveProperty('value', 'https://unknown.example/team');
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));
+ await act(async () => {});
+ expect(window.electronAPI.maker.testProviderConnection).toHaveBeenLastCalledWith(expect.objectContaining({
+ strategy: 'auto', spec: expect.objectContaining({ wireProtocol: 'anthropic-messages', baseUrl: 'https://unknown.example/team' }),
+ }));
+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.namePlaceholder'), { target: { value: 'Verified custom' } });
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.connection.saveProvider' }));
+ await act(async () => {});
+ const [config] = customProviderMocks.createCustomProvider.mock.calls[0];
+ expect(Object.keys(config.runtimes)).toEqual(['pi']);
+ expect(config.runtimes.pi).toMatchObject({ baseUrl: 'https://unknown.example/team', wireProtocol: 'anthropic-messages',
+ models: [{ id: 'private-model', api: 'anthropic-messages', route: { baseUrl: 'https://unknown.example/team', wireProtocol: 'anthropic-messages' } }] });
+ });
+ it.each(['key', 'address', 'stop'] as const)('cancels on %s and ignores a late successful protocol result', async change => {
+ await openIdentification();
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.detection.keepCustom' }));
+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: 'https://unknown.example/v1' } });
+ let finish!: (value: unknown) => void;
+ window.electronAPI.maker.testProviderConnection = vi.fn().mockImplementation(input => input.kind === 'cancel'
+ ? Promise.resolve({ ok: false, latencyMs: 0, decision: 'cancelled' }) : new Promise(resolve => { finish = resolve; }));
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));
+ expect(window.electronAPI.maker.testProviderConnection).toHaveBeenCalledOnce();
+ if (change === 'key') {
+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.apiKeyPlaceholder'), { target: { value: 'different-fake-key' } });
+ } else if (change === 'address') {
+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: 'https://new.example/v1' } });
+ } else {
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.test.stop' }));
}
+ expect(window.electronAPI.maker.testProviderConnection).toHaveBeenLastCalledWith(expect.objectContaining({ kind: 'cancel' }));
+ await act(async () => { finish({ ok: true, latencyMs: 1, selected: { baseUrl: 'https://stale.example', wireProtocol: 'openai-responses' } }); });
+ expect(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder')).toHaveProperty('value', change === 'address' ? 'https://new.example/v1' : 'https://unknown.example/v1');
+ expect(screen.queryByText('settings.providers.custom.test.ok')).toBeNull();
});
it('binds each supported engine to the identified provider instead of copying the active protocol', async () => {
const available: ProviderPreset = { ...preset, runtimes: {
@@ -2339,6 +2505,31 @@ describe('new-connection identification', () => {
expect(onDetected).not.toHaveBeenCalled();
expect(fetchProviderModels).toHaveBeenCalledOnce();
});
+ it.each([
+ [[], 'insufficient_evidence'],
+ [['sub2api', 'litellm'], 'conflict'],
+ [['missing-preset'], 'matched'],
+ ])('stays custom for unusable deployment candidates: %s', async (candidates, reason) => {
+ const { onDetected } = await openIdentification();
+ window.electronAPI.maker.detectProvider = vi.fn(async () => ({ candidates, reason, catalog: { ok: true, models: [] } })) as any;
+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.baseUrlPlaceholder'), { target: { value: 'https://unknown.example/team/v1' } });
+ await act(async () => { await vi.advanceTimersByTimeAsync(2000); });
+ expect(onDetected).not.toHaveBeenCalled();
+ expect(screen.queryByRole('button', { name: 'settings.providers.detection.configure' })).toBeNull();
+ });
+ it('does not navigate after unmount with a scheduled official handoff', async () => {
+ const { onDetected } = await openIdentification();
+ cleanup();
+ await act(async () => { await vi.advanceTimersByTimeAsync(2000); });
+ expect(onDetected).not.toHaveBeenCalled();
+ });
+ it('uses the current name when the user edits it during the jump delay', async () => {
+ const { onDetected } = await openIdentification();
+ fireEvent.change(screen.getByPlaceholderText('settings.providers.custom.fields.namePlaceholder'), { target: { value: 'Latest name' } });
+ await act(async () => { await vi.advanceTimersByTimeAsync(1200); });
+ expect(onDetected).toHaveBeenCalledOnce();
+ expect(onDetected.mock.calls[0][0].config.name).toBe('Latest name');
+ });
it('ignores a late response after the connection changes', async () => {
const { onDetected, fetchProviderModels } = await openIdentification();
let finish!: (value: { ok: true; models: { id: string; name: string }[] }) => void;
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 0f07b8b650..5c8280d5e3 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -934,8 +934,8 @@
"SSH_HOST_KEY_MISMATCH": "SSH Host Key Changed"
},
"providerError": {
- "AUTH_INVALID": "Invalid or expired API key (401). Check the key and try again",
- "AUTH_FORBIDDEN": "Key is valid but access is denied (403). Check plan or model permissions",
+ "AUTH_INVALID": "Authentication failed for this interface. Check the address, key, and authentication method.",
+ "AUTH_FORBIDDEN": "This interface denied access. Check your plan, model, or regional permissions.",
"RATE_LIMITED": "Rate limited (429). Try again later",
"QUOTA_EXCEEDED": "Quota or balance exhausted. Check your provider account",
"MODEL_NOT_FOUND": "Model not found or not accessible. Check the model ID",
@@ -3164,8 +3164,14 @@
"placeholder": "Choose a template…"
},
"test": {
+ "testing": "Testing the connection and compatible interfaces…",
+ "inconclusive": "Connection could not be confirmed. Check the address or network before retrying; the previous request may have run.",
+ "exhausted": "All candidate interfaces were tried. No working connection was found.",
+ "costHint": "Testing sends short generation requests and may incur a small charge.",
+ "details": "View attempts",
"button": "Test connection",
"testing": "Testing…",
+ "stop": "Stop test",
"ok": "Connected ({{ms}} ms)",
"needFields": "Fill in the base URL and at least one model ID first",
"unsupportedProtocol": "This model protocol is not supported by connection testing"
@@ -3774,6 +3780,8 @@
},
"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": {
+ "keyRequired": "Enter your API key to continue.",
+ "authRejected": "Authentication failed. Check the URL and API key; we’ll retry when you update them.",
"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}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 8d01c6495e..e8b6941094 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -922,8 +922,8 @@
"SSH_HOST_KEY_MISMATCH": "SSH ホスト鍵が変更されました"
},
"providerError": {
- "AUTH_INVALID": "API キーが無効か期限切れです(401)。キーを確認して再試行してください",
- "AUTH_FORBIDDEN": "キーは有効ですがアクセス権がありません(403)。プランやモデルの権限を確認してください",
+ "AUTH_INVALID": "このインターフェースで認証に失敗しました。アドレス、キー、認証方式を確認してください。",
+ "AUTH_FORBIDDEN": "このインターフェースへのアクセスが拒否されました。プラン、モデル、地域のアクセス権を確認してください。",
"RATE_LIMITED": "レート制限中です(429)。しばらくしてから再試行してください",
"QUOTA_EXCEEDED": "クォータまたは残高が不足しています。プロバイダーのアカウントを確認してください",
"MODEL_NOT_FOUND": "モデルが存在しないか利用権限がありません。モデル ID を確認してください",
@@ -3135,8 +3135,14 @@
"placeholder": "テンプレートを選択…"
},
"test": {
+ "testing": "接続と互換インターフェースを確認中…",
+ "inconclusive": "接続を確認できませんでした。アドレスやネットワークを確認してから再試行してください。前のリクエストが実行済みの可能性があります。",
+ "exhausted": "すべての候補を試しましたが、接続できませんでした。",
+ "costHint": "テストでは短い生成リクエストを送信し、少額の料金が発生する場合があります。",
+ "details": "試行結果を表示",
"button": "接続テスト",
"testing": "テスト中…",
+ "stop": "テストを停止",
"ok": "接続に成功しました({{ms}}ms)",
"needFields": "先にベース URL と少なくとも 1 つのモデル ID を入力してください",
"unsupportedProtocol": "接続テストはこのモデルプロトコルに対応していません"
@@ -3743,6 +3749,8 @@
},
"claudeAccountRetired": "Cindy では、この旧式の Claude 接続を使ったサブスクリプションへのログインに対応していません。Claude アカウントとサブスクリプションには影響ありません。「Claude Code でログイン」から接続してください。",
"detection": {
+ "keyRequired": "API キーを入力して続けてください。",
+ "authRejected": "認証できませんでした。URL と API キーを確認してください。変更すると自動的に再試行します。",
"hint": "URL と API キーを入力するとプロバイダーを識別します。保存後、接続の編集でプロトコルを変更できます。",
"pending": "プロバイダーを識別中…",
"matched": "{{name}} として識別されました",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index f9cac15b64..cda24c8d18 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -922,8 +922,8 @@
"SSH_HOST_KEY_MISMATCH": "SSH 호스트 키가 변경됨"
},
"providerError": {
- "AUTH_INVALID": "API 키가 유효하지 않거나 만료되었습니다(401). 키를 확인한 후 다시 시도하세요",
- "AUTH_FORBIDDEN": "키는 유효하지만 접근 권한이 없습니다(403). 요금제 또는 모델 권한을 확인하세요",
+ "AUTH_INVALID": "이 인터페이스에서 인증에 실패했습니다. 주소, 키 및 인증 방식을 확인하세요.",
+ "AUTH_FORBIDDEN": "이 인터페이스가 접근을 거부했습니다. 요금제, 모델 또는 지역 권한을 확인하세요.",
"RATE_LIMITED": "요청이 제한되었습니다(429). 잠시 후 다시 시도하세요",
"QUOTA_EXCEEDED": "할당량 또는 잔액이 부족합니다. 제공자 계정을 확인하세요",
"MODEL_NOT_FOUND": "모델이 존재하지 않거나 사용 권한이 없습니다. 모델 ID를 확인하세요",
@@ -3135,8 +3135,14 @@
"placeholder": "템플릿 선택…"
},
"test": {
+ "testing": "연결 및 호환 인터페이스 확인 중…",
+ "inconclusive": "연결을 확인하지 못했습니다. 주소나 네트워크를 확인한 후 다시 시도하세요. 이전 요청이 실행되었을 수 있습니다.",
+ "exhausted": "모든 후보 인터페이스를 시도했지만 연결하지 못했습니다.",
+ "costHint": "테스트는 짧은 생성 요청을 보내며 소액의 요금이 발생할 수 있습니다.",
+ "details": "시도 결과 보기",
"button": "연결 테스트",
"testing": "테스트 중…",
+ "stop": "테스트 중지",
"ok": "연결 성공 ({{ms}}ms)",
"needFields": "먼저 기본 URL과 모델 ID를 하나 이상 입력하세요",
"unsupportedProtocol": "연결 테스트는 이 모델 프로토콜을 지원하지 않습니다"
@@ -3743,6 +3749,8 @@
},
"claudeAccountRetired": "Cindy에서는 이 이전 Claude 연결 방식으로 구독에 로그인할 수 없습니다. Claude 계정과 구독에는 영향이 없습니다. ‘Claude Code로 로그인’을 사용해 구독을 연결하세요.",
"detection": {
+ "keyRequired": "API 키를 입력해 계속하세요.",
+ "authRejected": "인증하지 못했습니다. URL과 API 키를 확인하세요. 수정하면 자동으로 다시 시도합니다.",
"hint": "URL과 API 키를 입력하면 제공자를 식별합니다. 저장한 연결을 편집하여 프로토콜을 변경할 수 있습니다.",
"pending": "제공자 식별 중…",
"matched": "{{name}}(으)로 식별됨",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 10ca045d16..9f7e0e8d98 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -922,8 +922,8 @@
"SSH_HOST_KEY_MISMATCH": "SSH 主机密钥已变化"
},
"providerError": {
- "AUTH_INVALID": "API 密钥无效或已过期(401),请检查密钥后重试",
- "AUTH_FORBIDDEN": "密钥有效但无权访问(403),请检查套餐或模型权限",
+ "AUTH_INVALID": "当前接口认证失败,请检查地址、密钥和认证方式",
+ "AUTH_FORBIDDEN": "当前接口拒绝访问,请检查套餐、模型或地区权限",
"RATE_LIMITED": "请求被限流(429),请稍后重试",
"QUOTA_EXCEEDED": "配额或余额不足,请检查供应商账户",
"MODEL_NOT_FOUND": "模型不存在或无权使用,请检查模型 ID",
@@ -3135,8 +3135,14 @@
"placeholder": "选择一个模板…"
},
"test": {
+ "testing": "正在测试连接,并按需尝试兼容接口…",
+ "inconclusive": "暂时无法确认连接。请检查地址或网络后重试;上一条请求可能已执行。",
+ "exhausted": "已尝试所有候选接口,暂未找到可用连接。",
+ "costHint": "测试会发送简短生成请求,可能产生少量费用。",
+ "details": "查看尝试结果",
"button": "测试连接",
"testing": "测试中…",
+ "stop": "停止测试",
"ok": "连接成功({{ms}}ms)",
"needFields": "请先填写基础 URL 和至少一个模型 ID",
"unsupportedProtocol": "测试连接暂不支持该模型协议"
@@ -3743,6 +3749,8 @@
},
"claudeAccountRetired": "Cindy 已不再支持通过这条旧版 Claude 连接登录订阅,不影响你的 Claude 账号和订阅。请改用「使用 Claude Code 登录」连接订阅",
"detection": {
+ "keyRequired": "填写 API 密钥后继续。",
+ "authRejected": "认证未通过,请检查地址和 API 密钥,修改后会自动重试。",
"hint": "填写地址和 API 密钥后自动识别供应商。保存后可在编辑连接中调整协议。",
"pending": "正在识别供应商…",
"matched": "已识别为 {{name}}",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index db9dff7d3b..76c6535301 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -922,8 +922,8 @@
"SSH_HOST_KEY_MISMATCH": "SSH 主機金鑰已變更"
},
"providerError": {
- "AUTH_INVALID": "API 金鑰無效或已過期(401),請檢查金鑰後重試",
- "AUTH_FORBIDDEN": "金鑰有效但無權訪問(403),請檢查套餐或模型權限",
+ "AUTH_INVALID": "目前介面驗證失敗,請檢查位址、金鑰和驗證方式",
+ "AUTH_FORBIDDEN": "目前介面拒絕存取,請檢查方案、模型或地區權限",
"RATE_LIMITED": "請求被限流(429),請稍後重試",
"QUOTA_EXCEEDED": "配額或餘額不足,請檢查供應商帳戶",
"MODEL_NOT_FOUND": "模型不存在或無權使用,請檢查模型 ID",
@@ -3135,8 +3135,14 @@
"placeholder": "選擇一個模板…"
},
"test": {
+ "testing": "正在測試連線,並視需要嘗試相容介面…",
+ "inconclusive": "暫時無法確認連線。請檢查位址或網路後重試;上一個請求可能已執行。",
+ "exhausted": "已嘗試所有候選介面,暫未找到可用連線。",
+ "costHint": "測試會傳送簡短生成請求,可能產生少量費用。",
+ "details": "查看嘗試結果",
"button": "測試連線",
"testing": "測試中…",
+ "stop": "停止測試",
"ok": "連線成功({{ms}}ms)",
"needFields": "請先填寫基礎 URL 和至少一個模型 ID",
"unsupportedProtocol": "測試連線暫不支援此模型協定"
@@ -3743,6 +3749,8 @@
},
"claudeAccountRetired": "Cindy 已不再支援透過這筆舊版 Claude 連線登入訂閱,不影響你的 Claude 帳號和訂閱。請改用「使用 Claude Code 登入」連線訂閱",
"detection": {
+ "keyRequired": "填寫 API 金鑰後繼續。",
+ "authRejected": "驗證未通過,請檢查位址和 API 金鑰,修改後會自動重試。",
"hint": "填寫網址和 API 金鑰後自動識別供應商。儲存後可在編輯連線中調整協定。",
"pending": "正在識別供應商…",
"matched": "已識別為 {{name}}",
diff --git a/apps/desktop/src/renderer/lib/customProviderId.test.ts b/apps/desktop/src/renderer/lib/customProviderId.test.ts
index aeb7903484..5a4482d006 100644
--- a/apps/desktop/src/renderer/lib/customProviderId.test.ts
+++ b/apps/desktop/src/renderer/lib/customProviderId.test.ts
@@ -15,4 +15,38 @@ describe('uniqueCustomProviderId', () => {
const second = uniqueCustomProviderId('测试网关', new Set([first]));
expect(second).toBe(`${first}-2`);
});
+
+ it.each([39, 40, 41, 60])('bounds a %i-character slug to the store limit', (length) => {
+ expect(uniqueCustomProviderId('a'.repeat(length), new Set())).toBe(
+ 'a'.repeat(Math.min(length, 40)),
+ );
+ });
+
+ it('preserves existing short slug behavior', () => {
+ expect(uniqueCustomProviderId(' My AI Provider! ', new Set())).toBe('my-ai-provider');
+ expect(uniqueCustomProviderId('My AI Provider', new Set(['my-ai-provider']))).toBe(
+ 'my-ai-provider-2',
+ );
+ });
+
+ it('detects collisions after truncation, including different long names', () => {
+ const first = uniqueCustomProviderId('a'.repeat(40) + ' first', new Set());
+ const existing = new Set([first]);
+ expect(uniqueCustomProviderId('a'.repeat(40) + ' second', existing)).toBe(
+ 'a'.repeat(38) + '-2',
+ );
+ expect([...existing]).toEqual([first]);
+ });
+
+ it('reserves room for one-, two- and three-digit collision suffixes', () => {
+ const existing = new Set<string>();
+ for (let i = 1; i <= 101; i += 1) {
+ const id = uniqueCustomProviderId('a'.repeat(60), existing);
+ const suffix = i === 1 ? '' : `-${i}`;
+ expect(id).toBe('a'.repeat(40 - suffix.length) + suffix);
+ expect(existing.has(id)).toBe(false);
+ expect(id).toHaveLength(40);
+ existing.add(id);
+ }
+ });
});
diff --git a/apps/desktop/src/renderer/lib/customProviderId.ts b/apps/desktop/src/renderer/lib/customProviderId.ts
index d560fd353e..5401a3ad86 100644
--- a/apps/desktop/src/renderer/lib/customProviderId.ts
+++ b/apps/desktop/src/renderer/lib/customProviderId.ts
@@ -17,10 +17,13 @@ function slugify(name: string): string {
}
export function uniqueCustomProviderId(name: string, existing: ReadonlySet<string>): string {
- const base = slugify(name);
+ // Keep generated IDs within the custom-provider store’s 40-character limit.
+ const maxLength = 40;
+ const base = slugify(name).slice(0, maxLength);
if (!existing.has(base)) return base;
for (let i = 2; ; i += 1) {
- const candidate = `${base}-${i}`;
+ const suffix = `-${i}`;
+ const candidate = `${base.slice(0, maxLength - suffix.length)}${suffix}`;
if (!existing.has(candidate)) return candidate;
}
}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 8ef48d737a..271453ff17 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -5634,30 +5634,8 @@ interface ElectronAPI {
}>;
/** 供应商「测试连接」—— 与真实会话同路由口径的最小探测请求(结构化结果,code 走 providerError.* i18n)。 */
testProviderConnection: (
- input:
- | { kind: 'saved'; providerId: string; agent: 'claude-code' | 'codex' | 'pi' }
- | {
- kind: 'adhoc';
- spec: {
- agent: 'claude-code' | 'codex' | 'pi';
- baseUrl: string;
- modelId: string;
- authMethod: 'apiKey' | 'oauth' | 'none';
- wireProtocol?: import('@cindy/model-providers').ProviderWireProtocol;
- api?: import('@cindy/model-providers').PiModelApi;
- catalogPresetId?: string;
- requestPath?: string;
- apiKey?: string | null;
- headers?: Record<string, string>;
- };
- },
- ) => Promise<{
- ok: boolean;
- code?: import('../shared/providerErrors').ProviderErrorCode;
- status?: number;
- latencyMs: number;
- detail?: string;
- }>;
+ input: import('../shared/providerConnectionTest').ProviderConnectionTestRequest,
+ ) => Promise<import('../shared/providerConnectionTest').ProviderConnectionTestResult>;
/** 供应商「获取模型列表」—— 表单值透传,结构化结果(code 走 providerError.* i18n)。 */
detectProvider?: (input: ({ requestId: string; cancel: true } | {
requestId: string; agent: 'claude-code' | 'codex' | 'pi'; baseUrl: string;
diff --git a/apps/desktop/src/shared/providerConnectionTest.ts b/apps/desktop/src/shared/providerConnectionTest.ts
new file mode 100644
index 0000000000..3e896634ee
--- /dev/null
+++ b/apps/desktop/src/shared/providerConnectionTest.ts
@@ -0,0 +1,37 @@
+import type { AgentKind, PiModelApi, ProviderWireProtocol, ProviderProtocolCandidate } from '@cindy/model-providers';
+import type { ProviderErrorCode } from './providerErrors';
+
+/** Public probe contract: saved secrets are resolved exclusively in Main. */
+export interface ProviderConnectionProbeSpec {
+ agent: AgentKind;
+ baseUrl: string;
+ modelId: string;
+ authMethod?: 'apiKey' | 'oauth' | 'none';
+ wireProtocol?: ProviderWireProtocol;
+ api?: PiModelApi;
+ catalogPresetId?: string;
+ requestPath?: string;
+ apiKey?: string | null;
+ headers?: Record<string, string>;
+}
+export type ProviderConnectionTestInput = (
+ | { kind: 'saved'; providerId: string; agent: AgentKind }
+ | { kind: 'adhoc'; spec: ProviderConnectionProbeSpec }
+) & { requestId?: string; strategy?: 'auto' };
+export type ProviderConnectionTestRequest = ProviderConnectionTestInput | { kind: 'cancel'; requestId: string };
+export type ProtocolProbeDecision = 'success' | 'next' | 'blocked' | 'inconclusive' | 'cancelled';
+export interface ProtocolProbeAttempt extends ProviderProtocolCandidate {
+ code?: ProviderErrorCode;
+ status?: number;
+ decision: ProtocolProbeDecision;
+}
+export interface ProviderConnectionTestResult {
+ ok: boolean;
+ code?: ProviderErrorCode;
+ status?: number;
+ latencyMs: number;
+ detail?: string;
+ decision?: ProtocolProbeDecision;
+ selected?: ProviderProtocolCandidate;
+ attempts?: ProtocolProbeAttempt[];
+}
diff --git a/docs/dev-rules/provider-interface-audit.md b/docs/dev-rules/provider-interface-audit.md
index c3f9aa9cbb..292bd3ec38 100644
--- a/docs/dev-rules/provider-interface-audit.md
+++ b/docs/dev-rules/provider-interface-audit.md
@@ -44,6 +44,27 @@ OpenCode 官方文档表本次取得 Zen 69 条、Go 28 条声明,与实时模
- 底层 Bedrock/Vertex/Mistral SDK、认证和路由不作为新增 UI 语言;模型管理保持四种公开语言。
- 供应商升级文档/接口时应更新此记录和精确契约测试。Pi catalog 同步不会覆盖官方逐模型纠正层。
+## 官方地址识别补齐(2026-10-21)
+
+`providerDetection.ts` 按精确地址匹配,不对任意供应商统一剥除 `/v1`、改写域名或
+放宽业务路径。混合协议连接同时使用已有 `providerInterfaceDefaultRoute` 和模型独立
+路由识别入口。Mistral 的 `/v1` 输入对应 SDK 使用的根地址,Together 的历史 `.xyz`
+入口对应现有 `.ai/v1` 预设;别名只在预设仍声明原官方地址时启用。
+
+| 入口 | 官方依据 | 客户端处理 |
+| --- | --- | --- |
+| 火山普通 API | [官方 SDK 默认地址](https://github.com/volcengine/volcengine-python-sdk/blob/master/volcenginesdkarkruntime/_constants.py) | 独立于 Coding/Agent Plan,精确 `/api/v3`;使用 Chat 与动态模型发现 |
+| 硅基流动中国大陆 | [官方快速开始](https://docs.siliconflow.cn/cn/userguide/quickstart) | 独立 `.cn/v1` 预设与密钥入口 |
+| SiliconFlow | [官方快速开始](https://docs.siliconflow.com/en/userguide/quickstart) | 独立 `.com/v1` 预设与密钥入口 |
+| Mistral | [官方 API](https://docs.mistral.ai/api/) | 精确 `/v1` 别名,不改变既有 SDK adapter |
+| Together | [官方 SDK](https://github.com/togethercomputer/together-python) | 识别历史 `.xyz/v1`,使用现有 `.ai/v1` 运行配置 |
+| Fireworks | [官方协议说明](https://docs.fireworks.ai/tools-sdks/anthropic-compatibility) | 复用已有 `/inference` 与 `/inference/v1` 协议契约 |
+
+新增三个预设不静态推荐模型,需用账号密钥发现实际清单;识别与进入向导允许空密钥,
+不代表鉴权、模型列表或推理成功。本次仅修改客户端离线预设与识别规则,未修改或部署
+Server 正本。回归见 `providerDetection.test.ts` 与真实添加表单的
+`CustomProviderDialogAccessibility.test.tsx`。
+
## 全部预设
“保留”不代表本次完成云端验收;“待核实”不得转换成“不支持”。
@@ -180,3 +201,24 @@ OpenCode 官方文档表本次取得 Zen 69 条、Go 28 条声明,与实时模
- Fireworks 不按模型品牌删 Messages。中国大陆 MiniMax Responses 改用中国大陆官方来源,
原有别名主机的真实可用性仍单独标注;不把 Global 文档当作中国大陆部署证据。
- 本批仅使用虚拟凭证、本地模拟及公开文档读取,没有付费生成,也没有重启 DEV。
+
+
+## 自定义连接的一次点击协议验证
+
+- 新建且未绑定预设、未显式指定模型协议的自定义连接,在「测试连接」内按需串行尝试
+ Chat Completions、Responses、Anthropic Messages、Google Generative AI。已有预设与用户显式路由优先;
+ 不把供应商身份识别与生成协议验证混为一谈。默认简化添加页保存 Pi,保留独立草稿和编辑态的其他引擎。
+- 候选由同源、可持久化的 Pi base URL + wireProtocol 构成。明确完整接口后缀可优先,
+ 根地址采用各 SDK 标准根;保留部署路径,不扫描其它域名或任意目录,不接受带 userinfo/query/hash 的自动候选。
+ Pi 不支持的任意 requestPath 不能作为「只在测试中可用」的成功结果落库。
+- 协议请求默认复用 Pi 原生序列化/解析。Google SDK 不支持注入 fetch,探测使用同源的
+ streamGenerateContent HTTP 流验证,禁止重定向;基础生成通过不等于工具、图片或推理能力全部验证。
+- 只有明确、未进入生成阶段的协议/路由拒绝才尝试下一个。HTTP 状态码、未知字段、空流、
+ HTML 200、超时、5xx、断流均不能单独作为换协议依据。认证/额度/模型错误停止并给出对应提示。
+- 每候选最多一次生成请求,SDK retry=0,最多四候选,自动探测单次 8 秒、整轮 15 秒;明确指定单一路由的测试保留原时间预算。
+ 流式结果需同时有有效生成内容和合法结束;取消/超时不保证上游未执行,不自动重发。
+- 自动测试经既有 maker:provider:test-connection IPC 执行,追加可选 strategy/requestId 和取消请求,
+ 无字段的旧调用保留单次语义;此设置入口仅可信本机 Renderer 可用,不新增远控/手机凭证入口。
+ 请求按 sender 归属,关闭/改输入取消,迟到结果不回填;只在用户保存时持久化成功的 Pi 路由。
+- 回归位于 providerDetection.test.ts、providerDiagnostics.test.ts、providerHandlers.test.ts 和
+ CustomProviderDialogAccessibility.test.tsx;网络使用注入的协议响应,不当成真实第三方部署实测。
diff --git a/docs/product-rules/provider-auto-detection.md b/docs/product-rules/provider-auto-detection.md
index 882a5bdacf..88c65717f8 100644
--- a/docs/product-rules/provider-auto-detection.md
+++ b/docs/product-rules/provider-auto-detection.md
@@ -9,7 +9,7 @@
1. 添加页遵循已确认的 `simple-add-preview.html`:只填写显示名称、一组默认基础 URL 和 API key;请求头可选。
不展示预设下拉、鉴权方式、引擎页签或协议设置;独立引擎配置留在保存后的编辑入口。
- 未单独配置的引擎沿用默认连接与模型选择,仍各用自己的默认协议;已有独立草稿字段不覆盖。
+ 未识别的自定义连接默认只保存 Pi;已有独立引擎草稿字段不覆盖,已识别预设仍按预设绑定。
2. 输入稳定 400 ms 后,先按当前供应商目录匹配完整官方地址;未匹配时执行固定系统探测,
同时读取通用模型目录。名称、模型勾选变化不重新探测。
3. 只有唯一结果且该预设含可用引擎配置时显示“已识别为…”,保留 1200 ms,
@@ -31,7 +31,7 @@
- 遍历当前目录的预设(包括生成目录与已有官方 API 入口),不复制一份地区供应商白名单。
- 官方地址按规范化后的完整 origin/path 匹配,保留业务路径;同域不同路径不能混用。
-- Azure 等受约束资源模板使用既有模板绑定;任意 `{endpoint}`、回环地址及端口不能作为身份依据。
+- Azure 等受约束资源模板只在默认端口参与自动识别,非默认端口保留自定义,不进入会重写端口的模板绑定流程。原有手动模板绑定行为不在本次修改范围。任意 `{endpoint}`、回环地址及端口不能作为身份依据。
- 同地址对应多个套餐时不任意挑选,提示存在多个匹配,保留自定义流程;需要指定套餐时可返回供应商选择入口。
- 固定系统只有下面五类。用户部署地址替换预设端点,保留部署前缀和各模型路由;
不能把用户的地址替换成预设中的 localhost。识别后带入对应预设支持的各引擎配置,沿用各引擎的地址与协议规则,不创建兄弟账号。
@@ -67,13 +67,22 @@ LM Studio 详情按 key 或 loaded_instances.id 关联,不把本机所有已
- 返回 Renderer 的只有候选、模型元数据和分类错误,绝不返回账单、诊断原文或凭证。
- IPC 复用供应商配置的可信本机窗口校验,按真实 sender 隔离取消;页面销毁、账号代次变化后结果不可复用。
不扩大 device-link 的凭证通道。Mobile / 远程页面保持已有配置边界,不新增远程写密钥能力。
-- 无鉴权模式保持现有 loopback-only 规则;不因自动识别放宽。
+- 无鉴权模式保持现有 loopback-only 规则;不因自动识别放宽。新增简化表单仅在所有已填引擎地址和目录地址都是回环地址、且没有密钥或自定义请求头时自动使用无鉴权;密钥框仍保留,填写凭证或改成远程地址立即恢复 API key 模式。发现、测试、交接向导和保存使用同一有效鉴权方式;编辑已有连接不自动推断。
## 协议与保存
匹配后复用预设及 `providerInterfaceDefaultRoute`,再叠加用户显式配置和模型路由。
-未匹配时沿用现有新增流程的默认值:Claude Code 为 Messages,Codex 为 Responses,Pi 为 Chat。
-Pi 由保存流程写入协议,不把“运行时猜测”作为兜底。创建后仍可在编辑连接中调整协议和路径。
+未匹配时默认使用 Pi,尚未测试时以 Chat 为初始值。用户点击“测试连接”后,未显式指定模型接口的
+新自定义连接按地址特征、上次成功结果优先,最多串行验证 Chat、Responses、Messages、Google 四种协议。
+成功需要有效生成内容与合法结束,并将实际测通的地址和协议带回表单;用户保存时写入相同的 Pi 模型路由。
+已有预设、保存连接和显式模型接口保留各自的单次测试路径。
+
+只有明确、尚未进入生成的协议或路由拒绝允许继续。认证、额度、限流和模型错误立即停止;
+超时、断流、空流、HTML、5xx 或其它不确定结果停止并说明未能确认,不自动重复生成。
+每候选最多一次请求,SDK 不重试,自动探测单次 8 秒、整轮 15 秒;明确指定单一路由的测试沿用原时间预算。修改输入、关闭或主动停止后旧结果不回填。
+测试可能产生少量费用,基础生成成功不证明所有模型、工具或图片能力可用。
+
+Pi 由保存流程写入已验证或用户保留的协议,不在真实任务运行中猜测或轮换。创建后仍可在编辑连接中调整协议和路径。
探测结果与凭证只在当前表单内存中传递,保存仍走原来的连接创建和密钥存储。
即使识别为 LM Studio,手工添加的远程地址也创建独立连接,不覆盖托管的本地 LM Studio。
diff --git a/packages/model-providers/catalog/providers.json b/packages/model-providers/catalog/providers.json
index fbe5fcd733..fde539fd61 100644
--- a/packages/model-providers/catalog/providers.json
+++ b/packages/model-providers/catalog/providers.json
@@ -1737,6 +1737,47 @@
}
}
},
+ {
+ "id": "volcengine-api",
+ "name": "火山方舟 API",
+ "nameEn": "Volcengine Ark API",
+ "docsUrl": "https://www.volcengine.com/docs/82379/1330310",
+ "regionHint": "cn",
+ "models": [],
+ "runtimes": {
+ "claude-code": { "baseUrl": "https://ark.cn-beijing.volces.com/api/v3", "wireProtocol": "openai-chat" },
+ "codex": { "baseUrl": "https://ark.cn-beijing.volces.com/api/v3", "wireProtocol": "openai-chat" },
+ "pi": { "baseUrl": "https://ark.cn-beijing.volces.com/api/v3", "wireProtocol": "openai-chat" }
+ }
+ },
+ {
+ "id": "siliconflow-cn",
+ "name": "硅基流动(中国大陆)",
+ "nameEn": "SiliconFlow (China Mainland)",
+ "nameZhTW": "矽基流動(中國大陸)",
+ "docsUrl": "https://docs.siliconflow.cn/cn/userguide/quickstart",
+ "regionHint": "cn",
+ "models": [],
+ "runtimes": {
+ "claude-code": { "baseUrl": "https://api.siliconflow.cn/v1", "wireProtocol": "openai-chat", "modelsUrl": "https://api.siliconflow.cn/v1/models" },
+ "codex": { "baseUrl": "https://api.siliconflow.cn/v1", "wireProtocol": "openai-chat", "modelsUrl": "https://api.siliconflow.cn/v1/models" },
+ "pi": { "baseUrl": "https://api.siliconflow.cn/v1", "wireProtocol": "openai-chat", "modelsUrl": "https://api.siliconflow.cn/v1/models" }
+ }
+ },
+ {
+ "id": "siliconflow-global",
+ "name": "硅基流动",
+ "nameEn": "SiliconFlow",
+ "nameZhTW": "矽基流動",
+ "docsUrl": "https://docs.siliconflow.com/en/userguide/quickstart",
+ "regionHint": "global",
+ "models": [],
+ "runtimes": {
+ "claude-code": { "baseUrl": "https://api.siliconflow.com/v1", "wireProtocol": "openai-chat", "modelsUrl": "https://api.siliconflow.com/v1/models" },
+ "codex": { "baseUrl": "https://api.siliconflow.com/v1", "wireProtocol": "openai-chat", "modelsUrl": "https://api.siliconflow.com/v1/models" },
+ "pi": { "baseUrl": "https://api.siliconflow.com/v1", "wireProtocol": "openai-chat", "modelsUrl": "https://api.siliconflow.com/v1/models" }
+ }
+ },
{
"id": "volcengine-agent-plan",
"name": "火山方舟 Agent Plan",
diff --git a/packages/model-providers/src/__tests__/providerDetection.test.ts b/packages/model-providers/src/__tests__/providerDetection.test.ts
index 69a7bd723d..83b5ff3831 100644
--- a/packages/model-providers/src/__tests__/providerDetection.test.ts
+++ b/packages/model-providers/src/__tests__/providerDetection.test.ts
@@ -1,3 +1,4 @@
+import { providerProtocolCandidates } from '../providerProtocolProbe.js';
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';
@@ -55,6 +56,29 @@ describe('deployment evidence', () => {
});
describe('catalog mapping independent of desktop platform', () => {
+ // GUI acceptance 2026-10-21: these empty-key inputs stayed custom. Unit:
+ // exercise the real matcher and all harness bindings, not copied URL rules.
+ it.each([
+ ['https://ark.cn-beijing.volces.com/api/v3', 'volcengine-api'],
+ ['https://api.siliconflow.cn/v1', 'siliconflow-cn'],
+ ['https://api.siliconflow.com/v1', 'siliconflow-global'],
+ ['https://api.mistral.ai/v1', 'mistral'],
+ ['https://api.together.xyz/v1', 'together'],
+ ['https://api.fireworks.ai/inference/v1', 'fireworks'],
+ ])('recognizes and binds official API input %s', (url, id) => {
+ const matches = matchOfficialProviders(url, presets);
+ expect(matches.map(p => p.id)).toEqual([id]);
+ for (const agent of ['claude-code', 'codex', 'pi'] as const) {
+ const bound = bindDetectedProvider(matches[0], agent, url);
+ expect(bound?.runtimes[agent]).toBeDefined();
+ expect(bound?.runtimes[agent]?.baseUrl).not.toContain('{');
+ }
+ const fake = new URL(url);
+ fake.hostname += '.evil.test';
+ expect(matchOfficialProviders(fake.toString(), presets)).toEqual([]);
+ expect(matchOfficialProviders(url + '/unregistered', presets)).toEqual([]);
+ expect(matchOfficialProviders(url + '?token=fake', presets)).toEqual([]);
+ });
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)) {
@@ -94,3 +118,92 @@ describe('catalog mapping independent of desktop platform', () => {
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();
});
});
+
+// Automatic protocol routes must be persistable, same-origin, and preserve deployment prefixes.
+describe('protocol probe candidates', () => {
+ it.each([
+ ['https://relay.example', 'openai-chat', 'https://relay.example/v1'],
+ ['https://relay.example/responses', 'openai-responses', 'https://relay.example'],
+ ['https://relay.example/chat/completions', 'openai-chat', 'https://relay.example'],
+ ['https://relay.example/team/v1/chat/completions', 'openai-chat', 'https://relay.example/team/v1'],
+ ['https://relay.example/team/v1/responses', 'openai-responses', 'https://relay.example/team/v1'],
+ ['https://relay.example/team/v1/messages', 'anthropic-messages', 'https://relay.example/team'],
+ ['https://relay.example/team/v1beta', 'google-generative-ai', 'https://relay.example/team/v1beta'],
+ ])('keeps the exact resource binding for %s', (input, wireProtocol, baseUrl) => {
+ const candidates = providerProtocolCandidates(input);
+ expect(candidates).toHaveLength(4);
+ expect(candidates[0]).toEqual({ baseUrl, wireProtocol });
+ expect(candidates.every(item => new URL(item.baseUrl).origin === new URL(input).origin)).toBe(true);
+ });
+ it('prefers the previously verified route without changing its base', () => {
+ expect(providerProtocolCandidates('https://relay.example/team', 'anthropic-messages')[0]).toEqual({
+ baseUrl: 'https://relay.example/team', wireProtocol: 'anthropic-messages',
+ });
+ });
+ it.each(['https://relay.example/team/messages', 'https://user:[email protected]/v1', 'https://relay.example/v1?key=hidden', 'https://relay.example/v1#fragment', 'file:///tmp/test'])('rejects ambiguous credential or URL binding %s', input => {
+ expect(() => providerProtocolCandidates(input)).toThrow();
+ });
+});
+
+// Official resource identity must not redirect a custom-port service to port 443.
+describe('resource template port boundaries', () => {
+ it.each([
+ ['azure-openai-responses', 'https://reviewaccount.openai.azure.com/openai/v1'],
+ ['azure-openai-responses', 'https://reviewaccount.cognitiveservices.azure.com/openai/v1'],
+ ['google-vertex', 'https://us-central1-aiplatform.googleapis.com'],
+ ['google-vertex', 'https://aiplatform.googleapis.com'],
+ ['google-vertex', 'https://aiplatform.eu.rep.googleapis.com'],
+ ])('keeps %s custom ports outside automatic identity: %s', (id, input) => {
+ const preset = presets.find(p => p.id === id)!;
+ for (const port of ['', '443', '9443']) {
+ const url = new URL(input); url.port = port;
+ expect(matchOfficialProviders(url.toString(), presets).some(p => p.id === id)).toBe(port !== '9443');
+ for (const agent of ['claude-code', 'codex', 'pi'] as const) {
+ const bound = bindDetectedProvider(preset, agent, url.toString());
+ if (port === '9443') expect(bound).toBeUndefined();
+ else expect(new URL(bound!.runtimes[agent]!.baseUrl).port).toBe('');
+ }
+ }
+ });
+ it.each(['sub2api', 'litellm', 'lmstudio', 'llamacpp', 'vllm'])('preserves deployment port and prefix for %s', id => {
+ const preset = presets.find(p => p.id === id)!;
+ for (const agent of ['claude-code', 'codex', 'pi'] as const) {
+ const runtime = bindDetectedProvider(preset, agent, 'https://relay.example:9443/team/v1')?.runtimes[agent];
+ if (!preset.runtimes[agent]) continue;
+ expect(runtime!.baseUrl).toMatch(/^https:\/\/relay.example:9443\/team(?:\/v1)?$/);
+ if (runtime!.modelsUrl) expect(new URL(runtime!.modelsUrl).port).toBe('9443');
+ }
+ });
+});
+
+// Each fingerprint field is an independent boundary: partial lookalikes must not jump.
+describe('fingerprint boundary mutations', () => {
+ const checks = [
+ ['sub2api', 'subPublic.code'], ['sub2api', 'subPublic.data.version'],
+ ['sub2api', 'subPublic.data.hide_ccs_import_button'], ['sub2api', 'subPublic.data.backend_mode_enabled'],
+ ['sub2api', 'subPublic.data.subscription_enabled'], ['sub2api', 'subBilling.object'], ['sub2api', 'subBilling.schema_version'],
+ ['litellm', 'liteReady.litellm_version'], ['litellm', 'liteReady.status'], ['litellm', 'liteReady.success_callbacks'],
+ ['litellm', 'liteModels.data.0.model_name'], ['litellm', 'liteModels.data.0.litellm_params'], ['litellm', 'liteModels.data.0.model_info'],
+ ['lmstudio', 'lmGreeting.lmstudio'], ['lmstudio', 'lmModels.models'],
+ ['llamacpp', 'llamaProps.default_generation_settings'], ['llamacpp', 'llamaProps.total_slots'], ['llamacpp', 'llamaProps.build_info'], ['llamacpp', 'models.data.0.id'],
+ ['vllm', 'vllmVersion.version'], ['vllm', 'models.data.0.id'], ['vllm', 'models.data.0.root'], ['vllm', 'models.data.0.owned_by'], ['vllm', 'models.data.0.max_model_len'],
+ ];
+ it.each(checks)('rejects %s when %s is missing or null', (id, path) => {
+ for (const value of [undefined, null]) {
+ const input = structuredClone(evidence);
+ const parts = path.split('.');
+ let parent: any = input;
+ for (const part of parts.slice(0, -1)) parent = parent[part];
+ parent[parts.at(-1)!] = value;
+ expect(detectDeploymentProviders(input)).not.toContain(id);
+ }
+ });
+ it('does not merge ambiguous LM instance metadata or add hidden models', () => {
+ const visible = [{ id: 'shared', name: 'Shared' }];
+ const duplicate = { models: [
+ { key: 'first', type: 'llm', publisher: 'test', loaded_instances: [{ id: 'shared' }], max_context_length: 8192 },
+ { key: 'second', type: 'embedding', publisher: 'test', loaded_instances: [{ id: 'shared' }], max_context_length: 32768 },
+ ] };
+ expect(enrichDetectedModels(visible, 'lmstudio', { lmModels: duplicate })).toEqual(visible);
+ });
+});
diff --git a/packages/model-providers/src/__tests__/providerDetectionBinding.test.ts b/packages/model-providers/src/__tests__/providerDetectionBinding.test.ts
new file mode 100644
index 0000000000..5bd0d4cbe6
--- /dev/null
+++ b/packages/model-providers/src/__tests__/providerDetectionBinding.test.ts
@@ -0,0 +1,43 @@
+import { it, expect } from 'vitest';
+import { BUNDLED_CATALOG } from '../builtin.js';
+import { matchOfficialProviders, bindDetectedProvider, classifyProviderAddress } from '../providerDetection.js';
+const presets = BUNDLED_CATALOG.presets ?? [];
+const cases = presets.filter(p => classifyProviderAddress(p) === 'resource-template').flatMap(p => Object.values(p.runtimes).flatMap(rt => rt ? [{p, input: rt.baseUrl.replace(/\{([^}]+)\}/g, (_, key) => key === 'location' ? 'us-central1' : 'reviewaccount')}] : []));
+it.each(cases)('matched template binds after URL normalization: $p.id $input', ({p,input}) => {
+ for (const variant of [input, input.replace('https://', 'HTTPS://'), input.replace(/^(https:\/\/)([^/]+)/, (_, scheme, host) => scheme + host.toUpperCase()), input.replace(/^(https:\/\/)([^/]+)/, '$1$2:443')]) {
+ expect(matchOfficialProviders(variant, [p]).map(row => row.id), variant).toContain(p.id);
+ const bound = Object.keys(p.runtimes).map(a => bindDetectedProvider(p, a as keyof typeof p.runtimes, variant));
+ expect(bound.every(Boolean), variant).toBe(true);
+ for (const result of bound) for (const runtime of Object.values(result!.runtimes)) {
+ expect(runtime!.baseUrl).not.toMatch(/[{}]/);
+ if (p.id !== 'google-vertex') expect(runtime!.baseUrl).toContain('reviewaccount');
+ }
+ }
+});
+
+const official = presets.filter(p => classifyProviderAddress(p) === 'official').flatMap(p =>
+ [...new Set(Object.values(p.runtimes).flatMap(rt => rt ? [rt.baseUrl] : []))].map(input => ({ p, input })));
+it.each(official)('official address boundaries: $p.id $input', ({ p, input }) => {
+ const parsed = new URL(input);
+ if (parsed.search) return; // query-bound presets intentionally do not auto-identify
+ for (const value of [input, input + '/', input.replace(/^(https?:\/\/)([^/]+)/, (_, scheme, host) => scheme.toUpperCase() + host.toUpperCase())]) {
+ expect(matchOfficialProviders(value, [p]).map(row => row.id)).toContain(p.id);
+ for (const agent of Object.keys(p.runtimes) as (keyof typeof p.runtimes)[]) expect(bindDetectedProvider(p, agent, value)).toBeDefined();
+ }
+ for (const mutate of [
+ (u: URL) => { u.hostname += '.evil.example'; },
+ (u: URL) => { u.pathname += '/unregistered'; },
+ (u: URL) => { u.port = u.port === '9443' ? '9444' : '9443'; },
+ (u: URL) => { u.search = '?token=fake'; },
+ (u: URL) => { u.hash = '#fake'; },
+ (u: URL) => { u.username = 'fake'; },
+ ]) {
+ const value = new URL(input); mutate(value);
+ expect(matchOfficialProviders(value.toString(), [p]), value.toString()).toEqual([]);
+ }
+});
+
+it.each(['https://localhost:1234/v1', 'https://127.0.0.1:1234/v1', 'http://127.1:1234/v1', 'https://[::1]:1234/v1', 'HTTP://LOCALHOST:1234/v1'])('never assigns a brand from a loopback catalog URL: %s', baseUrl => {
+ const preset = { id: 'local-custom-brand', name: 'Local custom', runtimes: { pi: { baseUrl, models: [] } } };
+ expect(matchOfficialProviders(baseUrl, [preset])).toEqual([]);
+});
diff --git a/packages/model-providers/src/index.ts b/packages/model-providers/src/index.ts
index c940f0b6bf..f825129969 100644
--- a/packages/model-providers/src/index.ts
+++ b/packages/model-providers/src/index.ts
@@ -1,4 +1,5 @@
export { parseModelDisplayPricing, type ModelDisplayPricing } from './modelDisplayPricing.js';
+export { providerProtocolCandidates, type ProviderProtocolCandidate } from './providerProtocolProbe.js';
/**
* @cindy/model-providers — 模型供应商目录 + 路由抽象(纯逻辑,零 Electron / maker-core 运行时依赖)。
*
diff --git a/packages/model-providers/src/providerBranding.ts b/packages/model-providers/src/providerBranding.ts
index e9da20f29f..916e81b0b7 100644
--- a/packages/model-providers/src/providerBranding.ts
+++ b/packages/model-providers/src/providerBranding.ts
@@ -2,7 +2,7 @@
* Provider branding is pure catalog metadata shared by desktop and mobile.
*
* Paths use a 24px viewBox. Simple Icons 16.27.0 paths are CC0-1.0; the xAI
- * and Zhipu Mono paths are from Lobe Icons 5.14.0 under MIT. The LiteLLM
+ * Zhipu Mono and SiliconCloud paths are from Lobe Icons 5.14.0 under MIT. The LiteLLM
* mascot silhouette is adapted from litellm-docs/static/img/logo.svg under MIT.
* Ollama / LM Studio / vLLM paths are Simple Icons (CC0-1.0). llama.cpp has no
* official Simple Icons glyph; `llamacpp` is an original stack mark.
@@ -10,6 +10,7 @@
// Additional supplier marks: Lobe Icons 5.14.0 (MIT; included in THIRD-PARTY-NOTICES).
export const PROVIDER_LOGO_PATHS = {
+ siliconflow: 'M22.956 6.521H12.522c-.577 0-1.044.468-1.044 1.044v3.13c0 .577-.466 1.044-1.043 1.044H1.044c-.577 0-1.044.467-1.044 1.044v4.174C0 17.533.467 18 1.044 18h10.434c.577 0 1.044-.467 1.044-1.043v-3.13c0-.578.466-1.044 1.043-1.044h9.391c.577 0 1.044-.467 1.044-1.044V7.565c0-.576-.467-1.044-1.044-1.044z',
// Original S monogram for the self-hosted Sub2API connection (not upstream artwork).
sub2api: 'M5 3h14v3H8v4h8a3 3 0 0 1 3 3v5a3 3 0 0 1-3 3H5v-3h11v-5H8a3 3 0 0 1-3-3V3z',
antgroup: "M15.984 1.383c-.259.593-.877.914-1.334 1.348-.702.669-.998 1.726-1.218 2.682 3.37.775 5.995 3.532 6.486 7.025.566 4.016-1.85 7.859-5.744 9.134-3.894 1.276-8.153-.38-10.126-3.935A8.339 8.339 0 016.457 6.833a18.703 18.703 0 01-.376-.802l-.174-.408a8.698 8.698 0 01-.618-1.987 7.523 7.523 0 01-.051-.37 3.717 3.717 0 01-.024-.34 2.506 2.506 0 01.132-.872 1.26 1.26 0 01.384-.594.842.842 0 011.165.11c.694.82.169 2.078.142 3.02.009.575.111 1.144.301 1.684l-.103.052a8.404 8.404 0 001.318-.79c.28-.243.45-.742.781-.864.33-.121.682.146.946.297.278.145.587.219.901.214l.462.007c.076.002.152.005.226.011.212.01.422.026.63.05l.196-1.08c.04-.216.082-.43.126-.645l.141-.641c.14-.7.42-1.367.823-1.96.305-.431.75-.746 1.262-.89.877-.217 1.24.629.937 1.348zm-2.244 5.44c-2.841.002-4.898 2.532-4.628 5.64.27 3.11 2.781 5.642 5.613 5.666 2.832.024 4.932-2.512 4.658-5.644-.273-3.133-2.802-5.666-5.643-5.663zm.357.57a4.707 4.707 0 013.304 1.445 5.703 5.703 0 011.643 3.49 4.841 4.841 0 01-1.141 3.705v.015a3.923 3.923 0 01-2.808 1.303 4.664 4.664 0 01-3.367-1.387 5.678 5.678 0 01-1.71-3.518 4.832 4.832 0 011.14-3.753 3.923 3.923 0 012.813-1.3h.126z",
@@ -146,6 +147,9 @@ const PROVIDER_LOGO_KIND_BY_ID: Readonly<Record<string, ProviderLogoKind>> = {
'xiaomi-mimo-api-cn': 'xiaomimimo',
'xiaomi-mimo-token-plan-cn': 'xiaomimimo',
'volcengine-coding-plan': 'volcengine',
+ 'volcengine-api': 'volcengine',
+ 'siliconflow-cn': 'siliconflow',
+ 'siliconflow-global': 'siliconflow',
'volcengine-agent-plan': 'volcengine',
'tencentcloud-coding-plan': 'tencentcloud',
'opencode-go': 'opencode',
@@ -164,6 +168,8 @@ const PROVIDER_LOGO_KIND_BY_HOST: readonly (readonly [string, ProviderLogoKind])
["api.ant-ling.com", "antgroup"],
["inference.baseten.co", "baseten"],
["api.cerebras.ai", "cerebras"],
+ ["api.siliconflow.cn", "siliconflow"],
+ ["api.siliconflow.com", "siliconflow"],
["api.fireworks.ai", "fireworks"],
["api.groq.com", "groq"],
["router.huggingface.co", "huggingface"],
diff --git a/packages/model-providers/src/providerDetection.ts b/packages/model-providers/src/providerDetection.ts
index 7062ff7a76..3f7937b7dc 100644
--- a/packages/model-providers/src/providerDetection.ts
+++ b/packages/model-providers/src/providerDetection.ts
@@ -1,11 +1,12 @@
import type { AgentKind, ProviderPreset, ProviderPresetRuntime } from './types.js';
import { bindProviderPresetRuntime, providerEndpointBindings } from './providerEndpointTemplate.js';
import { providerInterfaceDefaultRoute } from './providerInterfaceRoutes.js';
+import { isLoopbackProviderUrl } from './provider-url.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 DETECTION_RULE_VERSION = '2026-10-21';
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>>;
@@ -71,6 +72,12 @@ export function detectionUrl(value: string): URL | undefined {
} catch { return; }
}
const clean = (value: string) => value.replace(/\/+$/, '');
+// Documented public aliases only. Do not strip /v1 or rewrite hostnames for
+// arbitrary providers. Each pair is gated on a declared canonical runtime.
+const officialAliases: Record<string, { canonical: string; input: string }> = {
+ mistral: { canonical: 'https://api.mistral.ai', input: 'https://api.mistral.ai/v1' },
+ together: { canonical: 'https://api.together.ai/v1', input: 'https://api.together.xyz/v1' },
+};
/** Never climb business prefixes or propagate query credentials into diagnostic endpoints. */
export function providerDeploymentRoot(value: string): string | undefined {
@@ -85,7 +92,7 @@ export function classifyProviderAddress(preset: ProviderPreset): ProviderAddress
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('{endpoint}') || isLoopbackProviderUrl(url))) return 'manual';
if (urls.some(url => url.includes('{'))) return 'resource-template';
return urls.every(url => detectionUrl(url)) ? 'official' : 'manual';
}
@@ -93,15 +100,31 @@ export function classifyProviderAddress(preset: ProviderPreset): ProviderAddress
/** 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 [];
+ if (!url || url.search || isLoopbackProviderUrl(baseUrl)) return [];
return presets.filter(preset => {
const kind = classifyProviderAddress(preset);
if (kind === 'deployment' || kind === 'manual') return false;
- return Object.values(preset.runtimes).some(rt => {
+ return Object.entries(preset.runtimes).some(([agent, rt]) => {
if (!rt) return false;
- if (rt.baseUrl.includes('{')) return !!providerEndpointBindings(rt.baseUrl, clean(url.toString()));
+ if (rt.baseUrl.includes('{')) {
+ // Account-family templates describe the official default port, not any
+ // service on the same hostname. Leave nonstandard ports in custom setup.
+ if (url.port) return false;
+ return !!providerEndpointBindings(rt.baseUrl, clean(url.toString()));
+ }
const declared = detectionUrl(rt.baseUrl);
- return declared && !declared.search && clean(declared.toString()) === clean(url.toString());
+ if (!declared || declared.search) return false;
+ const input = clean(url.toString());
+ const canonical = clean(declared.toString());
+ if (canonical === input) return true;
+ const alias = officialAliases[preset.id];
+ if (alias?.canonical === canonical && alias.input === input) return true;
+ // Mixed-protocol connections may publish the other protocol's address
+ // only in their maintained contract/model routes, not the default URL.
+ const route = providerInterfaceDefaultRoute(preset.id, agent as AgentKind, input);
+ const current = providerInterfaceDefaultRoute(preset.id, agent as AgentKind, canonical);
+ if (route && current && route.baseUrl === current.baseUrl) return true;
+ return rt.models.some(model => model.route && clean(model.route.baseUrl) === input);
});
});
}
@@ -110,6 +133,12 @@ export function matchOfficialProviders(baseUrl: string, presets: readonly Provid
export function bindDetectedProvider(preset: ProviderPreset, agent: AgentKind, input: string): ProviderPreset | undefined {
const original = preset.runtimes[agent];
if (!original) return;
+ // Match and bind the same normalized URL: scheme/host case and default
+ // ports are equivalent, while account IDs and business paths remain exact.
+ const normalized = detectionUrl(input);
+ if (!normalized || normalized.search) return;
+ input = clean(normalized.toString());
+ if (classifyProviderAddress(preset) === 'resource-template' && detectionUrl(input)?.port) return;
let runtime: ProviderPresetRuntime;
if (classifyProviderAddress(preset) === 'deployment') {
const root = providerDeploymentRoot(input);
diff --git a/packages/model-providers/src/providerProtocolProbe.ts b/packages/model-providers/src/providerProtocolProbe.ts
new file mode 100644
index 0000000000..6419cc7b39
--- /dev/null
+++ b/packages/model-providers/src/providerProtocolProbe.ts
@@ -0,0 +1,42 @@
+import type { ProviderWireProtocol } from './types.js';
+
+/** A candidate is a persistable Pi route, never a diagnostic-only request path. */
+export interface ProviderProtocolCandidate {
+ baseUrl: string;
+ wireProtocol: ProviderWireProtocol;
+}
+
+/** Bounded standard routes: preserve deployment prefixes, never guess another host. */
+export function providerProtocolCandidates(input: string, previous?: ProviderWireProtocol): ProviderProtocolCandidate[] {
+ const url = new URL(input);
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
+ throw new TypeError('automatic protocol detection requires a plain HTTP API base URL');
+ }
+ let path = url.pathname.replace(/\/+$/, '');
+ let preferred: ProviderWireProtocol | undefined = previous;
+ let exactEndpoint = false;
+ for (const [suffix, protocol] of [
+ ['/chat/completions', 'openai-chat'], ['/responses', 'openai-responses'],
+ ['/messages', 'anthropic-messages'],
+ ] as const) {
+ if (path.endsWith(suffix)) {
+ path = path.slice(0, -suffix.length); preferred = protocol; exactEndpoint = true;
+ if (protocol === 'anthropic-messages' && !path.endsWith('/v1')) {
+ throw new TypeError('this exact messages path cannot be represented by the native Pi SDK');
+ }
+ break;
+ }
+ }
+ if (/\/v1beta$/.test(path)) preferred = 'google-generative-ai';
+ const order: ProviderWireProtocol[] = ['openai-chat', 'openai-responses', 'anthropic-messages', 'google-generative-ai'];
+ if (preferred) order.splice(0, 0, ...order.splice(order.indexOf(preferred), 1));
+ return order.map(wireProtocol => {
+ let basePath = path;
+ // These are SDK standard roots, not a scan of sibling deployment paths.
+ if (!basePath && !exactEndpoint) basePath = wireProtocol === 'google-generative-ai' ? '/v1beta'
+ : wireProtocol === 'anthropic-messages' ? '' : '/v1';
+ // Anthropic's SDK itself appends /v1/messages.
+ if (wireProtocol === 'anthropic-messages') basePath = basePath.replace(/\/v1$/, '');
+ return { baseUrl: url.origin + basePath, wireProtocol };
+ });
+}
diff --git a/packages/model-providers/src/providerSetupLinks.ts b/packages/model-providers/src/providerSetupLinks.ts
index 19f83355a0..3bfb37da15 100644
--- a/packages/model-providers/src/providerSetupLinks.ts
+++ b/packages/model-providers/src/providerSetupLinks.ts
@@ -37,6 +37,9 @@ const links: Record<string, ProviderSetupLink> = {
'xiaomi-token-plan-sgp': key('https://platform.xiaomimimo.com/token-plan'),
longcat: key('https://longcat.chat/platform/api_keys'),
'volcengine-agent-plan': account('https://console.volcengine.com/ark/'),
+ 'volcengine-api': account('https://console.volcengine.com/ark/'),
+ 'siliconflow-cn': key('https://cloud.siliconflow.cn/account/ak'),
+ 'siliconflow-global': key('https://cloud.siliconflow.com/account/ak'),
'volcengine-coding-plan': account('https://console.volcengine.com/ark/'),
'tencentcloud-coding-plan': account('https://console.cloud.tencent.com/'),
opencode: account('https://opencode.ai/auth'),