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。

feat(desktop): 支持自定义供应商一键填充其他 runtime (#2291)

nanacobd599292c115
diff --git a/apps/desktop/src/main/__tests__/safeStorageCodexRestart.test.ts b/apps/desktop/src/main/__tests__/safeStorageCodexRestart.test.ts
index 541f57f900..49c6e44e99 100644
--- a/apps/desktop/src/main/__tests__/safeStorageCodexRestart.test.ts
+++ b/apps/desktop/src/main/__tests__/safeStorageCodexRestart.test.ts
@@ -72,4 +72,15 @@ describe('safe storage Codex restart invariants', () => {
expect(body).toContain("safeStorageReadLog.error('read failed'");
expect(body).not.toContain("console.error('[safe-storage-read]', err)");
});
+
+ it('keeps custom-provider runtime reads strict while preserving missing-key null semantics', () => {
+ const src = source();
+ const start = src.indexOf("'safe-storage-read'");
+ const end = src.indexOf("'safe-storage-remove'", start);
+ const body = src.slice(start, end);
+ expect(body).toContain('isCustomProviderRuntimeKeyStorageKey(key)');
+ expect(body).toContain("throwIpcError('INTERNAL', 'custom provider credential is unavailable')");
+ expect(body).toContain("throwIpcError('INTERNAL', 'custom provider credential is unreadable')");
+ expect(body).toContain('if (!fs.existsSync(filepath)) return null;');
+ });
});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 1c286abf2b..6b578191e8 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -549,6 +549,7 @@ import {
type BuiltinApiKeyBridgeDeps,
} from './secrets/builtinApiKeyBridge.js';
import {
+ isCustomProviderRuntimeKeyStorageKey,
isRendererAccessibleSafeStorageKey,
type ProviderSecretId,
} from '../shared/providerSecrets.js';
@@ -3899,12 +3900,18 @@ const registerIpcHandlers = () => {
ipcMain.handle(
'safe-storage-read',
async (event: Electron.IpcMainInvokeEvent, key: string): Promise<string | null> => {
+ const strictCustomProviderRead = isCustomProviderRuntimeKeyStorageKey(key);
try {
assertTrustedAppRendererEvent(event);
if (!isValidRendererKey(key)) return null;
const filepath = resolveSafeStorageFilepath(key);
if (!filepath) return null;
- if (!safeStorage.isEncryptionAvailable()) return null;
+ if (!safeStorage.isEncryptionAvailable()) {
+ if (strictCustomProviderRead) {
+ throwIpcError('INTERNAL', 'custom provider credential is unavailable');
+ }
+ return null;
+ }
if (!fs.existsSync(filepath)) return null;
const content = fs.readFileSync(filepath, 'utf-8');
const buffer = Buffer.from(content, 'base64');
@@ -3919,6 +3926,9 @@ const registerIpcHandlers = () => {
safeStorageReadLog.error('read failed', {
error: isIpcError(err) ? err.code : err instanceof Error ? err.name : 'unknown',
});
+ if (strictCustomProviderRead) {
+ throwIpcError('INTERNAL', 'custom provider credential is unreadable');
+ }
}
return null;
}
diff --git a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts
index 3a69ba9267..800e34f52a 100644
--- a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts
@@ -485,6 +485,21 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
.toBe('/tenant/acme/v2/infer?stream=1');
});
+ it('strips requestPath from Pi native runtime records', async () => {
+ mountDb();
+ await createCustomProvider({
+ ...valid,
+ runtimes: {
+ pi: {
+ ...valid.runtimes.codex!,
+ requestPath: '/ignored-by-pi',
+ },
+ },
+ });
+
+ expect((await getCustomProvider('openrouter'))?.runtimes.pi?.requestPath).toBeUndefined();
+ });
+
it.each([
'//evil.example/infer',
'/infer#fragment',
diff --git a/apps/desktop/src/main/maker-host/custom-provider-header-secrets.ts b/apps/desktop/src/main/maker-host/custom-provider-header-secrets.ts
index bcad198cdb..aedc513c5a 100644
--- a/apps/desktop/src/main/maker-host/custom-provider-header-secrets.ts
+++ b/apps/desktop/src/main/maker-host/custom-provider-header-secrets.ts
@@ -8,7 +8,6 @@
import type { AgentKind, CustomProviderConfig } from '@cindy/model-providers';
import {
- readCustomProviderHeaders,
readCustomProviderHeadersForMutation,
removeCustomProviderHeaders,
storeCustomProviderHeaders,
@@ -57,9 +56,13 @@ export function hydrateCustomProviderHeaders(
for (const agent of CUSTOM_PROVIDER_RUNTIME_AGENTS) {
const runtime = runtimes[agent];
if (!runtime) continue;
- const headers = readCustomProviderHeaders(config.id, agent);
- if (headers && Object.keys(headers).length > 0) {
- runtimes[agent] = { ...runtime, headers };
+ try {
+ const headers = readCustomProviderHeadersForMutation(config.id, agent);
+ if (headers && Object.keys(headers).length > 0) {
+ runtimes[agent] = { ...runtime, headers, headersState: 'configured' };
+ }
+ } catch {
+ runtimes[agent] = { ...runtime, headersState: 'unknown' };
}
}
return { ...config, runtimes };
diff --git a/apps/desktop/src/main/maker-host/custom-provider-store.ts b/apps/desktop/src/main/maker-host/custom-provider-store.ts
index a22cbb5993..13307a80c5 100644
--- a/apps/desktop/src/main/maker-host/custom-provider-store.ts
+++ b/apps/desktop/src/main/maker-host/custom-provider-store.ts
@@ -390,7 +390,9 @@ function normalizeRuntime(
});
const out: CustomProviderRuntimeConfig = { baseUrl: rt.baseUrl.trim(), models };
if (rt.wireProtocol) out.wireProtocol = rt.wireProtocol;
- if (rt.requestPath && rt.requestPath.trim()) out.requestPath = rt.requestPath.trim();
+ if (agent !== 'pi' && rt.requestPath && rt.requestPath.trim()) {
+ out.requestPath = rt.requestPath.trim();
+ }
if (rt.modelsUrl && rt.modelsUrl.trim()) out.modelsUrl = rt.modelsUrl.trim();
return out;
}
@@ -535,7 +537,7 @@ function parseRuntimes(raw: string): Partial<Record<AgentKind, CustomProviderRun
) {
entry.wireProtocol = r.wireProtocol;
}
- if (isProviderRequestPath(r.requestPath)) {
+ if (agent !== 'pi' && isProviderRequestPath(r.requestPath)) {
entry.requestPath = r.requestPath;
}
if (r.headers && typeof r.headers === 'object' && !Array.isArray(r.headers)) {
diff --git a/apps/desktop/src/main/maker-host/provider-diagnostics.ts b/apps/desktop/src/main/maker-host/provider-diagnostics.ts
index 7816c06877..f4a5aecada 100644
--- a/apps/desktop/src/main/maker-host/provider-diagnostics.ts
+++ b/apps/desktop/src/main/maker-host/provider-diagnostics.ts
@@ -333,6 +333,8 @@ export function resolveSavedProbeSpec(providerId: string, agent: AgentKind): Pro
isAgentSelectableModel(m, { userProvider: provider.source === 'user' }),
);
if (!model) throw new Error(`provider '${providerId}' has no chat models for '${agent}'`);
+ // Pi derives its inference path from wireProtocol and does not consume requestPath.
+ const requestPath = agent === 'pi' ? undefined : routing.requestPath;
// OAuth 形态:探测凭证用 Runner 持有的 access_token(与 oauth-token 路由同源),未登录时
// 无 token → 探测会得到 AUTH_INVALID,这本身就是「先去登录」的正确结论。
// token 走 authorization 头而**不走 apiKey 字段**——apiKey 会让 cc 探测同时发
@@ -345,7 +347,7 @@ export function resolveSavedProbeSpec(providerId: string, agent: AgentKind): Pro
baseUrl: routing.upstream,
modelId: model.id,
wireProtocol: routing.wireProtocol,
- requestPath: routing.requestPath,
+ requestPath,
apiKey: null,
headers: {
...withoutCredentialHeaders(routing.headerOverride),
@@ -359,7 +361,7 @@ export function resolveSavedProbeSpec(providerId: string, agent: AgentKind): Pro
baseUrl: routing.upstream,
modelId: model.id,
wireProtocol: routing.wireProtocol,
- requestPath: routing.requestPath,
+ requestPath,
apiKey: null,
headers: withoutCredentialHeaders(routing.headerOverride),
};
@@ -373,7 +375,7 @@ export function resolveSavedProbeSpec(providerId: string, agent: AgentKind): Pro
// 必须带上 wireProtocol,否则 buildProbeRequest 回落到原生 /responses,对 Chat-only 上游
// 误报连接失败(真实会话走 resolveSessionRoute 不受影响,探测结论会与真实会话相反)。
wireProtocol: routing.wireProtocol,
- requestPath: routing.requestPath,
+ requestPath,
apiKey,
// 与真实会话路由保持 legacy 兼容:safeStorage 已有 key 时清掉旧凭证头,由 apiKey
// 重新注入;尚未迁移的 header-only 配置则原样保留,否则“测试连接”会无凭证误报失败。
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 1bbd81a5fc..36b1bffceb 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
@@ -215,6 +215,7 @@ describe('provider:list IPC handler', () => {
upstream: 'https://custom.example/v1',
authStrategy: 'api-key-header',
headerOverride: { Authorization: 'Bearer secret' },
+ headerOverrideState: 'configured',
},
},
} as unknown as ProviderView;
@@ -227,6 +228,7 @@ describe('provider:list IPC handler', () => {
providers: ProviderView[];
};
expect(result.providers[0].routing.pi?.headerOverride).toBeUndefined();
+ expect(result.providers[0].routing.pi?.headerOverrideState).toBe('configured');
expect(result.providers[0].routing.pi?.upstream).toBe('https://custom.example/v1');
});
@@ -241,6 +243,7 @@ describe('provider:list IPC handler', () => {
upstream: 'https://custom.example/v1',
authStrategy: 'api-key-header',
headerOverride: { Authorization: 'Bearer secret' },
+ headerOverrideState: 'configured',
},
},
} as unknown as ProviderView;
@@ -253,6 +256,7 @@ describe('provider:list IPC handler', () => {
providers: ProviderView[];
};
expect(result.providers[0].routing.pi?.headerOverride).toBeUndefined();
+ expect(result.providers[0].routing.pi?.headerOverrideState).toBe('configured');
// 非密字段仍完整回传,编辑表单据此渲染 endpoint/鉴权策略。
expect(result.providers[0].routing.pi?.upstream).toBe('https://custom.example/v1');
});
@@ -1126,6 +1130,70 @@ describe('provider:custom:* CRUD handlers', () => {
expect(headers.get('pi')).toBeUndefined();
});
+ it('clears a stored API key when an update moves the runtime to a different endpoint', async () => {
+ mountDb();
+ const harness = new IpcHarness();
+ const keys = new Map<AgentKind, string>();
+ const removeCustomProviderKey = vi.fn((_providerId, agent: AgentKind) => {
+ keys.delete(agent);
+ return { success: true };
+ });
+ registerProviderHandlers(harness, makeDeps({
+ readCustomProviderKeyForMutation: vi.fn(
+ (_providerId, agent: AgentKind) => keys.get(agent) ?? null,
+ ),
+ storeCustomProviderKey: vi.fn((_providerId, agent: AgentKind, value: string) => {
+ keys.set(agent, value);
+ return true;
+ }),
+ removeCustomProviderKey,
+ }));
+ const config: CustomProviderConfig = {
+ id: 'move-api-key',
+ name: 'Move API key',
+ auth: { method: 'apiKey' },
+ runtimes: {
+ pi: {
+ baseUrl: 'https://old-endpoint.example/v1',
+ modelsUrl: 'https://old-endpoint.example/models',
+ models: [{ id: 'm', name: 'M' }],
+ },
+ },
+ };
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_CREATE, config, {
+ pi: 'endpoint-bound-key',
+ });
+ removeCustomProviderKey.mockClear();
+
+ await expect(harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {
+ ...config,
+ name: 'Move API key — model edit only',
+ runtimes: {
+ pi: {
+ ...config.runtimes.pi!,
+ models: [{ id: 'm', name: 'M renamed' }],
+ },
+ },
+ })).resolves.toEqual({ ok: true });
+ expect(removeCustomProviderKey).not.toHaveBeenCalledWith('move-api-key', 'pi');
+ expect(keys.get('pi')).toBe('endpoint-bound-key');
+ removeCustomProviderKey.mockClear();
+
+ await expect(harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, {
+ ...config,
+ runtimes: {
+ pi: {
+ baseUrl: 'https://new-endpoint.example/v1',
+ modelsUrl: 'https://new-endpoint.example/models',
+ models: [{ id: 'm', name: 'M' }],
+ },
+ },
+ })).resolves.toEqual({ ok: true });
+
+ expect(removeCustomProviderKey).toHaveBeenCalledWith('move-api-key', 'pi');
+ expect(keys.get('pi')).toBeUndefined();
+ });
+
it('merges stored main-only headers into a saved-provider model fetch', async () => {
// codex review:头凭证不回读进 renderer,刷新模型时 main 按 savedProviderId 并入已存头。
mountDb();
@@ -2124,12 +2192,17 @@ describe('provider:test-connection handler', () => {
baseUrl: 'https://pi.example/v1',
modelId: 'pi-model',
authMethod: 'apiKey',
+ requestPath: '/ignored-by-pi',
apiKey: 'k',
},
})).resolves.toMatchObject({ ok: true });
expect(testConnection).toHaveBeenCalledWith(expect.objectContaining({
kind: 'adhoc',
- spec: expect.objectContaining({ agent: 'pi', wireProtocol: 'openai-chat' }),
+ spec: expect.objectContaining({
+ agent: 'pi',
+ wireProtocol: 'openai-chat',
+ requestPath: undefined,
+ }),
}));
});
diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
index 1a58240ca8..f6135c0312 100644
--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
@@ -184,7 +184,8 @@ function withoutProviderHeaderCredentials(provider: ProviderView): ProviderView
const routing = Object.fromEntries(
Object.entries(provider.routing).map(([agent, descriptor]) => {
if (!descriptor) return [agent, descriptor];
- const { headerOverride: _secretHeaders, ...safeDescriptor } = descriptor;
+ const safeDescriptor = { ...descriptor };
+ delete safeDescriptor.headerOverride;
return [agent, safeDescriptor];
}),
) as ProviderView['routing'];
@@ -397,7 +398,8 @@ function parseTestInput(input: unknown): ProviderTestInput | null {
modelId: spec.modelId,
authMethod: spec.authMethod as ProviderProbeSpec['authMethod'],
wireProtocol: spec.wireProtocol as ProviderProbeSpec['wireProtocol'],
- requestPath: spec.requestPath as string | undefined,
+ requestPath:
+ spec.agent === 'pi' ? undefined : (spec.requestPath as string | undefined),
apiKey: (spec.apiKey as string | null | undefined) ?? null,
headers: spec.headers as Record<string, string> | undefined,
},
@@ -608,6 +610,22 @@ export function registerProviderHandlers(
};
type KeySnapshot = { agent: AgentKind; previous: string | null };
type KeyMutation = { agent: AgentKind; replacement: string | null };
+ // Stored API keys and main-only credential headers are endpoint-bound. If a runtime moves to a
+ // different base/models URL without an explicit replacement, clear the old secret atomically.
+ const endpointChangedForAgent = (
+ config: CustomProviderConfig,
+ previous: CustomProviderConfig | null | undefined,
+ agent: AgentKind,
+ ): boolean => {
+ const prevRt = previous?.runtimes[agent];
+ const nextRt = config.runtimes[agent];
+ if (!prevRt || !nextRt) return false;
+ const norm = (value: string | null | undefined): string => (value ?? '').trim();
+ return (
+ norm(prevRt.baseUrl) !== norm(nextRt.baseUrl) ||
+ norm(prevRt.modelsUrl) !== norm(nextRt.modelsUrl)
+ );
+ };
const restoreProviderKeys = (
providerId: string,
snapshots: readonly KeySnapshot[],
@@ -626,6 +644,7 @@ export function registerProviderHandlers(
config: CustomProviderConfig,
keys: RuntimeKeys,
mode: 'create' | 'update',
+ previous?: CustomProviderConfig | null,
): KeyMutation[] => {
const mutations: KeyMutation[] = [];
const usesApiKey = !config.auth || config.auth.method === 'apiKey';
@@ -640,6 +659,9 @@ export function registerProviderHandlers(
const shouldRemove = !usesApiKey || !config.runtimes[agent];
if (shouldRemove) mutations.push({ agent, replacement: null });
else if (replacement) mutations.push({ agent, replacement });
+ else if (endpointChangedForAgent(config, previous, agent)) {
+ mutations.push({ agent, replacement: null });
+ }
}
return mutations;
};
@@ -694,21 +716,6 @@ export function registerProviderHandlers(
}
return restored;
};
- // update 时:runtime 仍在、apiKey 鉴权、未带 headers 的“保留”分支只在**端点未变**时成立。
- // 若 baseUrl/modelsUrl 改到了另一端点,旧密文头绑定的是原端点,保留会把长期凭证 hydrate 到
- // 新主机(codex review P1)。用**权威的 previous 配置**逐 agent 比对端点,变了就清除、要求重填。
- const endpointChangedForAgent = (
- config: CustomProviderConfig,
- previous: CustomProviderConfig | null | undefined,
- agent: AgentKind,
- ): boolean => {
- const prevRt = previous?.runtimes[agent];
- const nextRt = config.runtimes[agent];
- if (!prevRt || !nextRt) return false; // 新增 runtime 无旧端点/旧头可漏;runtime 移除已单独清
- const norm = (u: string | null | undefined): string => (u ?? '').trim();
- return norm(prevRt.baseUrl) !== norm(nextRt.baseUrl)
- || norm(prevRt.modelsUrl) !== norm(nextRt.modelsUrl);
- };
const planProviderHeaderMutations = (
config: CustomProviderConfig,
headers: CustomProviderHeaderSecrets,
@@ -1334,7 +1341,7 @@ export function registerProviderHandlers(
assertProviderMutationOwner(ownerAtIngress);
const credentialSnapshots = stageProviderCredentials(
config.id,
- planProviderKeyMutations(config, keys, 'update'),
+ planProviderKeyMutations(config, keys, 'update', previous),
planProviderHeaderMutations(config, separated.headers, 'update', previous),
);
// 先阻止在途 flow 写回,再改描述符;否则旧 flow 可能在 clear 后迟到落一枚旧 token。
diff --git a/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx b/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx
index 84ff4b64d1..20d44c3ab9 100644
--- a/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx
+++ b/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx
@@ -14,9 +14,17 @@
* DESIGN.md §4 规定的 `--surface-elevated`(压在 ivory settings 卡上的输入必须用它)。
*/
-import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
+import * as Dialog from '@radix-ui/react-dialog';
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+ type RefObject,
+} from 'react';
import { useTranslation } from 'react-i18next';
-import { Check, ChevronDown, Plug, Plus, RefreshCw, Sparkles, Trash2 } from 'lucide-react';
+import { Check, ChevronDown, Plug, Plus, RefreshCw, Sparkles, Trash2, X } from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from '@/lib/toast';
@@ -25,6 +33,10 @@ import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover
import { ClaudeMark } from '@/components/icons/ClaudeMark';
import { CodexMark } from '@/components/icons/CodexMark';
import { PiMark } from '@/components/icons/PiMark';
+import {
+ CustomProviderRuntimeFillOverlay,
+ type RuntimeFillDialogState,
+} from '@/components/settings/CustomProviderRuntimeFillOverlay';
import { extractIpcError } from '@/utils/ipcError';
import {
createCustomProvider,
@@ -39,10 +51,12 @@ import {
import { uniqueCustomProviderId } from '@/lib/customProviderId';
import {
areProviderRequestUrlsAllowed,
+ canSendHydratedApiKey,
connectionTestCanUseSaved,
modelFetchCanReuseSavedCredentials,
providerConnectionTestRequestSignature,
providerModelFetchRequestSignature,
+ restoreHydratedApiKey,
stripCredentialHeaders,
type CustomProviderAuthMode,
type SavedProviderProbeBaseline,
@@ -51,6 +65,20 @@ import {
CUSTOM_PROVIDER_CODEX_WIRE_PROTOCOLS,
customProviderCodexWireProtocolOption,
} from '@/lib/customProviderWireProtocols';
+import {
+ applyRuntimeFillFields,
+ buildRuntimeFillDiffs,
+ cloneRuntimeFillDraft,
+ mergeHydratedRuntimeKeys,
+ normalizeRuntimeFillSelection,
+ runtimeFillEndpointUrlsChanged,
+ runtimeFillFieldsForToggle,
+ runtimeFillHasUnreviewedConflict,
+ runtimeFillSelectedTargetChanged,
+ runtimeFillTargetAgents,
+ type RuntimeFillDraft,
+ type RuntimeFillField,
+} from '@/lib/customProviderRuntimeFill';
import {
isProviderRequestPath,
@@ -78,6 +106,15 @@ const AGENTS: DialogAgentKind[] = ['claude-code', 'codex', 'pi'];
const VISIBLE_AGENTS: DialogAgentKind[] = AGENTS;
+const DIALOG_FOCUSABLE_SELECTOR = [
+ 'button:not([disabled])',
+ 'input:not([disabled])',
+ 'select:not([disabled])',
+ 'textarea:not([disabled])',
+ '[href]',
+ '[tabindex]:not([tabindex="-1"])',
+].join(',');
+
const TAB_META: Record<DialogAgentKind, { Mark: typeof ClaudeMark; labelKey: string; helpKey: string }> =
{
'claude-code': {
@@ -111,6 +148,8 @@ interface CustomProviderDialogProps {
initial?: CustomProviderConfig;
/** 已占用的全部 provider id(内置 anthropic/openai/xd + 全部自定义);新建时自动生成 id 时避让,防撞内置保留 id。 */
existingIds?: string[];
+ /** Stable fallback for transitions whose immediate opener unmounts before this dialog mounts. */
+ returnFocusRef?: RefObject<HTMLElement | null>;
onSaved: () => void;
onClose: () => void;
}
@@ -128,11 +167,7 @@ interface HeaderRow {
name: string;
value: string;
}
-interface RuntimeFields {
- baseUrl: string;
- requestPath: string;
- apiKey: string;
- wireProtocol: ProviderWireProtocol;
+interface RuntimeFields extends RuntimeFillDraft {
models: ModelRow[];
headers: HeaderRow[];
/** 隐藏字段:列模型端点(预设 / 已存配置快照进来),「获取模型列表」用;不在表单展示。 */
@@ -172,7 +207,7 @@ function initRuntimes(initial?: CustomProviderConfig): Record<DialogAgentKind, R
if (!rc) continue;
out[a] = {
baseUrl: rc.baseUrl,
- requestPath: rc.requestPath ?? '',
+ requestPath: a === 'pi' ? '' : (rc.requestPath ?? ''),
apiKey: '',
wireProtocol: rc.wireProtocol ?? defaultWireFor(a),
models: rc.models.length ? rc.models.map((m) => ({ ...m })) : [{ id: '', name: '' }],
@@ -181,6 +216,7 @@ function initRuntimes(initial?: CustomProviderConfig): Record<DialogAgentKind, R
? Object.entries(rc.headers).map(([n, v]) => ({ name: n, value: v }))
: [{ name: '', value: '' }],
modelsUrl: rc.modelsUrl ?? '',
+ headersState: rc.headersState,
};
}
}
@@ -311,6 +347,7 @@ function PresetDropdown({
export function CustomProviderDialog({
initial,
existingIds,
+ returnFocusRef,
onSaved,
onClose,
}: CustomProviderDialogProps) {
@@ -380,20 +417,42 @@ export function CustomProviderDialog({
pi: false,
});
// 拉取成功后的勾选弹层:行集合 = 拉取结果 ∪ 表单已填(后者默认勾选、保留用户显示名)。
+ const [runtimeFill, setRuntimeFill] = useState<RuntimeFillDialogState | null>(null);
const picker = childLayer?.kind === 'model-picker' ? childLayer.value : null;
const presetMenuOpen = childLayer?.kind === 'preset-menu';
+ const [keyHydrationReady, setKeyHydrationReady] = useState(!editing);
+ const [keyHydrationFailed, setKeyHydrationFailed] = useState<
+ Record<DialogAgentKind, boolean>
+ >({
+ 'claude-code': false,
+ codex: false,
+ pi: false,
+ });
+ const runtimeFillTriggerRef = useRef<HTMLButtonElement>(null);
+ const modelPickerTriggerRef = useRef<HTMLButtonElement>(null);
+ const modelFetchInFlightRef = useRef(false);
+ const dialogPanelRef = useRef<HTMLDivElement>(null);
// 原生 window listener 的生命周期不跟着每次 render 重绑;layout effect 只把
// 已提交的层状态写入 ref,既避开 passive effect 延迟,也不暴露被放弃的并发 render。
const childLayerRef = useRef(childLayer);
+ const runtimeFillRef = useRef(runtimeFill);
+ const savingRef = useRef(saving);
const onCloseRef = useRef(onClose);
useLayoutEffect(() => {
childLayerRef.current = childLayer;
+ runtimeFillRef.current = runtimeFill;
+ savingRef.current = saving;
onCloseRef.current = onClose;
- }, [childLayer, onClose]);
+ }, [childLayer, onClose, runtimeFill, saving]);
- // Dismissible form contract:一个关闭输入只结算最上层一次。模型选择器优先于
- // 预设菜单,最后才是表单;Cancel 仍直接表示用户要关闭表单,且无重复 ×。
+ // Dismissible form contract:一个关闭输入只结算最上层一次。runtime fill / 模型选择器
+ // 优先于预设菜单,最后才是表单;Cancel 仍直接表示用户要关闭表单,且无重复 ×。
const dismissTopmostLayer = useCallback(() => {
+ if (runtimeFillRef.current) {
+ runtimeFillRef.current = null;
+ setRuntimeFill((current) => (current ? null : current));
+ return;
+ }
const activeLayer = childLayerRef.current;
if (activeLayer) {
// 同一事件周期内先同步更新 owner,避免快速连续输入重复结算旧层。
@@ -401,6 +460,7 @@ export function CustomProviderDialog({
setChildLayer((current) => (current === activeLayer ? null : current));
return;
}
+ if (savingRef.current) return;
onCloseRef.current();
}, []);
@@ -408,7 +468,7 @@ export function CustomProviderDialog({
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Escape') return;
// IME 候选窗的 Escape 是组合输入控制,不是弹层关闭意图。
- if (event.isComposing || event.keyCode === 229) return;
+ if (event.defaultPrevented || event.isComposing || event.keyCode === 229) return;
// 在 Radix 的 document capture 之前由唯一 owner 结算;否则菜单的 80ms
// 退场层仍可能 preventDefault,吞掉刚打开的模型选择器的 Escape。
event.preventDefault();
@@ -418,6 +478,23 @@ export function CustomProviderDialog({
window.addEventListener('keydown', onKeyDown, { capture: true });
return () => window.removeEventListener('keydown', onKeyDown, true);
}, [dismissTopmostLayer]);
+
+ useEffect(() => {
+ const returnFocusElement =
+ document.activeElement instanceof HTMLElement && document.activeElement !== document.body
+ ? document.activeElement
+ : null;
+ const frame = requestAnimationFrame(() => {
+ dialogPanelRef.current?.querySelector<HTMLInputElement>('input')?.focus();
+ });
+ return () => {
+ cancelAnimationFrame(frame);
+ const focusTarget = returnFocusElement?.isConnected
+ ? returnFocusElement
+ : returnFocusRef?.current;
+ if (focusTarget?.isConnected) focusTarget.focus();
+ };
+ }, [returnFocusRef]);
// 最新 runtime 表单状态镜像:拉取响应到达时据此构建弹层行/预勾选,而不是用请求发出时的
// 闭包快照——在途期间被用户删除的行不得复活。镜像在每个 setRt updater 内**同步**更新
// (见 setRtSynced),不用被动 useEffect——effect 在 commit 后才跑,IPC 响应若落在
@@ -441,6 +518,13 @@ export function CustomProviderDialog({
codex: '',
pi: '',
});
+ // A late safeStorage response must not overwrite a key edited or copied while
+ // hydration was in flight. Revisions only change for explicit key mutations.
+ const keyEditRevisionRef = useRef<Record<DialogAgentKind, number>>({
+ 'claude-code': 0,
+ codex: 0,
+ pi: 0,
+ });
// 已存供应商在编辑态的基线快照:端点/协议/鉴权模式取自已存配置,apiKey 取回填值,
// headers 取已存非密文头(自定义鉴权头是 main-only 密文,不回读进表单)。测试连接 /
@@ -459,7 +543,7 @@ export function CustomProviderDialog({
: 'apiKey';
return {
baseUrl: rc.baseUrl,
- requestPath: rc.requestPath ?? '',
+ requestPath: agent === 'pi' ? '' : (rc.requestPath ?? ''),
modelsUrl: rc.modelsUrl ?? '',
wireProtocol: rc.wireProtocol ?? defaultWireFor(agent),
authMode: savedAuthMode,
@@ -473,6 +557,34 @@ export function CustomProviderDialog({
[editing, initial],
);
+ // URL edits temporarily clear an untouched hydrated key so it cannot be
+ // sent to a new endpoint. If the user returns to the saved credential
+ // target before editing the key, restore the in-memory hydration instead of
+ // forcing an unnecessary re-entry (or sending apiKey: null to model fetch).
+ const restoreHydratedKey = useCallback(
+ (agent: DialogAgentKind, draft: RuntimeFields): RuntimeFields => {
+ const savedBaseline = savedBaselineFor(agent);
+ if (!savedBaseline) return draft;
+ return restoreHydratedApiKey(
+ draft,
+ { ...savedBaseline, apiKey: loadedKeyRef.current[agent] },
+ authModeRef.current,
+ keyEditRevisionRef.current[agent],
+ );
+ },
+ [savedBaselineFor],
+ );
+
+ const changeAuthMode = useCallback((mode: CustomProviderAuthMode) => {
+ setAuthMode(mode);
+ if (mode !== 'apiKey') return;
+ setRtSynced((prev) =>
+ Object.fromEntries(
+ AGENTS.map((agent) => [agent, restoreHydratedKey(agent, prev[agent])]),
+ ) as Record<DialogAgentKind, RuntimeFields>,
+ );
+ }, [restoreHydratedKey, setRtSynced]);
+
// 新建态拉取预设模板(本地 IPC 极快返回;失败静默 —— 没有预设也不影响手填,规则 7 不做 loading)。
// 按实际构建区域排序,不随 UI 语言变化(只排序不过滤,可达性由测试连接实测裁决)。
useEffect(() => {
@@ -507,7 +619,7 @@ export function CustomProviderDialog({
}
next[a] = {
baseUrl: rc.baseUrl,
- requestPath: rc.requestPath ?? '',
+ requestPath: a === 'pi' ? '' : (rc.requestPath ?? ''),
apiKey: prev[a].apiKey, // 已填的 key 保留
wireProtocol: rc.wireProtocol ?? defaultWireFor(a),
models: rc.models.length ? rc.models.map((m) => ({ ...m })) : [{ id: '', name: '' }],
@@ -536,14 +648,30 @@ export function CustomProviderDialog({
// 让密钥框「能看」(eye 显形 / 可核对),而非空白遮罩;据此点亮「已保存」徽标。
// 鉴权请求头是 main-only 密文,不回读进表单;未显式改动时由 main 侧 update 保留旧值。
useEffect(() => {
- if (!editing || !initial) return;
+ if (!editing || !initial) {
+ setKeyHydrationReady(true);
+ return;
+ }
let cancelled = false;
+ setKeyHydrationReady(false);
+ setKeyHydrationFailed({ 'claude-code': false, codex: false, pi: false });
+ const revisionAtStart = { ...keyEditRevisionRef.current };
void (async () => {
const nextHas: Record<DialogAgentKind, boolean> = { 'claude-code': false, codex: false, pi: false };
const fetched: Partial<Record<DialogAgentKind, string>> = {};
+ const failed: Record<DialogAgentKind, boolean> = {
+ 'claude-code': false,
+ codex: false,
+ pi: false,
+ };
for (const a of AGENTS) {
if (!initial.runtimes[a]) continue;
- const k = await readCustomProviderKey(initial.id, a);
+ let k: string | null = null;
+ try {
+ k = await readCustomProviderKey(initial.id, a);
+ } catch {
+ failed[a] = true;
+ }
if (k) {
nextHas[a] = true;
fetched[a] = k;
@@ -554,27 +682,250 @@ export function CustomProviderDialog({
// 记下回填的已存明文 key 作为基线:测试连接判定「凭证材料是否被改动」时用来决定
// 走受控 saved 探测还是 adhoc(headers 是 main-only 密文,基线取自 initial 的非密文头)。
for (const a of AGENTS) loadedKeyRef.current[a] = fetched[a] ?? '';
- setRtSynced((prev) => {
- const next = { ...prev };
- for (const a of AGENTS) {
- if (fetched[a] != null) next[a] = { ...next[a], apiKey: fetched[a] as string };
- }
- return next;
- });
+ setRtSynced((prev) =>
+ mergeHydratedRuntimeKeys(
+ prev,
+ fetched,
+ Object.fromEntries(
+ AGENTS.flatMap((agent) => {
+ const baseline = savedBaselineFor(agent);
+ return baseline
+ ? [[agent, { baseUrl: baseline.baseUrl, modelsUrl: baseline.modelsUrl }] as const]
+ : [];
+ }),
+ ),
+ revisionAtStart,
+ keyEditRevisionRef.current,
+ ),
+ );
+ setKeyHydrationFailed(failed);
+ setKeyHydrationReady(true);
})();
return () => {
cancelled = true;
};
- }, [editing, initial]);
+ }, [editing, initial, savedBaselineFor]);
const patch = useCallback(
(agent: DialogAgentKind, fn: (f: RuntimeFields) => RuntimeFields) => {
- setRtSynced((prev) => ({ ...prev, [agent]: fn(prev[agent]) }));
+ setRtSynced((prev) => {
+ const current = prev[agent];
+ const next = restoreHydratedKey(agent, fn(current));
+ const endpointChanged =
+ current.baseUrl.trim() !== next.baseUrl.trim() ||
+ current.modelsUrl.trim() !== next.modelsUrl.trim();
+ return {
+ ...prev,
+ [agent]:
+ endpointChanged &&
+ keyEditRevisionRef.current[agent] === 0 &&
+ next.apiKey === current.apiKey
+ ? { ...next, apiKey: '' }
+ : next,
+ };
+ });
setTest((prev) => ({ ...prev, [agent]: IDLE_TEST }));
},
- [setRtSynced],
+ [restoreHydratedKey, setRtSynced],
);
+ const openRuntimeFill = useCallback(() => {
+ if (modelFetchInFlightRef.current || picker) {
+ toast.info(t('settings.providers.custom.runtimeFill.modelsBusy'));
+ return;
+ }
+ const source = activeTab;
+ const usesApiKey = authModeRef.current === 'apiKey';
+ if (usesApiKey && !keyHydrationReady) {
+ toast.info(t('settings.providers.custom.runtimeFill.loadingKeys'));
+ return;
+ }
+ if (usesApiKey && AGENTS.some((agent) => keyHydrationFailed[agent])) {
+ toast.info(t('settings.providers.custom.runtimeFill.keysUnavailable'));
+ return;
+ }
+ const includeApiKey = usesApiKey;
+
+ const oauthPiUnavailable = authModeRef.current === 'oauth' && source !== 'pi';
+ const sourceDraft = cloneRuntimeFillDraft(rtRef.current[source]);
+ const allTargets = runtimeFillTargetAgents(source, {
+ includePi: authModeRef.current !== 'oauth',
+ }).map((agent) => ({
+ agent,
+ draft: cloneRuntimeFillDraft(rtRef.current[agent]),
+ diffs: buildRuntimeFillDiffs(sourceDraft, rtRef.current[agent], {
+ includeApiKey,
+ sourceAgent: source,
+ targetAgent: agent,
+ }),
+ }));
+ if (!allTargets.some((target) => target.diffs.length > 0)) {
+ toast.info(t('settings.providers.custom.runtimeFill.nothingToFill'));
+ return;
+ }
+ const targets = allTargets.filter((target) =>
+ target.diffs.some((diff) => diff.targetState !== 'same'),
+ );
+ if (targets.length === 0) {
+ toast.info(t('settings.providers.custom.runtimeFill.alreadySame'));
+ return;
+ }
+ if (
+ !targets.some((target) =>
+ target.diffs.some(
+ (diff) => diff.targetState === 'empty' || diff.targetState === 'conflict',
+ ),
+ )
+ ) {
+ toast.info(t('settings.providers.custom.runtimeFill.noCompatibleFields'));
+ return;
+ }
+
+ const selected: Partial<Record<DialogAgentKind, RuntimeFillField[]>> = {};
+ for (const target of targets) {
+ selected[target.agent] = normalizeRuntimeFillSelection(
+ target.diffs
+ .filter((diff) => diff.targetState === 'empty' || diff.targetState === 'conflict')
+ .map((diff) => diff.field),
+ target.diffs,
+ );
+ }
+ childLayerRef.current = null;
+ setChildLayer(null);
+ setRuntimeFill({
+ source,
+ sourceDraft,
+ includeApiKey,
+ oauthPiUnavailable,
+ stage: 'review',
+ targets,
+ selected,
+ });
+ }, [activeTab, keyHydrationFailed, keyHydrationReady, picker, t]);
+
+ const applyRuntimeFill = useCallback(() => {
+ if (!runtimeFill) return;
+ const changedTargets = runtimeFill.targets.filter(
+ (target) => (runtimeFill.selected[target.agent]?.length ?? 0) > 0,
+ );
+ if (changedTargets.length === 0) return;
+
+ // Re-read targets immediately before applying. Background async work should not
+ // turn an empty field into an unconfirmed overwrite after the review snapshot.
+ const freshTargets = runtimeFill.targets.map((target) => {
+ const draft = cloneRuntimeFillDraft(rtRef.current[target.agent]);
+ return {
+ ...target,
+ draft,
+ diffs: buildRuntimeFillDiffs(runtimeFill.sourceDraft, draft, {
+ includeApiKey: runtimeFill.includeApiKey,
+ sourceAgent: runtimeFill.source,
+ targetAgent: target.agent,
+ }),
+ };
+ });
+ const hasUnreviewedConflict = freshTargets.some((target) => {
+ const previous = runtimeFill.targets.find((candidate) => candidate.agent === target.agent);
+ const selectedFields = runtimeFill.selected[target.agent] ?? [];
+ return (
+ runtimeFillHasUnreviewedConflict(previous?.diffs ?? [], target.diffs, selectedFields) ||
+ (previous != null &&
+ runtimeFillSelectedTargetChanged(
+ previous.draft,
+ target.draft,
+ selectedFields,
+ target.agent,
+ ))
+ );
+ });
+ if (hasUnreviewedConflict) {
+ setRuntimeFill((prev) => (prev ? { ...prev, stage: 'confirm', targets: freshTargets } : prev));
+ return;
+ }
+
+ for (const target of changedTargets) {
+ if (runtimeFill.selected[target.agent]?.includes('apiKey')) {
+ keyEditRevisionRef.current[target.agent] += 1;
+ }
+ }
+ setRtSynced((prev) => {
+ const next = { ...prev };
+ for (const target of changedTargets) {
+ const selectedFields = runtimeFill.selected[target.agent] ?? [];
+ const filled = applyRuntimeFillFields(
+ prev[target.agent],
+ runtimeFill.sourceDraft,
+ selectedFields,
+ { sourceAgent: runtimeFill.source, targetAgent: target.agent },
+ );
+ const endpointChanged = runtimeFillEndpointUrlsChanged(prev[target.agent], filled);
+ const endpointSafeFilled =
+ endpointChanged &&
+ !selectedFields.includes('apiKey') &&
+ keyEditRevisionRef.current[target.agent] === 0
+ ? { ...filled, apiKey: '' }
+ : filled;
+ next[target.agent] = restoreHydratedKey(target.agent, endpointSafeFilled);
+ }
+ return next;
+ });
+ const modelFilledAgents = changedTargets
+ .filter((target) => runtimeFill.selected[target.agent]?.includes('models'))
+ .map((target) => target.agent);
+ if (modelFilledAgents.length > 0) {
+ const modelFilled = new Set(modelFilledAgents);
+ setWindowDrafts((drafts) =>
+ Object.fromEntries(
+ Object.entries(drafts).filter(
+ ([key]) => !modelFilled.has(key.split(':')[0] as DialogAgentKind),
+ ),
+ ),
+ );
+ }
+ setTest((prev) => {
+ const next = { ...prev };
+ for (const target of changedTargets) next[target.agent] = IDLE_TEST;
+ return next;
+ });
+ toast.success(
+ t('settings.providers.custom.runtimeFill.filledToast', {
+ targets: new Intl.ListFormat(i18n.language, {
+ style: 'short',
+ type: 'conjunction',
+ }).format(changedTargets.map((target) => t(TAB_META[target.agent].labelKey))),
+ }),
+ );
+ setRuntimeFill(null);
+ }, [i18n.language, restoreHydratedKey, runtimeFill, setRtSynced, t]);
+
+ const continueRuntimeFill = useCallback(() => {
+ if (!runtimeFill) return;
+ const hasOverwrite = runtimeFill.targets.some((target) =>
+ target.diffs.some(
+ (diff) =>
+ diff.targetState === 'conflict' &&
+ (runtimeFill.selected[target.agent]?.includes(diff.field) ?? false),
+ ),
+ );
+ if (hasOverwrite) setRuntimeFill((prev) => (prev ? { ...prev, stage: 'confirm' } : prev));
+ else applyRuntimeFill();
+ }, [applyRuntimeFill, runtimeFill]);
+
+ const toggleRuntimeFillField = useCallback((agent: DialogAgentKind, field: RuntimeFillField) => {
+ setRuntimeFill((prev) => {
+ if (!prev) return prev;
+ const target = prev.targets.find((candidate) => candidate.agent === agent);
+ if (!target) return prev;
+ const current = prev.selected[agent] ?? [];
+ const toggledFields = runtimeFillFieldsForToggle(field, target.diffs);
+ const allSelected = toggledFields.every((candidate) => current.includes(candidate));
+ const nextFields = allSelected
+ ? current.filter((candidate) => !toggledFields.includes(candidate))
+ : normalizeRuntimeFillSelection([...current, ...toggledFields], target.diffs);
+ return { ...prev, selected: { ...prev.selected, [agent]: nextFields } };
+ });
+ }, []);
+
/** 切换协议时保留用户已填写的 endpoint,仅使旧测试结果失效。 */
const changeWireProtocol = useCallback(
(agent: DialogAgentKind, wireProtocol: ProviderWireProtocol) => {
@@ -593,6 +944,7 @@ export function CustomProviderDialog({
const handleTest = useCallback(async () => {
const agent = activeTab;
const rf = rt[agent];
+ const probeFields = agent === 'pi' ? { ...rf, requestPath: '' } : rf;
const baseUrl = rf.baseUrl.trim();
const firstModel = rf.models.map((m) => m.id.trim()).find((id) => id.length > 0);
if (!baseUrl || !firstModel) {
@@ -609,13 +961,24 @@ export function CustomProviderDialog({
if (n) headers[n] = h.value.trim();
}
const requestHeaders = authMode === 'none' ? stripCredentialHeaders(headers) : headers;
- const requestSig = providerConnectionTestRequestSignature(rf, authMode);
+ const requestSig = providerConnectionTestRequestSignature(probeFields, authMode);
// 编辑态且端点/协议/鉴权模式与凭证材料相对已存配置都未改动时,走受控 saved 探测:
// 它整体按已存 spec 发起,能带上不回读进表单的 main-only 密文鉴权头(否则纯密文头
// 供应商会因缺头而失败)。任一改动则回落 adhoc,测用户新填的值。
const savedBaseline = savedBaselineFor(agent);
+ const canSendApiKey =
+ authMode !== 'apiKey' ||
+ !savedBaseline ||
+ canSendHydratedApiKey(
+ probeFields,
+ savedBaseline,
+ authMode,
+ keyEditRevisionRef.current[agent],
+ );
const useSaved = Boolean(
- initial?.id && savedBaseline && connectionTestCanUseSaved(rf, savedBaseline, authMode),
+ initial?.id &&
+ savedBaseline &&
+ connectionTestCanUseSaved(probeFields, savedBaseline, authMode),
);
setTest((prev) => ({ ...prev, [agent]: { status: 'testing' } }));
try {
@@ -630,14 +993,22 @@ export function CustomProviderDialog({
modelId: firstModel,
authMethod: authMode,
wireProtocol: rf.wireProtocol,
- ...(rf.requestPath.trim() ? { requestPath: rf.requestPath.trim() } : {}),
- apiKey: authMode === 'apiKey' ? rf.apiKey.trim() || null : null,
+ ...(agent !== 'pi' && rf.requestPath.trim()
+ ? { requestPath: rf.requestPath.trim() }
+ : {}),
+ apiKey:
+ authMode === 'apiKey' && canSendApiKey ? rf.apiKey.trim() || null : null,
...(Object.keys(requestHeaders).length > 0 ? { headers: requestHeaders } : {}),
},
},
);
if (
- providerConnectionTestRequestSignature(rtRef.current[agent], authModeRef.current) !==
+ providerConnectionTestRequestSignature(
+ agent === 'pi'
+ ? { ...rtRef.current[agent], requestPath: '' }
+ : rtRef.current[agent],
+ authModeRef.current,
+ ) !==
requestSig
)
return;
@@ -649,7 +1020,12 @@ export function CustomProviderDialog({
}));
} catch (e) {
if (
- providerConnectionTestRequestSignature(rtRef.current[agent], authModeRef.current) !==
+ providerConnectionTestRequestSignature(
+ agent === 'pi'
+ ? { ...rtRef.current[agent], requestPath: '' }
+ : rtRef.current[agent],
+ authModeRef.current,
+ ) !==
requestSig
)
return;
@@ -667,7 +1043,14 @@ export function CustomProviderDialog({
const handleFetchModels = useCallback(async () => {
const agent = activeTab;
const rf = rt[agent];
- if (fetchingModels['claude-code'] || fetchingModels.codex || fetchingModels.pi) return; // 单飞(按钮已禁用,兜底)
+ if (
+ modelFetchInFlightRef.current ||
+ runtimeFill ||
+ picker ||
+ fetchingModels['claude-code'] ||
+ fetchingModels.codex ||
+ fetchingModels.pi
+ ) return; // 单飞(按钮已禁用,兜底)
const baseUrl = rf.baseUrl.trim();
if (!baseUrl) {
toast.error(t('settings.providers.custom.fetch.needBaseUrl'));
@@ -690,9 +1073,19 @@ export function CustomProviderDialog({
// savedProviderId,让 main 侧并入不回读进 renderer 的 main-only 密文鉴权头(表单显式
// 填的头/key 仍由 main 以 renderer 值优先);端点一改就不带,避免把已存凭证外泄给新主机。
const savedBaseline = savedBaselineFor(agent);
+ const canSendApiKey =
+ authMode !== 'apiKey' ||
+ !savedBaseline ||
+ canSendHydratedApiKey(
+ rf,
+ savedBaseline,
+ authMode,
+ keyEditRevisionRef.current[agent],
+ );
const reuseSaved = Boolean(
initial?.id && savedBaseline && modelFetchCanReuseSavedCredentials(rf, savedBaseline, authMode),
);
+ modelFetchInFlightRef.current = true;
setFetchingModels((prev) => ({ ...prev, [agent]: true }));
try {
const result = await window.electronAPI.maker.fetchProviderModels({
@@ -701,7 +1094,7 @@ export function CustomProviderDialog({
authMethod: authMode,
...(rf.wireProtocol ? { wireProtocol: rf.wireProtocol } : {}),
modelsUrl: rf.modelsUrl.trim() || null,
- apiKey: authMode === 'apiKey' ? rf.apiKey.trim() || null : null,
+ apiKey: authMode === 'apiKey' && canSendApiKey ? rf.apiKey.trim() || null : null,
...(Object.keys(requestHeaders).length > 0 ? { headers: requestHeaders } : {}),
...(reuseSaved ? { savedProviderId: initial!.id } : {}),
});
@@ -766,9 +1159,10 @@ export function CustomProviderDialog({
const ipc = extractIpcError(e);
toast.error(ipc?.message ?? t('settings.providers.custom.fetch.failed'));
} finally {
+ modelFetchInFlightRef.current = false;
setFetchingModels((prev) => ({ ...prev, [agent]: false }));
}
- }, [activeTab, authMode, rt, fetchingModels, t, savedBaselineFor, initial]);
+ }, [activeTab, authMode, rt, fetchingModels, initial, picker, runtimeFill, savedBaselineFor, t]);
/**
* 勾选弹层确认:勾选集写回该 runtime 的模型行。基于**确认时的最新表单行**合并,
@@ -878,6 +1272,27 @@ export function CustomProviderDialog({
toast.error(t('settings.providers.custom.errors.nameRequired'));
return;
}
+ if (editing && authMode === 'apiKey' && !keyHydrationReady) {
+ toast.info(t('settings.providers.custom.runtimeFill.loadingKeys'));
+ return;
+ }
+ if (editing && authMode === 'apiKey') {
+ const failedEndpointEdit = VISIBLE_AGENTS.find((agent) => {
+ if (!keyHydrationFailed[agent]) return false;
+ const baseline = savedBaselineFor(agent);
+ const draft = rt[agent];
+ return (
+ baseline != null &&
+ (draft.baseUrl.trim() !== baseline.baseUrl.trim() ||
+ draft.modelsUrl.trim() !== baseline.modelsUrl.trim())
+ );
+ });
+ if (failedEndpointEdit) {
+ setActiveTab(failedEndpointEdit);
+ toast.error(t('settings.providers.custom.runtimeFill.keysUnavailable'));
+ return;
+ }
+ }
// 上下文窗口草稿必须已可提交:输入框还挂着 `1,` / `-5` 这类未完成/非法文本时
// 点保存,已提交值(或隐式 200K 默认)与用户可见文本不一致——静默存旧值等于
// 改掉用户显式输入(review P1 ×2)。定位到首个问题 tab 并报错拦下。
@@ -934,7 +1349,7 @@ export function CustomProviderDialog({
: {}),
}))
.filter((m) => m.id && m.name);
- const requestPath = rf.requestPath.trim();
+ const requestPath = a === 'pi' ? '' : rf.requestPath.trim();
if (requestPath && !isProviderRequestPath(requestPath)) {
setActiveTab(a);
toast.error(t('settings.providers.custom.errors.requestPathInvalid'));
@@ -962,7 +1377,13 @@ export function CustomProviderDialog({
...(rf.modelsUrl.trim() ? { modelsUrl: rf.modelsUrl.trim() } : {}),
};
// OAuth 形态不收集 per-runtime API key(鉴权走 Runner 的 Bearer)。
- if (authMode === 'apiKey' && rf.apiKey.trim()) keys[a] = rf.apiKey.trim();
+ if (
+ authMode === 'apiKey' &&
+ rf.apiKey.trim() &&
+ (!editing || keyEditRevisionRef.current[a] > 0)
+ ) {
+ keys[a] = rf.apiKey.trim();
+ }
}
if (Object.keys(runtimes).length === 0) {
toast.error(t('settings.providers.custom.errors.runtimeRequired'));
@@ -1077,11 +1498,19 @@ export function CustomProviderDialog({
existingIds,
onSaved,
windowDrafts,
+ keyHydrationFailed,
showAdvanced,
+ savedBaselineFor,
t,
]);
- const keyPlaceholder = hasKey[activeTab]
+ const activeSavedBaseline = savedBaselineFor(activeTab);
+ const activeKeyCanRemainSaved =
+ hasKey[activeTab] &&
+ activeSavedBaseline != null &&
+ f.baseUrl.trim() === activeSavedBaseline.baseUrl.trim() &&
+ f.modelsUrl.trim() === activeSavedBaseline.modelsUrl.trim();
+ const keyPlaceholder = activeKeyCanRemainSaved
? t('settings.providers.custom.fields.apiKeyEditPlaceholder')
: t('settings.providers.custom.fields.apiKeyPlaceholder');
@@ -1091,23 +1520,58 @@ export function CustomProviderDialog({
onPointerDown={(event) => {
// pointerdown 时先按当前层级结算,避免 Popover 的 outside-dismiss 在随后
// click 前把状态改成 closed,令同一次手势继续误关底层表单。
- if (event.button === 0 && event.target === event.currentTarget) dismissTopmostLayer();
+ if (
+ event.button === 0 &&
+ event.target === event.currentTarget &&
+ !saving &&
+ !runtimeFill
+ ) {
+ dismissTopmostLayer();
+ }
+ }}
+ onKeyDown={(event) => {
+ if (childLayer || runtimeFill) return;
+ if (event.key !== 'Tab') return;
+ const focusable = Array.from(
+ dialogPanelRef.current?.querySelectorAll<HTMLElement>(DIALOG_FOCUSABLE_SELECTOR) ?? [],
+ );
+ if (focusable.length === 0) {
+ event.preventDefault();
+ dialogPanelRef.current?.focus();
+ return;
+ }
+ const first = focusable[0];
+ const last = focusable[focusable.length - 1];
+ if (event.shiftKey && document.activeElement === first) {
+ event.preventDefault();
+ last.focus();
+ } else if (!event.shiftKey && document.activeElement === last) {
+ event.preventDefault();
+ first.focus();
+ }
}}
>
<div
+ ref={dialogPanelRef}
role="dialog"
aria-modal="true"
+ aria-labelledby="custom-provider-dialog-title"
+ tabIndex={-1}
className={cn(
- 'flex max-h-[88vh] w-[600px] flex-col rounded-[16px]',
+ 'flex max-h-[88vh] w-[600px] flex-col rounded-[16px] outline-none',
'border border-[var(--border-default)] bg-[var(--surface-elevated)]',
'shadow-[var(--shadow-menu)]',
+ '[&_button:focus-visible]:outline-none [&_button:focus-visible]:ring-2 [&_button:focus-visible]:ring-[var(--focus-ring)]',
)}
>
{/* Header bar */}
<div className="flex items-center px-3 py-3">
<div className="flex items-center gap-2.5 pl-2">
<Sparkles size={20} className="text-[var(--settings-section-title)]" />
- <h2 className="text-18 font-semibold text-[var(--settings-section-title)]">
+ <h2
+ id="custom-provider-dialog-title"
+ className="text-18 font-semibold text-[var(--settings-section-title)]"
+ >
{editing
? t('settings.providers.custom.dialog.editTitle')
: t('settings.providers.custom.dialog.createTitle')}
@@ -1166,7 +1630,7 @@ export function CustomProviderDialog({
key={m}
type="button"
onClick={() => {
- setAuthMode(m);
+ changeAuthMode(m);
setTest({ 'claude-code': IDLE_TEST, codex: IDLE_TEST, pi: IDLE_TEST });
}}
className={cn(
@@ -1355,7 +1819,17 @@ export function CustomProviderDialog({
{/* 基础 URL */}
<div className="flex flex-col gap-[7px]">
- <FieldLabel>{t('settings.providers.custom.fields.baseUrl')}</FieldLabel>
+ <div className="flex items-center justify-between gap-3">
+ <FieldLabel>{t('settings.providers.custom.fields.baseUrl')}</FieldLabel>
+ <button
+ ref={runtimeFillTriggerRef}
+ type="button"
+ onClick={openRuntimeFill}
+ className="shrink-0 rounded-full px-1 py-0.5 text-11 font-medium text-[var(--text-tertiary)] transition-colors hover:text-[var(--settings-section-title)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ {t('settings.providers.custom.runtimeFill.action')}
+ </button>
+ </div>
<SettingsTextInput
surface="ivory"
value={f.baseUrl}
@@ -1365,22 +1839,24 @@ export function CustomProviderDialog({
</div>
{/* 精确推理路径:给非标准兼容端点使用;留空仍按所选协议推导。 */}
- <div className="flex flex-col gap-[7px]">
- <FieldLabel>{t('settings.providers.custom.fields.requestPath')}</FieldLabel>
- <SettingsTextInput
- surface="ivory"
- value={f.requestPath}
- onChange={(v) => patch(activeTab, (x) => ({ ...x, requestPath: v }))}
- placeholder={
- activeTab === 'claude-code' || f.wireProtocol === 'anthropic-messages'
- ? '/v1/messages'
- : customProviderCodexWireProtocolOption(f.wireProtocol).defaultRequestPath
- }
- />
- <span className="text-12 leading-snug text-[var(--text-tertiary)]">
- {t('settings.providers.custom.fields.requestPathHelp')}
- </span>
- </div>
+ {activeTab !== 'pi' && (
+ <div className="flex flex-col gap-[7px]">
+ <FieldLabel>{t('settings.providers.custom.fields.requestPath')}</FieldLabel>
+ <SettingsTextInput
+ surface="ivory"
+ value={f.requestPath}
+ onChange={(v) => patch(activeTab, (x) => ({ ...x, requestPath: v }))}
+ placeholder={
+ activeTab === 'claude-code' || f.wireProtocol === 'anthropic-messages'
+ ? '/v1/messages'
+ : customProviderCodexWireProtocolOption(f.wireProtocol).defaultRequestPath
+ }
+ />
+ <span className="text-12 leading-snug text-[var(--text-tertiary)]">
+ {t('settings.providers.custom.fields.requestPathHelp')}
+ </span>
+ </div>
+ )}
{/* API 密钥(OAuth 形态隐藏——鉴权走 Runner 的 Bearer,不收集 key) */}
{authMode === 'apiKey' && (
@@ -1388,7 +1864,7 @@ export function CustomProviderDialog({
<div className="flex items-center gap-2">
<FieldLabel>{t('settings.providers.custom.fields.apiKey')}</FieldLabel>
{/* 已存密钥时给明确徽标 —— 编辑态字段是遮罩空白(留空=不改),无徽标会让人误以为没存上。 */}
- {hasKey[activeTab] && (
+ {activeKeyCanRemainSaved && f.apiKey.trim() && (
<span
className="flex items-center gap-1 rounded-full px-2 py-0.5 text-11 font-medium"
style={{
@@ -1404,7 +1880,10 @@ export function CustomProviderDialog({
<SettingsTextInput
surface="ivory"
value={f.apiKey}
- onChange={(v) => patch(activeTab, (x) => ({ ...x, apiKey: v }))}
+ onChange={(v) => {
+ keyEditRevisionRef.current[activeTab] += 1;
+ patch(activeTab, (x) => ({ ...x, apiKey: v }));
+ }}
placeholder={keyPlaceholder}
mono
secret
@@ -1494,7 +1973,8 @@ export function CustomProviderDialog({
if (draftText === undefined || !isCommittableWindowText(draftText)) {
return drafts;
}
- const { [`${activeTab}:${i}`]: _drop, ...rest } = drafts;
+ const rest = { ...drafts };
+ delete rest[`${activeTab}:${i}`];
return rest;
})
}
@@ -1506,8 +1986,9 @@ export function CustomProviderDialog({
if (j !== i) return y;
const trimmed = v.trim();
if (trimmed === '') {
- const { contextWindow: _drop, ...rest } = y;
- return rest;
+ const next = { ...y };
+ delete next.contextWindow;
+ return next;
}
// 整体校验(分隔符只允许单个、夹在数字组之间;BigInt 精确
// 校验上界防 parseInt 先舍入):不合法的中间态/非法值只
@@ -1761,6 +2242,7 @@ export function CustomProviderDialog({
{/* 获取模型列表:GET 该供应商的列模型端点,成功后开勾选弹层填进上方模型行。
disabled 用 anyFetching(单飞):另一 Tab 在途时本 Tab 也不许发起。 */}
<button
+ ref={modelPickerTriggerRef}
type="button"
onClick={() => void handleFetchModels()}
disabled={anyFetching}
@@ -1802,6 +2284,7 @@ export function CustomProviderDialog({
className={cn(
'inline-flex items-center justify-center rounded-full border bg-transparent px-6 py-2.5 text-13 font-medium transition-colors active:scale-[0.98]',
'border-[var(--confirm-btn-secondary-border)] text-[var(--confirm-btn-secondary-text)] hover:bg-[var(--confirm-btn-secondary-hover)]',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
)}
>
{t('settings.providers.custom.cancel')}
@@ -1814,6 +2297,7 @@ export function CustomProviderDialog({
// min-w + 绝对定位 spinner:saving 切换时按钮宽度恒定,不再撑大挤动取消按钮(规则 7)。
'relative inline-flex min-w-[96px] items-center justify-center rounded-full px-6 py-2.5 text-13 font-medium transition-colors active:scale-[0.98]',
'bg-[var(--confirm-btn-primary-bg)] text-[var(--confirm-btn-primary-text)] hover:bg-[var(--confirm-btn-primary-hover)]',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
saving && 'cursor-not-allowed opacity-50',
)}
>
@@ -1834,6 +2318,23 @@ export function CustomProviderDialog({
}}
onConfirm={applyPicker}
onClose={dismissTopmostLayer}
+ returnFocusRef={modelPickerTriggerRef}
+ />
+ )}
+ {runtimeFill && (
+ <CustomProviderRuntimeFillOverlay
+ state={runtimeFill}
+ runtimeNames={
+ Object.fromEntries(
+ AGENTS.map((agent) => [agent, t(TAB_META[agent].labelKey)]),
+ ) as Record<DialogAgentKind, string>
+ }
+ returnFocusRef={runtimeFillTriggerRef}
+ onClose={dismissTopmostLayer}
+ onContinue={continueRuntimeFill}
+ onBack={() => setRuntimeFill((prev) => (prev ? { ...prev, stage: 'review' } : prev))}
+ onToggleField={toggleRuntimeFillField}
+ onApply={applyRuntimeFill}
/>
)}
</div>
@@ -1841,24 +2342,42 @@ export function CustomProviderDialog({
}
/** 勾选弹层内容(搜索 + 全选/清空 + 逐行勾选;> 8 项才显示搜索框,结构对齐 ModelListPanel)。 */
-function ModelPickerOverlay({
+export function ModelPickerOverlay({
picker,
onChange,
onConfirm,
onClose,
+ returnFocusRef,
}: {
picker: ModelPickerState;
onChange: (next: ModelPickerState) => void;
onConfirm: () => void;
onClose: () => void;
+ returnFocusRef: RefObject<HTMLButtonElement | null>;
}) {
const { t } = useTranslation();
+ const contentRef = useRef<HTMLDivElement>(null);
+ const searchInputRef = useRef<HTMLInputElement>(null);
+ const primaryButtonRef = useRef<HTMLButtonElement>(null);
const q = picker.query.trim().toLowerCase();
const filtered = q
? picker.models.filter(
(m) => m.id.toLowerCase().includes(q) || m.name.toLowerCase().includes(q),
)
: picker.models;
+ useEffect(() => {
+ const onPointerDown = (event: PointerEvent) => {
+ if (event.button !== 0) return;
+ const target = event.target;
+ if (target instanceof Node && contentRef.current?.contains(target)) return;
+ // Close only the picker and consume the gesture before it can reach the form beneath it.
+ event.preventDefault();
+ event.stopPropagation();
+ onClose();
+ };
+ window.addEventListener('pointerdown', onPointerDown, { capture: true });
+ return () => window.removeEventListener('pointerdown', onPointerDown, true);
+ }, [onClose]);
const toggle = (id: string) => {
const next = new Set(picker.selected);
if (next.has(id)) next.delete(id);
@@ -1874,136 +2393,174 @@ function ModelPickerOverlay({
onChange({ ...picker, selected: next });
};
return (
- <div
- className="fixed inset-0 z-[10001] flex items-center justify-center bg-[var(--overlay-modal)]"
- onPointerDown={(event) => {
- if (event.button === 0 && event.target === event.currentTarget) onClose();
- }}
- >
- <div
- role="dialog"
- aria-modal="true"
- className={cn(
- 'flex max-h-[72vh] w-[460px] flex-col rounded-[16px]',
- 'border border-[var(--border-default)] bg-[var(--surface-elevated)]',
- 'shadow-[var(--shadow-menu)]',
- )}
- >
- {/* Header */}
- <div className="flex items-center px-5 pb-1 pt-4">
- <div className="flex min-w-0 flex-col gap-0.5">
- <h3 className="text-15 font-semibold text-[var(--settings-section-title)]">
- {t('settings.providers.custom.fetch.pickerTitle', {
- runtime: t(TAB_META[picker.agent].labelKey),
- })}
- </h3>
- <span className="text-12 text-[var(--text-tertiary)]">
- {t('settings.providers.custom.fetch.pickerCount', {
- selected: picker.selected.size,
- total: picker.models.length,
- })}
- </span>
- </div>
- </div>
- {/* 搜索(项目多才显示)+ 全选/清空(作用于当前过滤结果) */}
- <div className="flex flex-col gap-2 px-5 pt-2">
- {picker.models.length > 8 && (
- <input
- value={picker.query}
- onChange={(e) => onChange({ ...picker, query: e.target.value })}
- placeholder={t('settings.providers.custom.fetch.searchPlaceholder')}
- className={cn(
- 'h-[34px] w-full rounded-[9px] px-[11px] text-13 outline-none transition-colors',
- 'text-[var(--settings-input-text)] placeholder:text-[var(--settings-input-placeholder)]',
- 'border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] focus:border-[var(--settings-input-border-focus)]',
- )}
- style={{ userSelect: 'text', WebkitUserSelect: 'text' }}
- />
+ <Dialog.Root open onOpenChange={(open) => !open && onClose()}>
+ <Dialog.Portal>
+ <Dialog.Overlay
+ className={cn(
+ 'fixed inset-0 z-[10001] bg-[var(--overlay-modal)]',
+ 'data-[state=open]:animate-confirm-overlay-in data-[state=closed]:animate-confirm-overlay-out',
)}
- <div className="flex items-center gap-3">
- <button
- type="button"
- onClick={() => setAllFiltered(true)}
- className="text-12 font-medium text-[var(--settings-section-title)] hover:underline"
- >
- {t('settings.providers.custom.fetch.selectAll')}
- </button>
+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
+ />
+ <Dialog.Content
+ ref={contentRef}
+ aria-describedby="custom-provider-model-picker-description"
+ onEscapeKeyDown={(event) => {
+ if (event.isComposing || event.keyCode === 229) event.preventDefault();
+ }}
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ (
+ searchInputRef.current ??
+ contentRef.current?.querySelector<HTMLButtonElement>('[role="checkbox"]') ??
+ primaryButtonRef.current
+ )?.focus();
+ }}
+ onCloseAutoFocus={(event) => {
+ event.preventDefault();
+ returnFocusRef.current?.focus();
+ }}
+ className={cn(
+ 'fixed left-1/2 top-1/2 z-[10001] -translate-x-1/2 -translate-y-1/2',
+ 'flex max-h-[72vh] w-[460px] max-w-[calc(100vw-2rem)] flex-col rounded-xl outline-none',
+ 'border border-[var(--border-default)] bg-[var(--confirm-bg)]',
+ 'shadow-[var(--confirm-shadow)]',
+ 'data-[state=open]:animate-confirm-content-in data-[state=closed]:animate-confirm-content-out',
+ )}
+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
+ >
+ {/* Header */}
+ <div className="flex items-center justify-between px-5 pb-1 pt-4">
+ <div className="flex min-w-0 flex-col gap-0.5">
+ <Dialog.Title className="text-15 font-semibold text-[var(--settings-section-title)]">
+ {t('settings.providers.custom.fetch.pickerTitle', {
+ runtime: t(TAB_META[picker.agent].labelKey),
+ })}
+ </Dialog.Title>
+ <Dialog.Description
+ id="custom-provider-model-picker-description"
+ className="text-12 text-[var(--text-tertiary)]"
+ >
+ {t('settings.providers.custom.fetch.pickerCount', {
+ selected: picker.selected.size,
+ total: picker.models.length,
+ })}
+ </Dialog.Description>
+ </div>
<button
type="button"
- onClick={() => setAllFiltered(false)}
- className="text-12 font-medium text-[var(--text-secondary)] hover:underline"
+ onClick={onClose}
+ aria-label={t('settings.providers.custom.cancel')}
+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-[var(--text-tertiary)] transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
>
- {t('settings.providers.custom.fetch.clearAll')}
+ <X size={16} />
</button>
</div>
- </div>
- {/* 列表 */}
- <div className="mt-2 flex-1 overflow-y-auto px-3 pb-2">
- {filtered.length === 0 ? (
- <div className="px-3 py-6 text-center text-13 text-[var(--text-tertiary)]">
- {t('settings.providers.custom.fetch.empty')}
+ {/* 搜索(项目多才显示)+ 全选/清空(作用于当前过滤结果) */}
+ <div className="flex flex-col gap-2 px-5 pt-2">
+ {picker.models.length > 8 && (
+ <input
+ ref={searchInputRef}
+ value={picker.query}
+ onChange={(e) => onChange({ ...picker, query: e.target.value })}
+ placeholder={t('settings.providers.custom.fetch.searchPlaceholder')}
+ className={cn(
+ 'h-[34px] w-full rounded-[9px] px-[11px] text-13 outline-none transition-colors',
+ 'text-[var(--settings-input-text)] placeholder:text-[var(--settings-input-placeholder)]',
+ 'border border-[var(--settings-input-border)] bg-[var(--settings-input-bg)] focus:border-[var(--settings-input-border-focus)]',
+ 'focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ )}
+ style={{ userSelect: 'text', WebkitUserSelect: 'text' }}
+ />
+ )}
+ <div className="flex items-center gap-3">
+ <button
+ type="button"
+ onClick={() => setAllFiltered(true)}
+ className="text-12 font-medium text-[var(--settings-section-title)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ {t('settings.providers.custom.fetch.selectAll')}
+ </button>
+ <button
+ type="button"
+ onClick={() => setAllFiltered(false)}
+ className="text-12 font-medium text-[var(--text-secondary)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
+ >
+ {t('settings.providers.custom.fetch.clearAll')}
+ </button>
</div>
- ) : (
- filtered.map((m) => {
- const isSelected = picker.selected.has(m.id);
- return (
- <button
- key={m.id}
- type="button"
- role="checkbox"
- aria-checked={isSelected}
- onClick={() => toggle(m.id)}
- className="flex w-full items-center gap-2.5 rounded-[8px] px-3 py-2 text-left hover:bg-[var(--surface-hover)]"
- >
- <span
- className={cn(
- 'flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] border transition-colors',
- isSelected
- ? 'border-[var(--settings-input-border-focus)] bg-[var(--surface-elevated)] text-[var(--settings-section-title)]'
- : 'border-[var(--settings-input-border)] text-transparent',
- )}
+ </div>
+ {/* 列表 */}
+ <div className="mt-2 flex-1 overflow-y-auto px-3 pb-2">
+ {filtered.length === 0 ? (
+ <div className="px-3 py-6 text-center text-13 text-[var(--text-tertiary)]">
+ {t('settings.providers.custom.fetch.empty')}
+ </div>
+ ) : (
+ filtered.map((m) => {
+ const isSelected = picker.selected.has(m.id);
+ return (
+ <button
+ key={m.id}
+ type="button"
+ role="checkbox"
+ aria-checked={isSelected}
+ onClick={() => toggle(m.id)}
+ className="flex w-full items-center gap-2.5 rounded-[8px] px-3 py-2 text-left hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]"
>
- <Check size={12} strokeWidth={3} />
- </span>
- <span className="min-w-0 flex-1 truncate text-13 text-[var(--settings-input-text)]">
- {m.name}
- </span>
- {m.name !== m.id && (
- <span className="max-w-[45%] truncate text-11 text-[var(--text-tertiary)]">
- {m.id}
+ <span
+ className={cn(
+ 'flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] border transition-colors',
+ isSelected
+ ? 'border-[var(--settings-input-border-focus)] bg-[var(--surface-elevated)] text-[var(--settings-section-title)]'
+ : 'border-[var(--settings-input-border)] text-transparent',
+ )}
+ >
+ <Check size={12} strokeWidth={3} />
</span>
- )}
- </button>
- );
- })
- )}
- </div>
- {/* Footer */}
- <div className="flex justify-end gap-2.5 px-5 py-3.5">
- <button
- type="button"
- onClick={onClose}
- className={cn(
- 'inline-flex items-center justify-center rounded-full border bg-transparent px-5 py-2 text-13 font-medium transition-colors active:scale-[0.98]',
- 'border-[var(--confirm-btn-secondary-border)] text-[var(--confirm-btn-secondary-text)] hover:bg-[var(--confirm-btn-secondary-hover)]',
- )}
- >
- {t('settings.providers.custom.cancel')}
- </button>
- <button
- type="button"
- onClick={onConfirm}
- disabled={picker.selected.size === 0}
- className={cn(
- 'inline-flex items-center justify-center rounded-full px-5 py-2 text-13 font-medium transition-colors active:scale-[0.98]',
- 'bg-[var(--confirm-btn-primary-bg)] text-[var(--confirm-btn-primary-text)] hover:bg-[var(--confirm-btn-primary-hover)]',
- picker.selected.size === 0 && 'cursor-not-allowed opacity-50',
+ <span className="min-w-0 flex-1 truncate text-13 text-[var(--settings-input-text)]">
+ {m.name}
+ </span>
+ {m.name !== m.id && (
+ <span className="max-w-[45%] truncate text-11 text-[var(--text-tertiary)]">
+ {m.id}
+ </span>
+ )}
+ </button>
+ );
+ })
)}
- >
- {t('settings.providers.custom.fetch.confirm', { count: picker.selected.size })}
- </button>
- </div>
- </div>
- </div>
+ </div>
+ {/* Footer */}
+ <div className="flex justify-end gap-2.5 px-5 py-3.5">
+ <button
+ type="button"
+ onClick={onClose}
+ className={cn(
+ 'inline-flex items-center justify-center rounded-full border bg-transparent px-5 py-2 text-13 font-medium transition-colors active:scale-[0.98]',
+ 'border-[var(--confirm-btn-secondary-border)] text-[var(--confirm-btn-secondary-text)] hover:bg-[var(--confirm-btn-secondary-hover)]',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ )}
+ >
+ {t('settings.providers.custom.cancel')}
+ </button>
+ <button
+ ref={primaryButtonRef}
+ type="button"
+ onClick={onConfirm}
+ disabled={picker.selected.size === 0}
+ className={cn(
+ 'inline-flex items-center justify-center rounded-full px-5 py-2 text-13 font-medium transition-colors active:scale-[0.98]',
+ 'bg-[var(--confirm-btn-primary-bg)] text-[var(--confirm-btn-primary-text)] hover:bg-[var(--confirm-btn-primary-hover)]',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ picker.selected.size === 0 && 'cursor-not-allowed opacity-50',
+ )}
+ >
+ {t('settings.providers.custom.fetch.confirm', { count: picker.selected.size })}
+ </button>
+ </div>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
);
}
diff --git a/apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx b/apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx
new file mode 100644
index 0000000000..9a6160f634
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx
@@ -0,0 +1,461 @@
+import * as Dialog from '@radix-ui/react-dialog';
+import { useRef, type RefObject } from 'react';
+import { Check } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { cn } from '@/lib/utils';
+import {
+ RUNTIME_FILL_ENDPOINT_FIELDS,
+ runtimeFillFieldHasValue,
+ runtimeFillFieldsForToggle,
+ runtimeFillHeaderCount,
+ runtimeFillModelCount,
+ type RuntimeFillDraft,
+ type RuntimeFillField,
+ type RuntimeFillFieldDiff,
+ type RuntimeFillAgent,
+ type RuntimeFillTargetState,
+} from '@/lib/customProviderRuntimeFill';
+
+export interface RuntimeFillTargetPlan {
+ agent: RuntimeFillAgent;
+ draft: RuntimeFillDraft;
+ diffs: RuntimeFillFieldDiff[];
+}
+
+export interface RuntimeFillDialogState {
+ source: RuntimeFillAgent;
+ sourceDraft: RuntimeFillDraft;
+ includeApiKey: boolean;
+ oauthPiUnavailable: boolean;
+ stage: 'review' | 'confirm';
+ targets: RuntimeFillTargetPlan[];
+ selected: Partial<Record<RuntimeFillAgent, RuntimeFillField[]>>;
+}
+
+interface RuntimeFillSelectionRow {
+ key: RuntimeFillField | 'endpointBundle';
+ fields: RuntimeFillField[];
+ targetState: Exclude<RuntimeFillTargetState, 'same' | 'incompatible'>;
+}
+
+const FOCUS_RING =
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]';
+
+function runtimeFillUrlSummary(value: string, fallback: string): string {
+ const trimmed = value.trim();
+ if (!trimmed) return fallback;
+ try {
+ const url = new URL(trimmed);
+ url.username = '';
+ url.password = '';
+ url.search = '';
+ url.hash = '';
+ return url.toString().replace(/\/$/, '') || fallback;
+ } catch {
+ // Avoid echoing an unfinished string that may contain token-like URL material.
+ return fallback;
+ }
+}
+
+function runtimeFillRequestPathSummary(value: string, fallback: string): string {
+ const trimmed = value.trim();
+ if (!trimmed) return fallback;
+ try {
+ return new URL(trimmed, 'https://runtime.invalid').pathname || fallback;
+ } catch {
+ // An invalid draft may still contain a query token. Never reflect it into the DOM.
+ return fallback;
+ }
+}
+
+function selectionRows(diffs: RuntimeFillFieldDiff[]): RuntimeFillSelectionRow[] {
+ const actionable = diffs.filter(
+ (diff): diff is RuntimeFillFieldDiff & { targetState: 'empty' | 'conflict' } =>
+ diff.targetState === 'empty' || diff.targetState === 'conflict',
+ );
+ const endpointDiffs = actionable.filter((diff) =>
+ (RUNTIME_FILL_ENDPOINT_FIELDS as readonly RuntimeFillField[]).includes(diff.field),
+ );
+ const implicitClearDiffs = actionable.filter((diff) => diff.implicitClear === true);
+ const rows: RuntimeFillSelectionRow[] = [];
+ if (endpointDiffs.length > 0 || implicitClearDiffs.length > 0) {
+ const anchor = endpointDiffs[0]?.field ?? implicitClearDiffs[0].field;
+ rows.push({
+ key: 'endpointBundle',
+ fields: runtimeFillFieldsForToggle(anchor, diffs),
+ targetState: [...endpointDiffs, ...implicitClearDiffs].some(
+ (diff) => diff.targetState === 'conflict',
+ )
+ ? 'conflict'
+ : 'empty',
+ });
+ }
+ for (const diff of actionable) {
+ if ((RUNTIME_FILL_ENDPOINT_FIELDS as readonly RuntimeFillField[]).includes(diff.field))
+ continue;
+ if (diff.implicitClear === true) continue;
+ rows.push({ key: diff.field, fields: [diff.field], targetState: diff.targetState });
+ }
+ return rows;
+}
+
+export function CustomProviderRuntimeFillOverlay({
+ state,
+ runtimeNames,
+ returnFocusRef,
+ onClose,
+ onContinue,
+ onBack,
+ onToggleField,
+ onApply,
+}: {
+ state: RuntimeFillDialogState;
+ runtimeNames: Record<RuntimeFillAgent, string>;
+ returnFocusRef?: RefObject<HTMLButtonElement | null>;
+ onClose: () => void;
+ onContinue: () => void;
+ onBack: () => void;
+ onToggleField: (agent: RuntimeFillAgent, field: RuntimeFillField) => void;
+ onApply: () => void;
+}) {
+ const { t } = useTranslation();
+ const primaryButtonRef = useRef<HTMLButtonElement>(null);
+ const sourceName = runtimeNames[state.source];
+ const sourceDraft = state.sourceDraft;
+ const hasSelectedOverwrite = state.targets.some((target) =>
+ target.diffs.some(
+ (diff) =>
+ diff.targetState === 'conflict' &&
+ (state.selected[target.agent]?.includes(diff.field) ?? false),
+ ),
+ );
+ const hasSelection = state.targets.some(
+ (target) => (state.selected[target.agent]?.length ?? 0) > 0,
+ );
+
+ const summaryFor = (
+ field: RuntimeFillField,
+ draft: RuntimeFillDraft,
+ agent: RuntimeFillAgent,
+ ): string => {
+ switch (field) {
+ case 'baseUrl':
+ case 'modelsUrl':
+ return runtimeFillUrlSummary(
+ field === 'baseUrl' ? draft.baseUrl : draft.modelsUrl,
+ runtimeFillFieldHasValue(field, draft, agent)
+ ? t('settings.providers.custom.runtimeFill.values.configured')
+ : t('settings.providers.custom.runtimeFill.values.default'),
+ );
+ case 'requestPath':
+ return runtimeFillRequestPathSummary(
+ draft.requestPath,
+ t('settings.providers.custom.runtimeFill.values.default'),
+ );
+ case 'wireProtocol':
+ return draft.wireProtocol;
+ case 'apiKey':
+ return runtimeFillFieldHasValue(field, draft, agent)
+ ? t('settings.providers.custom.runtimeFill.values.secretSet')
+ : t('settings.providers.custom.runtimeFill.values.empty');
+ case 'models': {
+ const count = runtimeFillModelCount(draft);
+ return count > 0
+ ? t('settings.providers.custom.runtimeFill.values.models', { count })
+ : t('settings.providers.custom.runtimeFill.values.empty');
+ }
+ case 'headers': {
+ const count = runtimeFillHeaderCount(draft);
+ return count > 0
+ ? t('settings.providers.custom.runtimeFill.values.headers', { count })
+ : draft.headersState != null
+ ? t('settings.providers.custom.runtimeFill.values.secretSet')
+ : t('settings.providers.custom.runtimeFill.values.empty');
+ }
+ }
+ };
+
+ const fieldLabel = (field: RuntimeFillField): string =>
+ t(`settings.providers.custom.runtimeFill.fields.${field}`);
+
+ const incompatibleSummary = (
+ diff: RuntimeFillFieldDiff,
+ targetName: string,
+ ): string =>
+ t(
+ diff.incompatibilityReason === 'protocol'
+ ? 'settings.providers.custom.runtimeFill.incompatibleProtocol'
+ : diff.incompatibilityReason === 'headers'
+ ? 'settings.providers.custom.runtimeFill.incompatibleHeaders'
+ : 'settings.providers.custom.runtimeFill.incompatibleEndpoint',
+ { target: targetName },
+ );
+
+ return (
+ <Dialog.Root open onOpenChange={(open) => !open && onClose()}>
+ <Dialog.Portal>
+ <Dialog.Overlay
+ className={cn(
+ 'fixed inset-0 z-[10001] bg-[var(--overlay-modal)]',
+ 'data-[state=open]:animate-confirm-overlay-in data-[state=closed]:animate-confirm-overlay-out',
+ )}
+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
+ />
+ <Dialog.Content
+ aria-describedby="custom-provider-runtime-fill-description"
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ primaryButtonRef.current?.focus();
+ }}
+ onCloseAutoFocus={(event) => {
+ if (!returnFocusRef?.current) return;
+ event.preventDefault();
+ returnFocusRef.current.focus();
+ }}
+ className={cn(
+ 'fixed left-1/2 top-1/2 z-[10001] -translate-x-1/2 -translate-y-1/2',
+ 'flex max-h-[78vh] w-[520px] max-w-[calc(100vw-2rem)] flex-col rounded-xl',
+ 'border border-[var(--border-default)] bg-[var(--confirm-bg)]',
+ 'shadow-[var(--confirm-shadow)] outline-none',
+ 'data-[state=open]:animate-confirm-content-in data-[state=closed]:animate-confirm-content-out',
+ )}
+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
+ >
+ <div className="px-5 pb-2 pt-4">
+ <Dialog.Title className="text-15 font-semibold text-[var(--settings-section-title)]">
+ {state.stage === 'review'
+ ? t('settings.providers.custom.runtimeFill.reviewTitle')
+ : t('settings.providers.custom.runtimeFill.confirmTitle')}
+ </Dialog.Title>
+ <Dialog.Description
+ id="custom-provider-runtime-fill-description"
+ className="mt-0.5 text-12 leading-snug text-[var(--text-tertiary)]"
+ >
+ {state.stage === 'review'
+ ? t('settings.providers.custom.runtimeFill.reviewSubtitle')
+ : t('settings.providers.custom.runtimeFill.confirmSubtitle', {
+ source: sourceName,
+ })}
+ </Dialog.Description>
+ </div>
+
+ <div className="flex-1 overflow-y-auto px-5 pb-2 pt-2">
+ <div
+ className="mb-3 flex items-center justify-between gap-3 rounded-[10px] px-3 py-2.5"
+ style={{ backgroundColor: 'var(--surface)' }}
+ >
+ <span className="text-12 text-[var(--text-tertiary)]">
+ {t('settings.providers.custom.runtimeFill.source')}
+ </span>
+ <span className="text-13 font-medium text-[var(--settings-section-title)]">
+ {sourceName}
+ </span>
+ </div>
+
+ {state.oauthPiUnavailable && (
+ <p className="mb-3 rounded-[10px] border border-[var(--border-default)] px-3 py-2.5 text-11 leading-[1.5] text-[var(--text-tertiary)]">
+ {t('settings.providers.custom.runtimeFill.oauthPiUnavailable')}
+ </p>
+ )}
+
+ <div className="flex flex-col gap-4">
+ {state.targets.map((target) => {
+ const targetName = runtimeNames[target.agent];
+ const conflictCount = target.diffs.filter(
+ (diff) => diff.targetState === 'conflict',
+ ).length;
+ const actionableCount = target.diffs.filter(
+ (diff) => diff.targetState === 'empty' || diff.targetState === 'conflict',
+ ).length;
+ const incompatibleCount = target.diffs.filter(
+ (diff) => diff.targetState === 'incompatible',
+ ).length;
+ const rows = selectionRows(target.diffs);
+ return (
+ <section key={target.agent} className="flex flex-col gap-2.5">
+ <div className="flex items-center justify-between gap-3">
+ <div className="min-w-0">
+ <h4 className="truncate text-13 font-medium text-[var(--settings-section-title)]">
+ {targetName}
+ </h4>
+ <p className="mt-0.5 text-11 text-[var(--text-tertiary)]">
+ {actionableCount === 0 && incompatibleCount > 0
+ ? t('settings.providers.custom.runtimeFill.targetIncompatible', {
+ count: incompatibleCount,
+ })
+ : conflictCount > 0
+ ? t('settings.providers.custom.runtimeFill.targetConflict', {
+ count: conflictCount,
+ })
+ : t('settings.providers.custom.runtimeFill.targetReady', {
+ count: actionableCount,
+ })}
+ </p>
+ </div>
+ <span className="shrink-0 text-11 font-medium text-[var(--text-secondary)]">
+ {actionableCount === 0 && incompatibleCount > 0
+ ? t('settings.providers.custom.runtimeFill.status.incompatible')
+ : conflictCount > 0
+ ? t('settings.providers.custom.runtimeFill.status.needsConfirm')
+ : t('settings.providers.custom.runtimeFill.status.ready')}
+ </span>
+ </div>
+
+ {state.stage === 'review' ? (
+ <div className="overflow-hidden rounded-[10px] border border-[var(--border-default)]">
+ <div
+ className="grid grid-cols-[0.8fr_1fr_1fr] gap-2 px-3 py-2 text-10 text-[var(--text-tertiary)]"
+ style={{ backgroundColor: 'var(--surface)' }}
+ >
+ <span>{t('settings.providers.custom.runtimeFill.columns.field')}</span>
+ <span>{t('settings.providers.custom.runtimeFill.columns.source')}</span>
+ <span>{t('settings.providers.custom.runtimeFill.columns.target')}</span>
+ </div>
+ {target.diffs.map((diff) => {
+ const sourceSummary = summaryFor(diff.field, sourceDraft, state.source);
+ const targetSummary = summaryFor(diff.field, target.draft, target.agent);
+ return (
+ <div
+ key={diff.field}
+ className="grid grid-cols-[0.8fr_1fr_1fr] items-center gap-2 border-t border-[var(--border-default)] px-3 py-2.5 text-11"
+ >
+ <span className="font-medium text-[var(--settings-section-title)]">
+ {fieldLabel(diff.field)}
+ </span>
+ <span
+ className="truncate text-[var(--text-secondary)]"
+ title={sourceSummary}
+ >
+ {sourceSummary}
+ </span>
+ <span
+ className={cn(
+ 'truncate',
+ diff.targetState === 'same' || diff.targetState === 'incompatible'
+ ? 'text-[var(--text-tertiary)]'
+ : 'font-medium text-[var(--settings-section-title)]',
+ )}
+ title={
+ diff.targetState === 'incompatible'
+ ? incompatibleSummary(diff, targetName)
+ : targetSummary
+ }
+ >
+ {diff.targetState === 'incompatible'
+ ? incompatibleSummary(diff, targetName)
+ : targetSummary}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ ) : rows.length > 0 ? (
+ <div className="flex flex-col gap-1.5">
+ {rows.map((row) => {
+ const selected = row.fields.every((field) =>
+ state.selected[target.agent]?.includes(field),
+ );
+ return (
+ <button
+ key={row.key}
+ type="button"
+ role="checkbox"
+ aria-checked={selected}
+ onClick={() => onToggleField(target.agent, row.fields[0])}
+ className={cn(
+ 'flex w-full items-center gap-2.5 rounded-[9px] border border-[var(--border-default)] px-3 py-2.5 text-left transition-colors hover:bg-[var(--surface-hover)] active:scale-[0.98]',
+ FOCUS_RING,
+ )}
+ >
+ <span
+ className={cn(
+ 'flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] border transition-colors',
+ selected
+ ? 'border-[var(--settings-input-border-focus)] bg-[var(--surface-elevated)] text-[var(--settings-section-title)]'
+ : 'border-[var(--settings-input-border)] text-transparent',
+ )}
+ >
+ <Check size={12} strokeWidth={3} />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="block text-12 font-medium text-[var(--settings-section-title)]">
+ {row.key === 'endpointBundle'
+ ? t(
+ 'settings.providers.custom.runtimeFill.fields.endpointBundle',
+ )
+ : fieldLabel(row.key)}
+ </span>
+ <span className="mt-0.5 block truncate text-11 text-[var(--text-tertiary)]">
+ {row.key === 'apiKey'
+ ? t('settings.providers.custom.runtimeFill.secretIndependent', {
+ target: targetName,
+ })
+ : row.targetState === 'conflict'
+ ? t('settings.providers.custom.runtimeFill.overwriteCurrent')
+ : t('settings.providers.custom.runtimeFill.fillEmpty')}
+ </span>
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ ) : (
+ <p className="text-11 leading-[1.5] text-[var(--text-tertiary)]">
+ {t('settings.providers.custom.runtimeFill.noSelectableFields')}
+ </p>
+ )}
+
+ <p className="text-11 leading-[1.5] text-[var(--text-tertiary)]">
+ {t('settings.providers.custom.runtimeFill.endpointBundleNote', {
+ target: targetName,
+ })}
+ </p>
+ </section>
+ );
+ })}
+ </div>
+
+ <p className="mt-4 text-11 leading-[1.5] text-[var(--text-tertiary)]">
+ {t('settings.providers.custom.runtimeFill.independentNote')}
+ </p>
+ </div>
+
+ <div className="flex justify-end gap-2.5 px-5 py-3.5">
+ <button
+ type="button"
+ onClick={state.stage === 'review' ? onClose : onBack}
+ className={cn(
+ 'inline-flex items-center justify-center rounded-full border bg-transparent px-5 py-2 text-13 font-medium transition-colors active:scale-[0.98]',
+ 'border-[var(--confirm-btn-secondary-border)] text-[var(--confirm-btn-secondary-text)] hover:bg-[var(--confirm-btn-secondary-hover)]',
+ FOCUS_RING,
+ )}
+ >
+ {state.stage === 'review'
+ ? t('settings.providers.custom.cancel')
+ : t('settings.providers.custom.runtimeFill.back')}
+ </button>
+ <button
+ ref={primaryButtonRef}
+ type="button"
+ onClick={state.stage === 'review' ? onContinue : onApply}
+ disabled={!hasSelection}
+ className={cn(
+ 'inline-flex items-center justify-center rounded-full px-5 py-2 text-13 font-medium transition-colors active:scale-[0.98]',
+ 'bg-[var(--confirm-btn-primary-bg)] text-[var(--confirm-btn-primary-text)] hover:bg-[var(--confirm-btn-primary-hover)]',
+ FOCUS_RING,
+ !hasSelection && 'cursor-not-allowed opacity-50',
+ )}
+ >
+ {state.stage === 'review'
+ ? hasSelectedOverwrite
+ ? t('settings.providers.custom.runtimeFill.continue')
+ : t('settings.providers.custom.runtimeFill.apply')
+ : t('settings.providers.custom.runtimeFill.applyOverwrite')}
+ </button>
+ </div>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
index 465fc5c9b0..d8ff8649d8 100644
--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
@@ -1726,6 +1726,7 @@ export function ProvidersSection() {
const [dialog, setDialog] = useState<
null | { mode: 'create' } | { mode: 'edit'; config: CustomProviderConfig }
>(null);
+ const addProviderButtonRef = useRef<HTMLButtonElement>(null);
const [detections, setDetections] = useState<LocalCliDetection[]>([]);
const [rediscovering, setRediscovering] = useState(false);
const [refreshingProviderId, setRefreshingProviderId] = useState<string | null>(null);
@@ -2242,6 +2243,7 @@ export function ProvidersSection() {
style={{ borderColor: 'var(--settings-theme-card-border)' }}
>
<button
+ ref={addProviderButtonRef}
type="button"
onClick={() => setWizard({})}
className="flex h-9 w-full items-center justify-center gap-1.5 rounded-full border border-dashed text-13 font-medium transition-colors hover:bg-[var(--surface-hover)]"
@@ -2465,6 +2467,7 @@ export function ProvidersSection() {
<CustomProviderDialog
initial={dialog.mode === 'edit' ? dialog.config : undefined}
existingIds={providers.map((p) => p.id)}
+ returnFocusRef={dialog.mode === 'create' ? addProviderButtonRef : undefined}
onClose={() => setDialog(null)}
onSaved={() => {
setDialog(null);
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx
new file mode 100644
index 0000000000..eb791cce2d
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderDialogAccessibility.test.tsx
@@ -0,0 +1,332 @@
+// @vitest-environment jsdom
+import { useRef, useState } from 'react';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { CustomProviderConfig } from '@cindy/model-providers';
+
+import { CustomProviderDialog } from '../CustomProviderDialog';
+
+const customProviderMocks = vi.hoisted(() => ({
+ readCustomProviderKey: vi.fn(),
+ updateCustomProvider: vi.fn(),
+}));
+
+vi.mock('@/lib/customProviders', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/lib/customProviders')>()),
+ readCustomProviderKey: customProviderMocks.readCustomProviderKey,
+ updateCustomProvider: customProviderMocks.updateCustomProvider,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ i18n: { language: 'en' },
+ }),
+}));
+
+beforeEach(() => {
+ customProviderMocks.readCustomProviderKey.mockReset();
+ customProviderMocks.updateCustomProvider.mockReset().mockResolvedValue(undefined);
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ maker: {
+ listProviderPresets: vi.fn(async () => ({ presets: [] })),
+ testProviderConnection: vi.fn(async () => ({ ok: true, latencyMs: 1 })),
+ },
+ },
+ });
+});
+
+afterEach(cleanup);
+
+describe('CustomProviderDialog accessibility', () => {
+ it('ignores consumed and IME Escape events, then restores focus after closing', async () => {
+ function Harness() {
+ const [open, setOpen] = useState(false);
+ return (
+ <>
+ <button type="button" onClick={() => setOpen(true)}>
+ Add provider
+ </button>
+ {open && (
+ <CustomProviderDialog onSaved={() => setOpen(false)} onClose={() => setOpen(false)} />
+ )}
+ </>
+ );
+ }
+
+ const user = userEvent.setup();
+ render(<Harness />);
+ const trigger = screen.getByRole('button', { name: 'Add provider' });
+ await user.click(trigger);
+
+ const dialog = screen.getByRole('dialog', {
+ name: 'settings.providers.custom.dialog.createTitle',
+ });
+ await waitFor(() => expect(dialog.contains(document.activeElement)).toBe(true));
+
+ fireEvent.keyDown(dialog, { key: 'Escape', isComposing: true, keyCode: 229 });
+ expect(screen.getByRole('dialog')).not.toBeNull();
+
+ const consumedEscape = new KeyboardEvent('keydown', {
+ key: 'Escape',
+ bubbles: true,
+ cancelable: true,
+ });
+ consumedEscape.preventDefault();
+ fireEvent(dialog, consumedEscape);
+ expect(screen.getByRole('dialog')).not.toBeNull();
+
+ fireEvent.keyDown(dialog, { key: 'Escape' });
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ await waitFor(() => expect(document.activeElement).toBe(trigger));
+ });
+
+ it('uses a stable fallback when the immediate opener unmounts during a wizard transition', async () => {
+ function Harness() {
+ const [stage, setStage] = useState<'idle' | 'wizard' | 'dialog'>('idle');
+ const stableTriggerRef = useRef<HTMLButtonElement>(null);
+ return (
+ <>
+ <button ref={stableTriggerRef} type="button" onClick={() => setStage('wizard')}>
+ Add provider
+ </button>
+ {stage === 'wizard' && (
+ <button type="button" onClick={() => setStage('dialog')}>
+ Custom endpoint
+ </button>
+ )}
+ {stage === 'dialog' && (
+ <CustomProviderDialog
+ returnFocusRef={stableTriggerRef}
+ onSaved={() => setStage('idle')}
+ onClose={() => setStage('idle')}
+ />
+ )}
+ </>
+ );
+ }
+
+ const user = userEvent.setup();
+ render(<Harness />);
+ const stableTrigger = screen.getByRole('button', { name: 'Add provider' });
+ await user.click(stableTrigger);
+ await user.click(screen.getByRole('button', { name: 'Custom endpoint' }));
+ await user.click(screen.getByText('settings.providers.custom.cancel'));
+
+ await waitFor(() => expect(document.activeElement).toBe(stableTrigger));
+ });
+
+ it('does not submit a hydrated key as a replacement when only the endpoint changes', async () => {
+ const initial: CustomProviderConfig = {
+ id: 'existing-provider',
+ name: 'Existing provider',
+ auth: { method: 'apiKey' },
+ runtimes: {
+ codex: {
+ baseUrl: 'https://old.example.test/v1',
+ models: [{ id: 'test-model', name: 'Test Model' }],
+ },
+ },
+ };
+ customProviderMocks.readCustomProviderKey.mockResolvedValue('old-secret');
+
+ const user = userEvent.setup();
+ render(<CustomProviderDialog initial={initial} onSaved={vi.fn()} onClose={vi.fn()} />);
+ await screen.findByText('settings.providers.custom.fields.apiKeySaved');
+ const apiKey = screen.getByPlaceholderText(
+ 'settings.providers.custom.fields.apiKeyEditPlaceholder',
+ );
+ expect((apiKey as HTMLInputElement).value).toBe('old-secret');
+
+ const baseUrl = screen.getByPlaceholderText(
+ 'settings.providers.custom.fields.baseUrlPlaceholder',
+ );
+ await user.clear(baseUrl);
+ await user.type(baseUrl, 'https://new.example.test/v1');
+ await waitFor(() => expect((apiKey as HTMLInputElement).value).toBe(''));
+ expect(
+ screen.queryByText('settings.providers.custom.fields.apiKeySaved'),
+ ).toBeNull();
+ expect(apiKey.getAttribute('placeholder')).toBe(
+ 'settings.providers.custom.fields.apiKeyPlaceholder',
+ );
+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));
+
+ await waitFor(() => expect(customProviderMocks.updateCustomProvider).toHaveBeenCalledOnce());
+ expect(customProviderMocks.updateCustomProvider.mock.calls[0]?.[1]).toEqual({});
+ });
+
+ it('restores an untouched hydrated key when returning to API-key mode on the saved endpoint', async () => {
+ const initial: CustomProviderConfig = {
+ id: 'existing-provider',
+ name: 'Existing provider',
+ auth: { method: 'apiKey' },
+ runtimes: {
+ codex: {
+ baseUrl: 'https://old.example.test/v1',
+ models: [{ id: 'test-model', name: 'Test Model' }],
+ },
+ },
+ };
+ customProviderMocks.readCustomProviderKey.mockResolvedValue('old-secret');
+
+ const user = userEvent.setup();
+ render(<CustomProviderDialog initial={initial} onSaved={vi.fn()} onClose={vi.fn()} />);
+ const apiKey = await screen.findByPlaceholderText(
+ 'settings.providers.custom.fields.apiKeyEditPlaceholder',
+ );
+ const baseUrl = screen.getByPlaceholderText(
+ 'settings.providers.custom.fields.baseUrlPlaceholder',
+ );
+
+ await user.clear(baseUrl);
+ await user.type(baseUrl, 'https://new.example.test/v1');
+ await waitFor(() => expect((apiKey as HTMLInputElement).value).toBe(''));
+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.authMode.none' }));
+ await user.clear(baseUrl);
+ await user.type(baseUrl, 'https://old.example.test/v1');
+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.authMode.apiKey' }));
+
+ const restoredApiKey = await screen.findByPlaceholderText(
+ 'settings.providers.custom.fields.apiKeyEditPlaceholder',
+ );
+ expect((restoredApiKey as HTMLInputElement).value).toBe('old-secret');
+ });
+
+ it('blocks an endpoint save when that runtime key could not be read', async () => {
+ const initial: CustomProviderConfig = {
+ id: 'existing-provider',
+ name: 'Existing provider',
+ auth: { method: 'apiKey' },
+ runtimes: {
+ codex: {
+ baseUrl: 'https://old.example.test/v1',
+ models: [{ id: 'test-model', name: 'Test Model' }],
+ },
+ },
+ };
+ customProviderMocks.readCustomProviderKey.mockRejectedValue(new Error('safeStorage unavailable'));
+
+ const user = userEvent.setup();
+ render(<CustomProviderDialog initial={initial} onSaved={vi.fn()} onClose={vi.fn()} />);
+ await waitFor(() => expect(customProviderMocks.readCustomProviderKey).toHaveBeenCalled());
+
+ const baseUrl = screen.getByPlaceholderText(
+ 'settings.providers.custom.fields.baseUrlPlaceholder',
+ );
+ await user.clear(baseUrl);
+ await user.type(baseUrl, 'https://new.example.test/v1');
+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));
+
+ await waitFor(() => expect(customProviderMocks.updateCustomProvider).not.toHaveBeenCalled());
+ });
+
+ it('does not send a hydrated key to a changed endpoint during an ad-hoc test', async () => {
+ const testProviderConnection = vi
+ .fn<(request: unknown) => Promise<{ ok: true; latencyMs: number }>>()
+ .mockResolvedValue({ ok: true, latencyMs: 1 });
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ maker: {
+ listProviderPresets: vi.fn(async () => ({ presets: [] })),
+ testProviderConnection,
+ },
+ },
+ });
+ const initial: CustomProviderConfig = {
+ id: 'existing-provider',
+ name: 'Existing provider',
+ auth: { method: 'apiKey' },
+ runtimes: {
+ codex: {
+ baseUrl: 'https://old.example.test/v1',
+ models: [{ id: 'test-model', name: 'Test Model' }],
+ },
+ },
+ };
+ customProviderMocks.readCustomProviderKey.mockResolvedValue('old-secret');
+
+ const user = userEvent.setup();
+ render(<CustomProviderDialog initial={initial} onSaved={vi.fn()} onClose={vi.fn()} />);
+ await screen.findByText('settings.providers.custom.fields.apiKeySaved');
+ const baseUrl = screen.getByPlaceholderText(
+ 'settings.providers.custom.fields.baseUrlPlaceholder',
+ );
+ await user.clear(baseUrl);
+ await user.type(baseUrl, 'https://new.example.test/v1');
+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.test.button' }));
+
+ await waitFor(() => expect(testProviderConnection).toHaveBeenCalledOnce());
+ expect(testProviderConnection.mock.calls[0]?.[0]).toMatchObject({
+ kind: 'adhoc',
+ spec: expect.objectContaining({
+ baseUrl: 'https://new.example.test/v1',
+ apiKey: null,
+ }),
+ });
+ });
+
+ it('hides and strips a legacy request path from a Pi runtime', async () => {
+ const initial: CustomProviderConfig = {
+ id: 'legacy-pi-provider',
+ name: 'Legacy Pi provider',
+ auth: { method: 'apiKey' },
+ runtimes: {
+ pi: {
+ baseUrl: 'https://pi.example.test/v1',
+ requestPath: '/legacy-infer',
+ models: [{ id: 'pi-model', name: 'Pi Model' }],
+ },
+ },
+ };
+ customProviderMocks.readCustomProviderKey.mockResolvedValue(null);
+
+ const user = userEvent.setup();
+ render(<CustomProviderDialog initial={initial} onSaved={vi.fn()} onClose={vi.fn()} />);
+ await waitFor(() => expect(customProviderMocks.readCustomProviderKey).toHaveBeenCalled());
+
+ expect(
+ screen.queryByText('settings.providers.custom.fields.requestPath'),
+ ).toBeNull();
+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));
+
+ await waitFor(() => expect(customProviderMocks.updateCustomProvider).toHaveBeenCalledOnce());
+ expect(
+ customProviderMocks.updateCustomProvider.mock.calls[0]?.[0].runtimes.pi?.requestPath,
+ ).toBeUndefined();
+ });
+
+ it('submits an explicitly edited key as the endpoint replacement', async () => {
+ const initial: CustomProviderConfig = {
+ id: 'existing-provider',
+ name: 'Existing provider',
+ auth: { method: 'apiKey' },
+ runtimes: {
+ codex: {
+ baseUrl: 'https://old.example.test/v1',
+ models: [{ id: 'test-model', name: 'Test Model' }],
+ },
+ },
+ };
+ customProviderMocks.readCustomProviderKey.mockResolvedValue('old-secret');
+
+ const user = userEvent.setup();
+ render(<CustomProviderDialog initial={initial} onSaved={vi.fn()} onClose={vi.fn()} />);
+ const apiKey = await screen.findByPlaceholderText(
+ 'settings.providers.custom.fields.apiKeyEditPlaceholder',
+ );
+
+ await user.clear(apiKey);
+ await user.type(apiKey, 'replacement-secret');
+ await user.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));
+
+ await waitFor(() => expect(customProviderMocks.updateCustomProvider).toHaveBeenCalledOnce());
+ expect(customProviderMocks.updateCustomProvider.mock.calls[0]?.[1]).toEqual({
+ codex: 'replacement-secret',
+ });
+ });
+});
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderModelPickerOverlay.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderModelPickerOverlay.test.tsx
new file mode 100644
index 0000000000..6bd46ab2d7
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderModelPickerOverlay.test.tsx
@@ -0,0 +1,104 @@
+// @vitest-environment jsdom
+import { useRef, useState } from 'react';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { ModelPickerOverlay } from '../CustomProviderDialog';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+afterEach(cleanup);
+
+const models = Array.from({ length: 9 }, (_, index) => ({
+ id: `model-${index}`,
+ name: `Model ${index}`,
+}));
+
+describe('ModelPickerOverlay', () => {
+ it('focuses search, traps focus, closes on Escape, and restores the trigger', async () => {
+ const onClose = vi.fn();
+
+ function Harness() {
+ const [open, setOpen] = useState(true);
+ const [picker, setPicker] = useState<{
+ agent: 'claude-code' | 'codex' | 'pi';
+ models: typeof models;
+ selected: Set<string>;
+ query: string;
+ }>({
+ agent: 'pi',
+ models,
+ selected: new Set(['model-0']),
+ query: '',
+ });
+ const triggerRef = useRef<HTMLButtonElement>(null);
+
+ return (
+ <>
+ <button ref={triggerRef} type="button">
+ Fetch models
+ </button>
+ {open && (
+ <ModelPickerOverlay
+ picker={picker}
+ onChange={setPicker}
+ onConfirm={() => {}}
+ onClose={() => {
+ onClose();
+ setOpen(false);
+ }}
+ returnFocusRef={triggerRef}
+ />
+ )}
+ </>
+ );
+ }
+
+ const user = userEvent.setup();
+ render(<Harness />);
+
+ await waitFor(() =>
+ expect(document.activeElement).toBe(
+ screen.getByPlaceholderText('settings.providers.custom.fetch.searchPlaceholder'),
+ ),
+ );
+
+ fireEvent.keyDown(document, { key: 'Escape', isComposing: true, keyCode: 229 });
+ expect(onClose).not.toHaveBeenCalled();
+ expect(screen.getByRole('dialog')).not.toBeNull();
+
+ await user.tab({ shift: true });
+ expect(screen.getByRole('dialog').contains(document.activeElement)).toBe(true);
+
+ fireEvent.keyDown(document, { key: 'Escape' });
+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
+ await waitFor(() =>
+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Fetch models' })),
+ );
+ });
+
+ it('focuses the first model when the short list has no search field', async () => {
+ const triggerRef = { current: null };
+
+ render(
+ <ModelPickerOverlay
+ picker={{
+ agent: 'codex',
+ models: models.slice(0, 2),
+ selected: new Set(),
+ query: '',
+ }}
+ onChange={() => {}}
+ onConfirm={() => {}}
+ onClose={() => {}}
+ returnFocusRef={triggerRef}
+ />,
+ );
+
+ const firstModel = screen.getAllByRole('checkbox')[0];
+ await waitFor(() => expect(document.activeElement).toBe(firstModel));
+ });
+});
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderRuntimeFillOverlay.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderRuntimeFillOverlay.test.tsx
new file mode 100644
index 0000000000..bcb3aa8bac
--- /dev/null
+++ b/apps/desktop/src/renderer/components/settings/__tests__/CustomProviderRuntimeFillOverlay.test.tsx
@@ -0,0 +1,303 @@
+// @vitest-environment jsdom
+import { useRef, useState } from 'react';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ CustomProviderRuntimeFillOverlay,
+ type RuntimeFillDialogState,
+} from '../CustomProviderRuntimeFillOverlay';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+afterEach(cleanup);
+
+function draft(overrides: Partial<RuntimeFillDialogState['sourceDraft']> = {}) {
+ return {
+ baseUrl: 'https://source.example/v1',
+ requestPath: '',
+ apiKey: '',
+ wireProtocol: 'openai-chat' as const,
+ models: [],
+ headers: [],
+ modelsUrl: '',
+ ...overrides,
+ };
+}
+
+const runtimeNames = {
+ 'claude-code': 'Claude Code',
+ codex: 'Codex',
+ pi: 'Pi',
+};
+
+function state(overrides: Partial<RuntimeFillDialogState> = {}): RuntimeFillDialogState {
+ return {
+ source: 'codex',
+ sourceDraft: draft(),
+ includeApiKey: true,
+ oauthPiUnavailable: false,
+ stage: 'review',
+ targets: [
+ {
+ agent: 'pi',
+ draft: draft({
+ baseUrl: 'https://target.example/v1',
+ requestPath: '/responses',
+ }),
+ diffs: [
+ { field: 'baseUrl', targetState: 'conflict' },
+ { field: 'requestPath', targetState: 'conflict' },
+ { field: 'wireProtocol', targetState: 'same' },
+ ],
+ },
+ ],
+ selected: { pi: ['baseUrl', 'requestPath', 'wireProtocol'] },
+ ...overrides,
+ };
+}
+
+function renderOverlay(value: RuntimeFillDialogState, onClose = vi.fn()) {
+ return render(
+ <CustomProviderRuntimeFillOverlay
+ state={value}
+ runtimeNames={runtimeNames}
+ onClose={onClose}
+ onContinue={() => {}}
+ onBack={() => {}}
+ onToggleField={() => {}}
+ onApply={() => {}}
+ />,
+ );
+}
+
+describe('CustomProviderRuntimeFillOverlay', () => {
+ it('never reflects request-path query credentials into text or title attributes', () => {
+ renderOverlay(
+ state({
+ sourceDraft: draft({ requestPath: '/infer?api_key=source-secret' }),
+ targets: [
+ {
+ agent: 'pi',
+ draft: draft({ requestPath: '/infer?token=target-secret' }),
+ diffs: [{ field: 'requestPath', targetState: 'conflict' }],
+ },
+ ],
+ selected: { pi: ['requestPath'] },
+ }),
+ );
+
+ expect(document.body.textContent).toContain('/infer');
+ expect(document.body.innerHTML).not.toContain('source-secret');
+ expect(document.body.innerHTML).not.toContain('target-secret');
+ });
+
+ it('renders the endpoint tuple as one checkbox in the confirmation stage', () => {
+ renderOverlay(state({ stage: 'confirm' }));
+
+ const choices = screen.getAllByRole('checkbox');
+ expect(choices).toHaveLength(1);
+ expect(choices[0].textContent).toContain(
+ 'settings.providers.custom.runtimeFill.fields.endpointBundle',
+ );
+ expect(choices[0].getAttribute('aria-checked')).toBe('true');
+ });
+
+ it('keeps implicit endpoint clears in the same confirmation checkbox', () => {
+ renderOverlay(
+ state({
+ stage: 'confirm',
+ targets: [
+ {
+ agent: 'pi',
+ draft: draft({ modelsUrl: 'https://target.example/models' }),
+ diffs: [
+ { field: 'baseUrl', targetState: 'same' },
+ { field: 'requestPath', targetState: 'same' },
+ { field: 'wireProtocol', targetState: 'same' },
+ { field: 'modelsUrl', targetState: 'conflict', implicitClear: true },
+ ],
+ },
+ ],
+ selected: { pi: ['baseUrl', 'requestPath', 'wireProtocol', 'modelsUrl'] },
+ }),
+ );
+
+ const choices = screen.getAllByRole('checkbox');
+ expect(choices).toHaveLength(1);
+ expect(choices[0].textContent).toContain(
+ 'settings.providers.custom.runtimeFill.fields.endpointBundle',
+ );
+ });
+
+ it('shows protocol incompatibility instead of silently hiding the skipped field', () => {
+ renderOverlay(
+ state({
+ targets: [
+ {
+ agent: 'claude-code',
+ draft: draft({ wireProtocol: 'anthropic-messages' }),
+ diffs: [
+ {
+ field: 'wireProtocol',
+ targetState: 'incompatible',
+ incompatibilityReason: 'protocol',
+ },
+ ],
+ },
+ ],
+ selected: {},
+ }),
+ );
+
+ expect(
+ screen.getByText('settings.providers.custom.runtimeFill.incompatibleProtocol'),
+ ).not.toBeNull();
+ expect(screen.queryByRole('checkbox')).toBeNull();
+ });
+
+ it('does not mislabel endpoint incompatibility as an unsupported protocol', () => {
+ renderOverlay(
+ state({
+ targets: [
+ {
+ agent: 'pi',
+ draft: draft(),
+ diffs: [
+ {
+ field: 'requestPath',
+ targetState: 'incompatible',
+ incompatibilityReason: 'endpoint',
+ },
+ ],
+ },
+ ],
+ selected: {},
+ }),
+ );
+
+ expect(
+ screen.getByText('settings.providers.custom.runtimeFill.incompatibleEndpoint'),
+ ).not.toBeNull();
+ expect(
+ screen.queryByText('settings.providers.custom.runtimeFill.incompatibleProtocol'),
+ ).toBeNull();
+ });
+
+ it('shows hidden target headers as configured without exposing values', () => {
+ renderOverlay(
+ state({
+ targets: [
+ {
+ agent: 'pi',
+ draft: draft({ headersState: 'configured' }),
+ diffs: [{ field: 'headers', targetState: 'conflict', implicitClear: true }],
+ },
+ ],
+ selected: { pi: ['headers'] },
+ }),
+ );
+
+ expect(screen.getByText('settings.providers.custom.runtimeFill.values.secretSet')).not.toBeNull();
+ });
+
+ it('does not present unreadable target headers as empty', () => {
+ renderOverlay(
+ state({
+ sourceDraft: draft({ headersState: 'unknown' }),
+ targets: [
+ {
+ agent: 'pi',
+ draft: draft(),
+ diffs: [
+ {
+ field: 'headers',
+ targetState: 'incompatible',
+ incompatibilityReason: 'headers',
+ },
+ ],
+ },
+ ],
+ selected: {},
+ }),
+ );
+
+ expect(screen.getByText('settings.providers.custom.runtimeFill.values.secretSet')).not.toBeNull();
+ });
+
+ it('explains that main-only source headers cannot be copied', () => {
+ renderOverlay(
+ state({
+ sourceDraft: draft({ headersState: 'configured' }),
+ targets: [
+ {
+ agent: 'pi',
+ draft: draft(),
+ diffs: [
+ {
+ field: 'headers',
+ targetState: 'incompatible',
+ incompatibilityReason: 'headers',
+ },
+ ],
+ },
+ ],
+ selected: {},
+ }),
+ );
+
+ expect(
+ screen.getByText('settings.providers.custom.runtimeFill.incompatibleHeaders'),
+ ).not.toBeNull();
+ });
+
+ it('focuses the primary action, traps keyboard focus, closes on Escape, and restores focus', async () => {
+ const onClose = vi.fn();
+
+ function Harness() {
+ const [open, setOpen] = useState(true);
+ const triggerRef = useRef<HTMLButtonElement>(null);
+ return (
+ <>
+ <button ref={triggerRef} type="button">
+ Open fill
+ </button>
+ {open && (
+ <CustomProviderRuntimeFillOverlay
+ state={state()}
+ runtimeNames={runtimeNames}
+ returnFocusRef={triggerRef}
+ onClose={() => {
+ onClose();
+ setOpen(false);
+ }}
+ onContinue={() => {}}
+ onBack={() => {}}
+ onToggleField={() => {}}
+ onApply={() => {}}
+ />
+ )}
+ </>
+ );
+ }
+
+ const user = userEvent.setup();
+ render(<Harness />);
+ const primary = screen.getByRole('button', {
+ name: 'settings.providers.custom.runtimeFill.continue',
+ });
+ await waitFor(() => expect(document.activeElement).toBe(primary));
+
+ await user.tab();
+ expect(screen.getByRole('dialog').contains(document.activeElement)).toBe(true);
+
+ fireEvent.keyDown(document, { key: 'Escape' });
+ await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
+ await waitFor(() =>
+ expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Open fill' })),
+ );
+ });
+});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 498307d6da..8fe8fb11fc 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1468,6 +1468,67 @@
},
"advanced": {
"label": "Advanced (models / headers)"
+ },
+ "runtimeFill": {
+ "action": "Fill other runtimes",
+ "reviewTitle": "Fill other runtimes",
+ "reviewSubtitle": "Review field differences first. Each runtime remains independently saved.",
+ "confirmTitle": "Confirm overwrites",
+ "confirmSubtitle": "Choose the fields to copy from {{source}}.",
+ "source": "Source",
+ "columns": { "field": "Field", "source": "Source value", "target": "Current value" },
+ "fields": {
+ "endpointBundle": "Endpoint and API protocol",
+ "baseUrl": "Base URL",
+ "requestPath": "Request path",
+ "wireProtocol": "API protocol",
+ "apiKey": "API key",
+ "models": "Models",
+ "headers": "Advanced headers",
+ "modelsUrl": "Model list endpoint"
+ },
+ "values": {
+ "empty": "Empty",
+ "default": "Default / inferred",
+ "configured": "Configured",
+ "secretSet": "Set (value hidden)",
+ "models_one": "{{count}} model",
+ "models_other": "{{count}} models",
+ "headers_one": "{{count}} header",
+ "headers_other": "{{count}} headers"
+ },
+ "targetConflict_one": "{{count}} existing field differs",
+ "targetConflict_other": "{{count}} existing fields differ",
+ "targetReady_one": "{{count}} field can be filled",
+ "targetReady_other": "{{count}} fields can be filled",
+ "targetIncompatible_one": "{{count}} field is not compatible",
+ "targetIncompatible_other": "{{count}} fields are not compatible",
+ "status": {
+ "needsConfirm": "Needs confirmation",
+ "ready": "Ready to fill",
+ "incompatible": "Not compatible"
+ },
+ "secretIndependent": "Copy to {{target}}'s separate local key",
+ "overwriteCurrent": "Replaces the current value",
+ "fillEmpty": "Fills the currently empty field",
+ "incompatibleProtocol": "Not copied: {{target}} does not support this API protocol",
+ "incompatibleHeaders": "Not copied: {{target}} needs headers that cannot be copied here",
+ "incompatibleEndpoint": "Not copied: {{target}} cannot use this endpoint configuration",
+ "noSelectableFields": "No compatible fields are available for this runtime.",
+ "endpointBundleNote": "For {{target}}, the Base URL, request path, and API protocol are copied together so they cannot become mismatched.",
+ "oauthPiUnavailable": "Pi is excluded because its native runtime does not support OAuth providers.",
+ "independentNote": "This is a one-time fill. Later edits never sync between runtime tabs. API keys continue to use separate safeStorage records.",
+ "continue": "Review overwrites",
+ "apply": "Confirm fill",
+ "applyOverwrite": "Overwrite and fill",
+ "back": "Back to differences",
+ "nothingToFill": "Fill in reusable fields for the current runtime first",
+ "alreadySame": "The fillable fields already match in the other runtimes",
+ "loadingKeys": "Wait for saved API keys to finish loading before filling other runtimes",
+ "keysUnavailable": "Saved API keys could not be loaded, so filling other runtimes is unavailable",
+ "modelsBusy": "Finish fetching or selecting models before filling other runtimes",
+ "noCompatibleFields": "The other runtimes do not support the reusable fields in the current runtime",
+ "filledToast": "Filled {{targets}}; each runtime remains independent"
}
},
"models": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 636e50d14c..68ac566b0a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1468,6 +1468,67 @@
},
"advanced": {
"label": "詳細設定(モデル / リクエストヘッダー)"
+ },
+ "runtimeFill": {
+ "action": "他の runtime に入力",
+ "reviewTitle": "他の runtime に入力",
+ "reviewSubtitle": "差分を確認してください。各 runtime は個別に保存されます。",
+ "confirmTitle": "上書きを確認",
+ "confirmSubtitle": "{{source}} からコピーする項目を選択してください。",
+ "source": "コピー元",
+ "columns": { "field": "項目", "source": "コピー元", "target": "現在値" },
+ "fields": {
+ "endpointBundle": "エンドポイントと API プロトコル",
+ "baseUrl": "ベース URL",
+ "requestPath": "リクエストパス",
+ "wireProtocol": "API プロトコル",
+ "apiKey": "API キー",
+ "models": "モデル",
+ "headers": "追加ヘッダー",
+ "modelsUrl": "モデル一覧 URL"
+ },
+ "values": {
+ "empty": "空",
+ "default": "既定/推測",
+ "configured": "設定済み",
+ "secretSet": "設定済み(非表示)",
+ "models_one": "{{count}} モデル",
+ "models_other": "{{count}} モデル",
+ "headers_one": "{{count}} ヘッダー",
+ "headers_other": "{{count}} ヘッダー"
+ },
+ "targetConflict_one": "既存の {{count}} 項目が異なります",
+ "targetConflict_other": "既存の {{count}} 項目が異なります",
+ "targetReady_one": "{{count}} 項目を入力できます",
+ "targetReady_other": "{{count}} 項目を入力できます",
+ "targetIncompatible_one": "{{count}} 項目は互換性がありません",
+ "targetIncompatible_other": "{{count}} 項目は互換性がありません",
+ "status": {
+ "needsConfirm": "確認が必要",
+ "ready": "入力可能",
+ "incompatible": "互換性なし"
+ },
+ "secretIndependent": "{{target}} の個別キーとしてコピー",
+ "overwriteCurrent": "現在値を置換",
+ "fillEmpty": "空の項目を入力",
+ "incompatibleProtocol": "コピーされません:{{target}} はこの API プロトコルをサポートしていません",
+ "incompatibleHeaders": "コピーされません:{{target}} にはここで安全にコピーできないヘッダーが必要です",
+ "incompatibleEndpoint": "コピーされません:{{target}} ではこのエンドポイント設定を使用できません",
+ "noSelectableFields": "この runtime に入力できる互換項目はありません。",
+ "endpointBundleNote": "{{target}} には、ベース URL、リクエストパス、API プロトコルを一括コピーし、不整合を防ぎます。",
+ "oauthPiUnavailable": "Pi のネイティブ runtime は OAuth プロバイダーをサポートしないため、入力先から除外されます。",
+ "independentNote": "これは一度だけの入力です。以後 runtime 間で同期されません。キーは個別の safeStorage に保存されます。",
+ "continue": "上書きを確認",
+ "apply": "入力を確定",
+ "applyOverwrite": "上書きして入力",
+ "back": "差分に戻る",
+ "nothingToFill": "現在の runtime に再利用可能な項目を入力してください",
+ "alreadySame": "他の runtime と同じです",
+ "loadingKeys": "保存済み API キーの読み込み完了後に、他の runtime へ入力してください",
+ "keysUnavailable": "保存済み API キーを読み込めなかったため、ほかの runtime には入力できません",
+ "modelsBusy": "モデル一覧の取得または選択を完了してから、他の runtime へ入力してください",
+ "noCompatibleFields": "現在の runtime の再利用可能な項目は、他の runtime でサポートされていません",
+ "filledToast": "{{targets}} に入力しました"
}
},
"models": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index bafdbd0f1e..a3c5748e3d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1468,6 +1468,67 @@
},
"advanced": {
"label": "고급 설정 (모델 / 요청 헤더)"
+ },
+ "runtimeFill": {
+ "action": "다른 runtime 채우기",
+ "reviewTitle": "다른 runtime 채우기",
+ "reviewSubtitle": "필드 차이를 먼저 확인하세요. 각 runtime은 독립적으로 저장됩니다.",
+ "confirmTitle": "덮어쓰기 확인",
+ "confirmSubtitle": "{{source}}에서 복사할 필드를 선택하세요.",
+ "source": "원본",
+ "columns": { "field": "필드", "source": "원본 값", "target": "현재 값" },
+ "fields": {
+ "endpointBundle": "엔드포인트 및 API 프로토콜",
+ "baseUrl": "기본 URL",
+ "requestPath": "요청 경로",
+ "wireProtocol": "API 프로토콜",
+ "apiKey": "API 키",
+ "models": "모델",
+ "headers": "추가 헤더",
+ "modelsUrl": "모델 목록 엔드포인트"
+ },
+ "values": {
+ "empty": "비어 있음",
+ "default": "기본/추론",
+ "configured": "설정됨",
+ "secretSet": "설정됨(숨김)",
+ "models_one": "모델 {{count}}개",
+ "models_other": "모델 {{count}}개",
+ "headers_one": "헤더 {{count}}개",
+ "headers_other": "헤더 {{count}}개"
+ },
+ "targetConflict_one": "기존 필드 {{count}}개가 다름",
+ "targetConflict_other": "기존 필드 {{count}}개가 다름",
+ "targetReady_one": "필드 {{count}}개를 채울 수 있음",
+ "targetReady_other": "필드 {{count}}개를 채울 수 있음",
+ "targetIncompatible_one": "필드 {{count}}개가 호환되지 않음",
+ "targetIncompatible_other": "필드 {{count}}개가 호환되지 않음",
+ "status": {
+ "needsConfirm": "확인 필요",
+ "ready": "채울 준비됨",
+ "incompatible": "호환되지 않음"
+ },
+ "secretIndependent": "{{target}}의 별도 로컬 키로 복사",
+ "overwriteCurrent": "현재 값 대체",
+ "fillEmpty": "빈 필드 채우기",
+ "incompatibleProtocol": "복사되지 않음: {{target}}에서 이 API 프로토콜을 지원하지 않습니다",
+ "incompatibleHeaders": "복사되지 않음: {{target}}에 필요한 헤더는 여기서 안전하게 복사할 수 없습니다",
+ "incompatibleEndpoint": "복사되지 않음: {{target}}에서는 이 엔드포인트 설정을 사용할 수 없습니다",
+ "noSelectableFields": "이 runtime에 호환되는 필드가 없습니다.",
+ "endpointBundleNote": "{{target}}에는 기본 URL, 요청 경로, API 프로토콜을 함께 복사하여 엔드포인트 불일치를 방지합니다.",
+ "oauthPiUnavailable": "Pi 네이티브 runtime은 OAuth 제공자를 지원하지 않아 채우기 대상에서 제외됩니다.",
+ "independentNote": "일회성 채우기입니다. 이후 runtime 간 동기화되지 않으며 키는 별도 safeStorage에 저장됩니다.",
+ "continue": "덮어쓰기 검토",
+ "apply": "채우기 확인",
+ "applyOverwrite": "덮어쓰고 채우기",
+ "back": "차이로 돌아가기",
+ "nothingToFill": "현재 runtime에 재사용 가능한 필드를 먼저 입력하세요",
+ "alreadySame": "다른 runtime과 이미 일치합니다",
+ "loadingKeys": "저장된 API 키를 모두 불러온 후 다른 runtime을 채우세요",
+ "keysUnavailable": "저장된 API 키를 불러오지 못해 다른 runtime을 채울 수 없습니다",
+ "modelsBusy": "모델 목록 가져오기 또는 선택을 완료한 후 다른 runtime을 채우세요",
+ "noCompatibleFields": "현재 runtime의 재사용 가능한 필드를 다른 runtime에서 지원하지 않습니다",
+ "filledToast": "{{targets}}에 채웠습니다"
}
},
"models": {
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 4fc08a814f..085bf96024 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1468,6 +1468,63 @@
},
"advanced": {
"label": "高级配置(模型 / 请求头)"
+ },
+ "runtimeFill": {
+ "action": "填充其他 runtime",
+ "reviewTitle": "填充其他 runtime",
+ "reviewSubtitle": "先查看字段差异;每个 runtime 仍独立保存。",
+ "confirmTitle": "确认覆盖",
+ "confirmSubtitle": "选择从 {{source}} 复制的字段。",
+ "source": "来源",
+ "columns": { "field": "字段", "source": "来源值", "target": "当前值" },
+ "fields": {
+ "endpointBundle": "端点与 API 协议",
+ "baseUrl": "基础 URL",
+ "requestPath": "请求路径",
+ "wireProtocol": "API 协议",
+ "apiKey": "API 密钥",
+ "models": "模型",
+ "headers": "高级请求头",
+ "modelsUrl": "模型列表端点"
+ },
+ "values": {
+ "empty": "空",
+ "default": "默认/推断",
+ "configured": "已配置",
+ "secretSet": "已设置(值已隐藏)",
+ "models_one": "{{count}} 个模型",
+ "models_other": "{{count}} 个模型",
+ "headers_one": "{{count}} 个请求头",
+ "headers_other": "{{count}} 个请求头"
+ },
+ "targetConflict_one": "{{count}} 个已有字段不同",
+ "targetConflict_other": "{{count}} 个已有字段不同",
+ "targetReady_one": "可填充 {{count}} 个字段",
+ "targetReady_other": "可填充 {{count}} 个字段",
+ "targetIncompatible_one": "{{count}} 个字段不兼容",
+ "targetIncompatible_other": "{{count}} 个字段不兼容",
+ "status": { "needsConfirm": "需要确认", "ready": "可以填充", "incompatible": "不兼容" },
+ "secretIndependent": "复制到 {{target}} 的独立本地密钥",
+ "overwriteCurrent": "替换当前值",
+ "fillEmpty": "填充当前空字段",
+ "incompatibleProtocol": "未复制:{{target}} 不支持此 API 协议",
+ "incompatibleHeaders": "未复制:{{target}} 需要无法在此安全复制的请求头",
+ "incompatibleEndpoint": "未复制:{{target}} 无法使用此端点配置",
+ "noSelectableFields": "此 runtime 没有可兼容填充的字段。",
+ "endpointBundleNote": "向 {{target}} 填充时,基础 URL、请求路径和 API 协议会成组复制,避免端点组合不匹配。",
+ "oauthPiUnavailable": "Pi 原生 runtime 不支持 OAuth 供应商,因此不会作为填充目标。",
+ "independentNote": "这是一次性填充;之后各 runtime 不会同步。API 密钥仍使用独立 safeStorage 记录。",
+ "continue": "查看覆盖项",
+ "apply": "确认填充",
+ "applyOverwrite": "覆盖并填充",
+ "back": "返回差异",
+ "nothingToFill": "请先填写当前 runtime 的可复用字段",
+ "alreadySame": "其他 runtime 中的可填充字段已经一致",
+ "loadingKeys": "请等待已保存的 API 密钥加载完成后再填充其他 runtime",
+ "keysUnavailable": "无法读取已保存的 API 密钥,暂时无法填充其他 runtime",
+ "modelsBusy": "请先完成正在进行的模型列表获取或选择,再填充其他 runtime",
+ "noCompatibleFields": "其他 runtime 不支持当前 runtime 中可复用的字段",
+ "filledToast": "已填充 {{targets}};各 runtime 仍独立"
}
},
"models": {
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 cbc3618afb..d0a3a369dc 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -1445,6 +1445,63 @@
"empty": "沒有匹配的模型",
"confirm": "填入所選模型({{count}})"
},
+ "runtimeFill": {
+ "action": "填入其他 Runtime",
+ "reviewTitle": "填入其他 Runtime",
+ "reviewSubtitle": "先查看欄位差異;每個 Runtime 仍會獨立儲存。",
+ "confirmTitle": "確認覆蓋",
+ "confirmSubtitle": "選擇要從 {{source}} 複製的欄位。",
+ "source": "來源",
+ "columns": { "field": "欄位", "source": "來源值", "target": "目前值" },
+ "fields": {
+ "endpointBundle": "端點與 API 協議",
+ "baseUrl": "基礎 URL",
+ "requestPath": "請求路徑",
+ "wireProtocol": "API 協議",
+ "apiKey": "API 金鑰",
+ "models": "模型",
+ "headers": "進階請求標頭",
+ "modelsUrl": "模型列表端點"
+ },
+ "values": {
+ "empty": "空白",
+ "default": "預設/推斷",
+ "configured": "已設定",
+ "secretSet": "已設定(值已隱藏)",
+ "models_one": "{{count}} 個模型",
+ "models_other": "{{count}} 個模型",
+ "headers_one": "{{count}} 個請求標頭",
+ "headers_other": "{{count}} 個請求標頭"
+ },
+ "targetConflict_one": "{{count}} 個既有欄位不同",
+ "targetConflict_other": "{{count}} 個既有欄位不同",
+ "targetReady_one": "可填入 {{count}} 個欄位",
+ "targetReady_other": "可填入 {{count}} 個欄位",
+ "targetIncompatible_one": "{{count}} 個欄位不相容",
+ "targetIncompatible_other": "{{count}} 個欄位不相容",
+ "status": { "needsConfirm": "需要確認", "ready": "可以填入", "incompatible": "不相容" },
+ "secretIndependent": "複製到 {{target}} 的獨立本機金鑰",
+ "overwriteCurrent": "取代目前值",
+ "fillEmpty": "填入目前空白欄位",
+ "incompatibleProtocol": "未複製:{{target}} 不支援此 API 協議",
+ "incompatibleHeaders": "未複製:{{target}} 需要無法在此安全複製的請求標頭",
+ "incompatibleEndpoint": "未複製:{{target}} 無法使用此端點設定",
+ "noSelectableFields": "此 Runtime 沒有可相容填入的欄位。",
+ "endpointBundleNote": "填入 {{target}} 時,基礎 URL、請求路徑和 API 協議會成組複製,避免端點組合不符。",
+ "oauthPiUnavailable": "Pi 原生 Runtime 不支援 OAuth 供應商,因此不會作為填入目標。",
+ "independentNote": "這是一次性填入;之後各 Runtime 不會同步。API 金鑰仍使用獨立 safeStorage 記錄。",
+ "continue": "查看覆蓋項目",
+ "apply": "確認填入",
+ "applyOverwrite": "覆蓋並填入",
+ "back": "返回差異",
+ "nothingToFill": "請先填寫目前 Runtime 的可重用欄位",
+ "alreadySame": "其他 Runtime 中可填入的欄位已經一致",
+ "loadingKeys": "請等待已儲存的 API 金鑰載入完成,再填入其他 Runtime",
+ "keysUnavailable": "無法讀取已儲存的 API 金鑰,暫時無法填入其他 runtime",
+ "modelsBusy": "請先完成正在進行的模型列表獲取或選擇,再填入其他 Runtime",
+ "noCompatibleFields": "其他 Runtime 不支援目前 Runtime 中可重用的欄位",
+ "filledToast": "已填入 {{targets}};各 Runtime 仍保持獨立"
+ },
"authMode": {
"label": "鑑權方式",
"apiKey": "API 金鑰",
diff --git a/apps/desktop/src/renderer/lib/__tests__/customProviderRuntimeFill.test.ts b/apps/desktop/src/renderer/lib/__tests__/customProviderRuntimeFill.test.ts
new file mode 100644
index 0000000000..9dee09506f
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/__tests__/customProviderRuntimeFill.test.ts
@@ -0,0 +1,733 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ProviderWireProtocol } from '@cindy/model-providers';
+
+import {
+ applyRuntimeFillFields,
+ buildRuntimeFillDiffs,
+ cloneRuntimeFillDraft,
+ mergeHydratedRuntimeKeys,
+ normalizeRuntimeFillSelection,
+ runtimeFillFieldsForToggle,
+ runtimeFillHeaderCount,
+ runtimeFillHasUnreviewedConflict,
+ runtimeFillModelCount,
+ runtimeFillEndpointUrlsChanged,
+ runtimeFillSelectedTargetChanged,
+ runtimeFillTargetAgents,
+ type RuntimeFillDraft,
+} from '../customProviderRuntimeFill';
+
+function draft(
+ overrides: Partial<RuntimeFillDraft> & { wireProtocol?: ProviderWireProtocol } = {},
+): RuntimeFillDraft {
+ return {
+ baseUrl: '',
+ requestPath: '',
+ apiKey: '',
+ wireProtocol: 'openai-chat',
+ models: [],
+ headers: [],
+ modelsUrl: '',
+ ...overrides,
+ };
+}
+
+describe('custom provider runtime fill', () => {
+ it('only treats base or model-list URL changes as endpoint changes for key retention', () => {
+ const previous = draft({
+ baseUrl: 'https://same.example/v1',
+ requestPath: '/old-path',
+ modelsUrl: 'https://same.example/v1/models',
+ });
+ expect(
+ runtimeFillEndpointUrlsChanged(previous, {
+ ...previous,
+ requestPath: '/new-path',
+ wireProtocol: 'openai-responses',
+ }),
+ ).toBe(false);
+ expect(
+ runtimeFillEndpointUrlsChanged(previous, {
+ ...previous,
+ baseUrl: 'https://new.example/v1',
+ }),
+ ).toBe(true);
+ });
+
+ it('excludes Pi as a target when the provider uses OAuth', () => {
+ expect(runtimeFillTargetAgents('codex', { includePi: false })).toEqual(['claude-code']);
+ expect(runtimeFillTargetAgents('codex', { includePi: true })).toEqual(['claude-code', 'pi']);
+ });
+
+ it('treats endpoint URL, default request path, and protocol as one atomic selection', () => {
+ const source = draft({
+ baseUrl: 'https://anthropic.example/v1',
+ requestPath: '',
+ wireProtocol: 'anthropic-messages',
+ });
+ const target = draft({
+ baseUrl: 'https://openai.example/v1',
+ requestPath: '/responses',
+ wireProtocol: 'openai-responses',
+ });
+ const diffs = buildRuntimeFillDiffs(source, target, {
+ includeApiKey: true,
+ sourceAgent: 'claude-code',
+ targetAgent: 'codex',
+ });
+
+ expect(diffs.slice(0, 3).map((diff) => diff.field)).toEqual([
+ 'baseUrl',
+ 'requestPath',
+ 'wireProtocol',
+ ]);
+ expect(runtimeFillFieldsForToggle('requestPath', diffs)).toEqual([
+ 'baseUrl',
+ 'requestPath',
+ 'wireProtocol',
+ ]);
+ expect(normalizeRuntimeFillSelection(['baseUrl'], diffs)).toEqual([
+ 'baseUrl',
+ 'requestPath',
+ 'wireProtocol',
+ ]);
+
+ // The apply guard also expands a partial caller selection, so a future UI cannot
+ // accidentally retain /responses while switching to Anthropic Messages.
+ expect(
+ applyRuntimeFillFields(target, source, ['requestPath'], {
+ sourceAgent: 'claude-code',
+ targetAgent: 'codex',
+ }),
+ ).toMatchObject({
+ baseUrl: 'https://anthropic.example/v1',
+ requestPath: '',
+ wireProtocol: 'anthropic-messages',
+ });
+ });
+
+ it('reports unsupported endpoint fields and refuses to apply them', () => {
+ const source = draft({
+ baseUrl: 'https://openai.example/v1',
+ requestPath: '/responses',
+ wireProtocol: 'openai-responses',
+ headers: [{ name: 'X-Route', value: 'responses' }],
+ });
+ const target = draft({
+ baseUrl: 'https://anthropic.example/v1',
+ wireProtocol: 'anthropic-messages',
+ });
+ const diffs = buildRuntimeFillDiffs(source, target, {
+ includeApiKey: true,
+ sourceAgent: 'codex',
+ targetAgent: 'claude-code',
+ });
+
+ expect(
+ diffs
+ .filter((diff) =>
+ ['baseUrl', 'requestPath', 'wireProtocol', 'headers'].includes(diff.field),
+ )
+ .every((diff) => diff.targetState === 'incompatible'),
+ ).toBe(true);
+ expect(
+ diffs
+ .filter((diff) =>
+ ['baseUrl', 'requestPath', 'wireProtocol', 'headers'].includes(diff.field),
+ )
+ .every((diff) => diff.incompatibilityReason === 'protocol'),
+ ).toBe(true);
+ expect(runtimeFillFieldsForToggle('baseUrl', diffs)).toEqual([]);
+ expect(
+ applyRuntimeFillFields(
+ target,
+ source,
+ ['baseUrl', 'requestPath', 'wireProtocol', 'headers'],
+ {
+ sourceAgent: 'codex',
+ targetAgent: 'claude-code',
+ },
+ ),
+ ).toEqual(target);
+ });
+
+ it('rejects the whole inference endpoint when a non-empty request path crosses Pi', () => {
+ const source = draft({
+ baseUrl: 'https://openai.example/v1',
+ requestPath: '/responses',
+ modelsUrl: 'https://openai.example/v1/models',
+ wireProtocol: 'openai-responses',
+ });
+ const target = draft({
+ baseUrl: 'https://pi.example/v1',
+ requestPath: '/old-path',
+ modelsUrl: 'https://pi.example/v1/old-models',
+ wireProtocol: 'openai-chat',
+ });
+ const diffs = buildRuntimeFillDiffs(source, target, {
+ includeApiKey: true,
+ sourceAgent: 'codex',
+ targetAgent: 'pi',
+ });
+
+ expect(
+ diffs
+ .filter((diff) => ['baseUrl', 'requestPath', 'wireProtocol'].includes(diff.field))
+ .every((diff) => diff.targetState === 'incompatible'),
+ ).toBe(true);
+ expect(
+ diffs
+ .filter((diff) => ['baseUrl', 'requestPath', 'wireProtocol'].includes(diff.field))
+ .every((diff) => diff.incompatibilityReason === 'endpoint'),
+ ).toBe(true);
+ expect(diffs.find((diff) => diff.field === 'modelsUrl')?.targetState).toBe('conflict');
+ expect(runtimeFillFieldsForToggle('baseUrl', diffs)).toEqual([]);
+ expect(normalizeRuntimeFillSelection(['apiKey'], diffs)).toEqual([]);
+ expect(
+ applyRuntimeFillFields(
+ target,
+ source,
+ ['baseUrl', 'requestPath', 'wireProtocol', 'modelsUrl', 'apiKey'],
+ {
+ sourceAgent: 'codex',
+ targetAgent: 'pi',
+ },
+ ),
+ ).toMatchObject({
+ baseUrl: target.baseUrl,
+ wireProtocol: target.wireProtocol,
+ requestPath: '',
+ modelsUrl: source.modelsUrl,
+ apiKey: target.apiKey,
+ });
+
+ const piSource = draft({
+ baseUrl: 'https://pi.example/v1',
+ requestPath: '/ignored-by-pi',
+ modelsUrl: 'https://pi.example/v1/models',
+ wireProtocol: 'openai-chat',
+ });
+ const codexTarget = draft({
+ baseUrl: 'https://old.example/v1',
+ wireProtocol: 'openai-responses',
+ });
+ const reverseDiffs = buildRuntimeFillDiffs(piSource, codexTarget, {
+ includeApiKey: true,
+ sourceAgent: 'pi',
+ targetAgent: 'codex',
+ });
+ expect(
+ reverseDiffs
+ .filter((diff) => ['baseUrl', 'requestPath', 'wireProtocol'].includes(diff.field))
+ .every((diff) => diff.targetState === 'incompatible'),
+ ).toBe(true);
+ expect(reverseDiffs.find((diff) => diff.field === 'modelsUrl')?.targetState).toBe('empty');
+ });
+
+ it('copies a path-free endpoint and models URL across Pi', () => {
+ const source = draft({
+ baseUrl: 'https://openai.example/v1',
+ wireProtocol: 'openai-responses',
+ modelsUrl: 'https://openai.example/v1/models',
+ });
+ const target = draft({
+ baseUrl: 'https://pi.example/v1',
+ requestPath: '/legacy-path',
+ wireProtocol: 'openai-chat',
+ });
+ const diffs = buildRuntimeFillDiffs(source, target, {
+ includeApiKey: true,
+ sourceAgent: 'codex',
+ targetAgent: 'pi',
+ });
+
+ expect(runtimeFillFieldsForToggle('baseUrl', diffs)).toEqual([
+ 'baseUrl',
+ 'wireProtocol',
+ 'modelsUrl',
+ ]);
+ expect(diffs.find((diff) => diff.field === 'modelsUrl')?.targetState).toBe('empty');
+ expect(
+ applyRuntimeFillFields(target, source, ['baseUrl', 'wireProtocol', 'modelsUrl'], {
+ sourceAgent: 'codex',
+ targetAgent: 'pi',
+ }),
+ ).toMatchObject({
+ baseUrl: source.baseUrl,
+ requestPath: '',
+ wireProtocol: source.wireProtocol,
+ modelsUrl: source.modelsUrl,
+ });
+ });
+
+ it('treats hidden stored target headers as a conflict without exposing their values', () => {
+ const source = draft({
+ baseUrl: 'https://source.example/v1',
+ headers: [{ name: 'X-Tenant', value: 'source-tenant' }],
+ });
+ const target = draft({
+ baseUrl: 'https://target.example/v1',
+ headersState: 'configured',
+ });
+ const diffs = buildRuntimeFillDiffs(source, target, {
+ includeApiKey: true,
+ sourceAgent: 'codex',
+ targetAgent: 'codex',
+ });
+
+ expect(diffs.find((diff) => diff.field === 'headers')?.targetState).toBe('conflict');
+ expect(
+ applyRuntimeFillFields(target, source, ['headers'], {
+ sourceAgent: 'codex',
+ targetAgent: 'codex',
+ }),
+ ).toMatchObject({
+ headers: source.headers,
+ headersState: undefined,
+ });
+ });
+
+ it('requires endpoint confirmation before clearing hidden target headers', () => {
+ const source = draft({ baseUrl: 'https://source.example/v1' });
+ const target = draft({
+ baseUrl: 'https://target.example/v1',
+ headersState: 'configured',
+ });
+ const diffs = buildRuntimeFillDiffs(source, target, {
+ includeApiKey: true,
+ sourceAgent: 'codex',
+ targetAgent: 'codex',
+ });
+
+ expect(diffs.find((diff) => diff.field === 'headers')).toEqual({
+ field: 'headers',
+ targetState: 'conflict',
+ implicitClear: true,
+ });
+ expect(runtimeFillFieldsForToggle('baseUrl', diffs)).toEqual([
+ 'baseUrl',
+ 'requestPath',
+ 'wireProtocol',
+ 'headers',
+ ]);
+ expect(runtimeFillFieldsForToggle('headers', diffs)).toEqual([
+ 'baseUrl',
+ 'requestPath',
+ 'wireProtocol',
+ 'headers',
+ ]);
+ expect(
+ applyRuntimeFillFields(target, source, ['baseUrl', 'requestPath', 'wireProtocol', 'headers'], {
+ sourceAgent: 'codex',
+ targetAgent: 'codex',
+ }),
+ ).toMatchObject({
+ baseUrl: source.baseUrl,
+ headers: [],
+ headersState: undefined,
+ });
+ });
+
+ it('binds a changed models URL to the endpoint and credential-clear bundle', () => {
+ const source = draft({
+ baseUrl: 'https://source.example/v1',
+ modelsUrl: 'https://source.example/models',
+ });
+ const target = draft({
+ baseUrl: 'https://target.example/v1',
+ modelsUrl: 'https://target.example/models',
+ headersState: 'configured',
+ apiKey: 'target-key',
+ });
+ const diffs = buildRuntimeFillDiffs(source, target, {
+ includeApiKey: true,
+ sourceAgent: 'codex',
+ targetAgent: 'codex',
+ });
+
+ expect(diffs.find((diff) => diff.field === 'modelsUrl')).toMatchObject({
+ targetState: 'conflict',
+ implicitClear: true,
+ });
+ expect(runtimeFillFieldsForToggle('modelsUrl', diffs)).toEqual([
+ 'baseUrl',
+ 'requestPath',
+ 'wireProtocol',
+ 'apiKey',
+ 'headers',
+ 'modelsUrl',
+ ]);
+ expect(
+ applyRuntimeFillFields(target, source, ['modelsUrl'], {
+ sourceAgent: 'codex',
+ targetAgent: 'codex',
+ }),
+ ).toMatchObject({
+ baseUrl: source.baseUrl,
+ modelsUrl: source.modelsUrl,
+ headersState: undefined,
+ headers: [],
+ });
+ });
+
+ it('binds target API-key clearing to an endpoint fill when source has no key', () => {
+ const source = draft({ baseUrl: 'https://source.example/v1' });
+ const target = draft({
+ baseUrl: 'https://target.example/v1',
+ apiKey: 'target-key',
+ });
+ const diffs = buildRuntimeFillDiffs(source, target, {
+ includeApiKey: false,
+ sourceAgent: 'codex',
+ targetAgent: 'codex',
+ });
+
+ expect(diffs.find((diff) => diff.field === 'apiKey')).toMatchObject({
+ targetState: 'conflict',
+ implicitClear: true,
+ });
+ expect(runtimeFillFieldsForToggle('baseUrl', diffs)).toEqual([
+ 'baseUrl',
+ 'requestPath',
+ 'wireProtocol',
+ 'apiKey',
+ ]);
+ expect(
+ applyRuntimeFillFields(target, source, ['baseUrl'], {
+ sourceAgent: 'codex',
+ targetAgent: 'codex',
+ }),
+ ).toMatchObject({ baseUrl: source.baseUrl, apiKey: '' });
+ });
+
+ it('clears an explicit target models URL when the source uses inference', () => {
+ const source = draft({ baseUrl: 'https://source.example/v1', modelsUrl: '' });
+ const target = draft({
+ baseUrl: 'https://target.example/v1',
+ modelsUrl: 'https://target.example/custom-models',
+ });
+ const diffs = buildRuntimeFillDiffs(source, target, {
+ includeApiKey: true,
+ sourceAgent: 'codex',
+ targetAgent: 'codex',
+ });
+
+ expect(diffs.find((diff) => diff.field === 'modelsUrl')).toEqual({
+ field: 'modelsUrl',
+ targetState: 'conflict',
+ implicitClear: true,
+ });
+ expect(runtimeFillFieldsForToggle('baseUrl', diffs)).toEqual([
+ 'baseUrl',
+ 'requestPath',
+ 'wireProtocol',
+ 'modelsUrl',
+ ]);
+ expect(normalizeRuntimeFillSelection(['modelsUrl'], diffs)).toEqual([
+ 'baseUrl',
+ 'requestPath',
+ 'wireProtocol',
+ 'modelsUrl',
+ ]);
+ expect(
+ applyRuntimeFillFields(target, source, ['baseUrl', 'requestPath', 'wireProtocol', 'modelsUrl'], {
+ sourceAgent: 'codex',
+ targetAgent: 'codex',
+ }),
+ ).toMatchObject({
+ baseUrl: source.baseUrl,
+ modelsUrl: '',
+ });
+ });
+
+ it('blocks endpoint transfer when source headers exist only in main storage', () => {
+ const source = draft({
+ baseUrl: 'https://source.example/v1',
+ modelsUrl: 'https://source.example/v1/models',
+ headersState: 'configured',
+ });
+ const target = draft({ baseUrl: 'https://target.example/v1' });
+ const diffs = buildRuntimeFillDiffs(source, target, {
+ includeApiKey: true,
+ sourceAgent: 'codex',
+ targetAgent: 'pi',
+ });
+
+ expect(
+ diffs
+ .filter((diff) => ['baseUrl', 'requestPath', 'wireProtocol', 'headers', 'modelsUrl'].includes(diff.field))
+ .every(
+ (diff) =>
+ diff.targetState === 'incompatible' && diff.incompatibilityReason === 'headers',
+ ),
+ ).toBe(true);
+ expect(runtimeFillFieldsForToggle('baseUrl', diffs)).toEqual([]);
+ expect(
+ applyRuntimeFillFields(target, source, ['baseUrl', 'wireProtocol', 'headers', 'modelsUrl'], {
+ sourceAgent: 'codex',
+ targetAgent: 'pi',
+ }),
+ ).toMatchObject(target);
+ });
+
+ it('blocks endpoint-bound fields when target header storage is unreadable', () => {
+ const source = draft({
+ baseUrl: 'https://source.example/v1',
+ models: [{ id: 'model', name: 'Model' }],
+ });
+ const target = draft({
+ baseUrl: 'https://target.example/v1',
+ headersState: 'unknown',
+ });
+ const diffs = buildRuntimeFillDiffs(source, target, {
+ includeApiKey: true,
+ sourceAgent: 'codex',
+ targetAgent: 'codex',
+ });
+ expect(diffs.find((diff) => diff.field === 'baseUrl')).toMatchObject({
+ targetState: 'incompatible',
+ incompatibilityReason: 'headers',
+ });
+ expect(diffs.find((diff) => diff.field === 'models')?.targetState).toBe('empty');
+ expect(
+ applyRuntimeFillFields(target, source, ['baseUrl', 'headers', 'modelsUrl'], {
+ sourceAgent: 'codex',
+ targetAgent: 'codex',
+ }),
+ ).toMatchObject(target);
+ });
+
+ it('does not copy an endpoint-bound API key when source headers hide the endpoint transfer', () => {
+ const source = draft({
+ baseUrl: 'https://source.example/v1',
+ modelsUrl: 'https://source.example/v1/models',
+ apiKey: 'source-key',
+ headersState: 'configured',
+ });
+ const target = draft({
+ baseUrl: 'https://target.example/v1',
+ modelsUrl: 'https://target.example/v1/models',
+ apiKey: '',
+ });
+ const diffs = buildRuntimeFillDiffs(source, target, {
+ includeApiKey: true,
+ sourceAgent: 'codex',
+ targetAgent: 'pi',
+ });
+
+ expect(diffs.find((diff) => diff.field === 'apiKey')).toMatchObject({
+ targetState: 'incompatible',
+ incompatibilityReason: 'headers',
+ });
+ expect(normalizeRuntimeFillSelection(['apiKey'], diffs)).toEqual([]);
+ expect(
+ applyRuntimeFillFields(target, source, ['apiKey'], {
+ sourceAgent: 'codex',
+ targetAgent: 'pi',
+ }),
+ ).toMatchObject(target);
+ });
+
+ it('clears a legacy target request path when filling from a path-free Pi source', () => {
+ const source = draft({
+ baseUrl: 'https://pi.example/v1',
+ wireProtocol: 'openai-chat',
+ });
+ const target = draft({
+ baseUrl: 'https://old.example/v1',
+ requestPath: '/responses',
+ wireProtocol: 'openai-responses',
+ });
+ const diffs = buildRuntimeFillDiffs(source, target, {
+ includeApiKey: true,
+ sourceAgent: 'pi',
+ targetAgent: 'codex',
+ });
+
+ expect(diffs.find((diff) => diff.field === 'requestPath')?.targetState).toBe('conflict');
+ expect(runtimeFillFieldsForToggle('baseUrl', diffs)).toEqual([
+ 'baseUrl',
+ 'requestPath',
+ 'wireProtocol',
+ ]);
+ expect(
+ applyRuntimeFillFields(target, source, ['baseUrl', 'requestPath', 'wireProtocol'], {
+ sourceAgent: 'pi',
+ targetAgent: 'codex',
+ }),
+ ).toMatchObject({
+ baseUrl: source.baseUrl,
+ requestPath: '',
+ wireProtocol: source.wireProtocol,
+ });
+ });
+
+ it('preserves Pi-only model capabilities when portable model fields are filled', () => {
+ const source = draft({
+ models: [{ id: 'model-a', name: 'Model A', contextWindow: 128_000 }],
+ });
+ const target = draft({
+ models: [
+ {
+ id: 'model-a',
+ name: 'Old name',
+ contextWindow: 32_000,
+ supportsImageInput: true,
+ reasoning: true,
+ reasoningEfforts: ['low', 'high'],
+ },
+ ],
+ });
+
+ const result = applyRuntimeFillFields(target, source, ['models'], {
+ sourceAgent: 'claude-code',
+ targetAgent: 'pi',
+ });
+ expect(result.models).toEqual([
+ {
+ id: 'model-a',
+ name: 'Model A',
+ contextWindow: 128_000,
+ supportsImageInput: true,
+ reasoning: true,
+ reasoningEfforts: ['low', 'high'],
+ },
+ ]);
+ });
+
+ it('ignores Pi-only capabilities when comparing or filling a non-Pi target', () => {
+ const source = draft({
+ models: [
+ {
+ id: 'model-a',
+ name: 'Model A',
+ supportsImageInput: true,
+ reasoning: true,
+ reasoningEfforts: ['low'],
+ },
+ ],
+ });
+ const target = draft({ models: [{ id: 'model-a', name: 'Model A' }] });
+ const modelDiff = buildRuntimeFillDiffs(source, target, {
+ includeApiKey: true,
+ sourceAgent: 'pi',
+ targetAgent: 'codex',
+ }).find((diff) => diff.field === 'models');
+
+ expect(modelDiff?.targetState).toBe('same');
+ expect(
+ applyRuntimeFillFields(target, source, ['models'], {
+ sourceAgent: 'pi',
+ targetAgent: 'codex',
+ }).models,
+ ).toEqual([{ id: 'model-a', name: 'Model A' }]);
+ });
+
+ it('uses the same model and header counting semantics as save', () => {
+ const value = draft({
+ models: [
+ { id: 'valid', name: 'Valid' },
+ { id: 'missing-name', name: '' },
+ { id: '', name: 'Missing id' },
+ ],
+ headers: [
+ { name: 'X-Test', value: 'first' },
+ { name: '', value: 'discarded' },
+ { name: 'X-Test', value: 'last' },
+ ],
+ });
+
+ expect(runtimeFillModelCount(value)).toBe(1);
+ expect(runtimeFillHeaderCount(value)).toBe(1);
+ expect(
+ applyRuntimeFillFields(draft(), value, ['models', 'headers'], {
+ sourceAgent: 'codex',
+ targetAgent: 'pi',
+ }),
+ ).toMatchObject({
+ models: [{ id: 'valid', name: 'Valid' }],
+ headers: [{ name: 'X-Test', value: 'last' }],
+ });
+ });
+
+ it('takes a deep snapshot for review and apply', () => {
+ const source = draft({
+ models: [{ id: 'model-a', name: 'Model A', reasoningEfforts: ['low'] }],
+ headers: [{ name: 'X-Test', value: 'one' }],
+ });
+ const snapshot = cloneRuntimeFillDraft(source);
+
+ source.models[0].name = 'Changed';
+ source.models[0].reasoningEfforts?.push('high');
+ source.headers[0].value = 'two';
+
+ expect(snapshot.models[0]).toMatchObject({
+ name: 'Model A',
+ reasoningEfforts: ['low'],
+ });
+ expect(snapshot.headers[0]).toEqual({ name: 'X-Test', value: 'one' });
+ });
+
+ it('does not let late key hydration overwrite a user edit or runtime fill', () => {
+ const drafts = {
+ 'claude-code': draft({ apiKey: 'saved-claude' }),
+ codex: draft({ apiKey: 'newly-copied-codex' }),
+ pi: draft({ apiKey: '' }),
+ };
+ const revisionAtStart = { 'claude-code': 0, codex: 0, pi: 0 };
+ const currentRevision = { 'claude-code': 0, codex: 1, pi: 0 };
+
+ const merged = mergeHydratedRuntimeKeys(
+ drafts,
+ { 'claude-code': 'stored-claude', codex: 'stale-codex', pi: 'stored-pi' },
+ {
+ 'claude-code': { baseUrl: '', modelsUrl: '' },
+ codex: { baseUrl: '', modelsUrl: '' },
+ pi: { baseUrl: '', modelsUrl: '' },
+ },
+ revisionAtStart,
+ currentRevision,
+ );
+
+ expect(merged['claude-code'].apiKey).toBe('stored-claude');
+ expect(merged.codex.apiKey).toBe('newly-copied-codex');
+ expect(merged.pi.apiKey).toBe('stored-pi');
+ });
+
+ it('does not hydrate a saved key after the credential endpoint changed', () => {
+ const drafts = {
+ 'claude-code': draft(),
+ codex: draft({ baseUrl: 'https://new.example/v1' }),
+ pi: draft(),
+ };
+ const revisions = { 'claude-code': 0, codex: 0, pi: 0 };
+
+ const merged = mergeHydratedRuntimeKeys(
+ drafts,
+ { codex: 'stored-codex' },
+ { codex: { baseUrl: 'https://saved.example/v1', modelsUrl: '' } },
+ revisions,
+ revisions,
+ );
+
+ expect(merged.codex.apiKey).toBe('');
+ });
+
+ it('requires a new confirmation if a selected target becomes occupied after review', () => {
+ const previous = [{ field: 'apiKey', targetState: 'empty' }] as const;
+ const fresh = [{ field: 'apiKey', targetState: 'conflict' }] as const;
+
+ expect(runtimeFillHasUnreviewedConflict(previous, fresh, ['apiKey'])).toBe(true);
+ expect(runtimeFillHasUnreviewedConflict(previous, fresh, ['models'])).toBe(false);
+ expect(runtimeFillHasUnreviewedConflict(fresh, fresh, ['apiKey'])).toBe(false);
+ });
+
+ it('requires a new confirmation if a selected conflicting value changes after review', () => {
+ const previous = draft({ models: [{ id: 'old', name: 'Old' }] });
+ const fresh = draft({ models: [{ id: 'new', name: 'New' }] });
+
+ expect(runtimeFillSelectedTargetChanged(previous, fresh, ['models'], 'codex')).toBe(true);
+ expect(runtimeFillSelectedTargetChanged(previous, fresh, ['apiKey'], 'codex')).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts b/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts
index c7cbcf1297..101707c8c6 100644
--- a/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts
@@ -258,6 +258,37 @@ describe('providerViewToCustomProviderConfig', () => {
},
]);
});
+
+ it('preserves non-secret presence metadata for main-only runtime headers', () => {
+ const provider = {
+ id: 'headered-provider',
+ name: 'Headered provider',
+ source: 'user',
+ agents: ['codex'],
+ auth: { method: 'apiKey' },
+ routing: {
+ codex: {
+ upstream: 'https://api.example/v1',
+ authStrategy: 'api-key-header',
+ headerOverrideState: 'configured',
+ },
+ },
+ models: {
+ codex: [{
+ id: 'model',
+ name: 'Model',
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ }],
+ },
+ connected: true,
+ } satisfies ProviderView;
+
+ expect(providerViewToCustomProviderConfig(provider).runtimes.codex).toMatchObject({
+ headersState: 'configured',
+ });
+ });
});
describe('appendDiscoveredCustomProviderModels', () => {
diff --git a/apps/desktop/src/renderer/lib/__tests__/providerModelFetch.test.ts b/apps/desktop/src/renderer/lib/__tests__/providerModelFetch.test.ts
index c5e331c3be..3306338061 100644
--- a/apps/desktop/src/renderer/lib/__tests__/providerModelFetch.test.ts
+++ b/apps/desktop/src/renderer/lib/__tests__/providerModelFetch.test.ts
@@ -2,10 +2,12 @@ import { describe, expect, it } from 'vitest';
import {
areProviderRequestUrlsAllowed,
+ canSendHydratedApiKey,
connectionTestCanUseSaved,
modelFetchCanReuseSavedCredentials,
providerConnectionTestRequestSignature,
providerModelFetchRequestSignature,
+ restoreHydratedApiKey,
type SavedProviderProbeBaseline,
} from '../providerModelFetch';
@@ -167,6 +169,133 @@ describe('modelFetchCanReuseSavedCredentials', () => {
),
).toBe(false);
});
+
+ it('keeps saved credentials when only the inference request path changes', () => {
+ expect(
+ modelFetchCanReuseSavedCredentials(
+ {
+ baseUrl: headerAuthBaseline.baseUrl,
+ requestPath: '/tenant/acme/models',
+ modelsUrl: headerAuthBaseline.modelsUrl,
+ },
+ headerAuthBaseline,
+ 'none',
+ ),
+ ).toBe(true);
+ });
+});
+
+describe('canSendHydratedApiKey', () => {
+ const apiKeyBaseline: SavedProviderProbeBaseline = {
+ ...headerAuthBaseline,
+ authMode: 'apiKey',
+ apiKey: 'saved-key',
+ };
+ const requestTarget = {
+ baseUrl: apiKeyBaseline.baseUrl,
+ requestPath: apiKeyBaseline.requestPath,
+ modelsUrl: apiKeyBaseline.modelsUrl,
+ };
+
+ it('keeps an untouched hydrated key on the saved base/models endpoint', () => {
+ expect(canSendHydratedApiKey(requestTarget, apiKeyBaseline, 'apiKey', 0)).toBe(true);
+ expect(
+ canSendHydratedApiKey(
+ { ...requestTarget, baseUrl: 'https://new.example/v1' },
+ apiKeyBaseline,
+ 'apiKey',
+ 0,
+ ),
+ ).toBe(false);
+ expect(
+ canSendHydratedApiKey(
+ { ...requestTarget, modelsUrl: 'https://new.example/models' },
+ apiKeyBaseline,
+ 'apiKey',
+ 0,
+ ),
+ ).toBe(false);
+ });
+
+ it('allows a key after the user explicitly edits it', () => {
+ expect(
+ canSendHydratedApiKey(
+ { ...requestTarget, baseUrl: 'https://new.example/v1' },
+ apiKeyBaseline,
+ 'apiKey',
+ 1,
+ ),
+ ).toBe(true);
+ });
+ it('allows the hydrated key when only requestPath changes', () => {
+ expect(
+ canSendHydratedApiKey(
+ {
+ baseUrl: apiKeyBaseline.baseUrl,
+ requestPath: '/tenant/acme/models',
+ modelsUrl: apiKeyBaseline.modelsUrl,
+ },
+ apiKeyBaseline,
+ 'apiKey',
+ 0,
+ ),
+ ).toBe(true);
+ });
+
+ it('still blocks a changed model-discovery endpoint until the key is edited', () => {
+ expect(
+ canSendHydratedApiKey(
+ { baseUrl: 'https://new.example/v1', modelsUrl: apiKeyBaseline.modelsUrl },
+ apiKeyBaseline,
+ 'apiKey',
+ 0,
+ ),
+ ).toBe(false);
+ expect(
+ canSendHydratedApiKey(
+ { baseUrl: 'https://new.example/v1', modelsUrl: apiKeyBaseline.modelsUrl },
+ apiKeyBaseline,
+ 'apiKey',
+ 1,
+ ),
+ ).toBe(true);
+ });
+});
+
+describe('restoreHydratedApiKey', () => {
+ const baseline: SavedProviderProbeBaseline = {
+ ...headerAuthBaseline,
+ authMode: 'apiKey',
+ apiKey: 'saved-key',
+ };
+
+ it('restores a cleared hydrated key after returning to the saved endpoint', () => {
+ const reverted = {
+ baseUrl: baseline.baseUrl,
+ modelsUrl: baseline.modelsUrl,
+ apiKey: '',
+ };
+ expect(restoreHydratedApiKey(reverted, baseline, 'apiKey', 0).apiKey).toBe('saved-key');
+ });
+
+ it('does not overwrite an explicit key edit or a different endpoint', () => {
+ expect(
+ restoreHydratedApiKey(
+ { baseUrl: baseline.baseUrl, modelsUrl: baseline.modelsUrl, apiKey: '' },
+ baseline,
+ 'apiKey',
+ 1,
+ ).apiKey,
+ ).toBe('');
+ expect(
+ restoreHydratedApiKey(
+ { baseUrl: 'https://new.example/v1', modelsUrl: baseline.modelsUrl, apiKey: '' },
+ baseline,
+ 'apiKey',
+ 0,
+ ).apiKey,
+ ).toBe('');
+ });
});
describe('connectionTestCanUseSaved', () => {
diff --git a/apps/desktop/src/renderer/lib/customProviderRuntimeFill.ts b/apps/desktop/src/renderer/lib/customProviderRuntimeFill.ts
new file mode 100644
index 0000000000..aa0b6be2e4
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/customProviderRuntimeFill.ts
@@ -0,0 +1,623 @@
+import type {
+ AgentKind,
+ ProviderRuntimeModelConfig,
+ ProviderWireProtocol,
+} from '@cindy/model-providers';
+
+export type RuntimeFillAgent = Extract<AgentKind, 'claude-code' | 'codex' | 'pi'>;
+export interface RuntimeFillHeaderRow {
+ name: string;
+ value: string;
+}
+export interface RuntimeFillDraft {
+ baseUrl: string;
+ requestPath: string;
+ apiKey: string;
+ wireProtocol: ProviderWireProtocol;
+ models: ProviderRuntimeModelConfig[];
+ headers: RuntimeFillHeaderRow[];
+ modelsUrl: string;
+ /** Non-secret metadata for headers held in main-only storage. */
+ headersState?: 'configured' | 'unknown';
+}
+export type RuntimeFillField =
+ 'baseUrl' | 'requestPath' | 'wireProtocol' | 'apiKey' | 'models' | 'headers' | 'modelsUrl';
+export type RuntimeFillTargetState = 'empty' | 'same' | 'conflict' | 'incompatible';
+export type RuntimeFillIncompatibilityReason = 'protocol' | 'endpoint' | 'headers';
+export interface RuntimeFillFieldDiff {
+ field: RuntimeFillField;
+ targetState: RuntimeFillTargetState;
+ incompatibilityReason?: RuntimeFillIncompatibilityReason;
+ /** This field must be cleared together with the endpoint bundle. */
+ implicitClear?: boolean;
+}
+
+export const RUNTIME_FILL_ENDPOINT_FIELDS = [
+ 'baseUrl',
+ 'requestPath',
+ 'wireProtocol',
+] as const satisfies readonly RuntimeFillField[];
+
+export const RUNTIME_FILL_FIELD_ORDER: readonly RuntimeFillField[] = [
+ ...RUNTIME_FILL_ENDPOINT_FIELDS,
+ 'apiKey',
+ 'models',
+ 'headers',
+ 'modelsUrl',
+];
+
+const PROTOCOL_BOUND_FIELDS = new Set<RuntimeFillField>([
+ ...RUNTIME_FILL_ENDPOINT_FIELDS,
+ 'headers',
+ 'modelsUrl',
+]);
+
+const HEADER_DEPENDENT_FIELDS = new Set<RuntimeFillField>([
+ ...RUNTIME_FILL_ENDPOINT_FIELDS,
+ 'headers',
+ 'modelsUrl',
+]);
+
+const RUNTIME_FILL_AGENTS: readonly RuntimeFillAgent[] = ['claude-code', 'codex', 'pi'];
+
+export function runtimeFillTargetAgents(
+ source: RuntimeFillAgent,
+ options: { includePi: boolean },
+): RuntimeFillAgent[] {
+ return RUNTIME_FILL_AGENTS.filter(
+ (agent) => agent !== source && (options.includePi || agent !== 'pi'),
+ );
+}
+
+function defaultWire(agent: RuntimeFillAgent): ProviderWireProtocol {
+ return agent === 'claude-code'
+ ? 'anthropic-messages'
+ : agent === 'codex'
+ ? 'openai-responses'
+ : 'openai-chat';
+}
+
+function effectiveWire(agent: RuntimeFillAgent, value: ProviderWireProtocol | undefined) {
+ return value ?? defaultWire(agent);
+}
+
+function protocolSupported(agent: RuntimeFillAgent, wire: ProviderWireProtocol) {
+ return agent !== 'claude-code' || wire === 'anthropic-messages';
+}
+
+/** Pi's native provider config does not consume the shared route-only request path. */
+function fieldSupported(
+ agent: RuntimeFillAgent,
+ field: RuntimeFillField,
+ wire: ProviderWireProtocol,
+) {
+ if (agent === 'pi' && field === 'requestPath') return false;
+ return !PROTOCOL_BOUND_FIELDS.has(field) || protocolSupported(agent, wire);
+}
+
+function transferFieldSupported(
+ source: RuntimeFillDraft,
+ sourceAgent: RuntimeFillAgent,
+ targetAgent: RuntimeFillAgent,
+ field: RuntimeFillField,
+ wire: ProviderWireProtocol,
+): boolean {
+ // A path-free Pi source can intentionally clear a legacy/custom path on a route-aware target
+ // while moving the rest of the inference endpoint. Pi itself still cannot receive a path.
+ if (field === 'requestPath') {
+ return targetAgent !== 'pi' &&
+ (sourceAgent !== 'pi' || source.requestPath.trim().length === 0) &&
+ protocolSupported(sourceAgent, wire) &&
+ protocolSupported(targetAgent, wire);
+ }
+ return fieldSupported(sourceAgent, field, wire) && fieldSupported(targetAgent, field, wire);
+}
+
+/** Pi cannot express a custom inference request path, so this endpoint cannot be copied partly. */
+function endpointBundleSupported(
+ source: RuntimeFillDraft,
+ sourceAgent: RuntimeFillAgent,
+ targetAgent: RuntimeFillAgent,
+): boolean {
+ return source.requestPath.trim().length === 0 || (sourceAgent !== 'pi' && targetAgent !== 'pi');
+}
+
+function savedModelShape(model: ProviderRuntimeModelConfig, includePiCapabilities: boolean) {
+ return {
+ id: model.id.trim(),
+ name: model.name.trim(),
+ ...(model.contextWindow !== undefined ? { contextWindow: model.contextWindow } : {}),
+ ...(model.defaultEnabled === false ? { defaultEnabled: false } : {}),
+ ...(includePiCapabilities && model.supportsImageInput === true
+ ? { supportsImageInput: true }
+ : {}),
+ ...(includePiCapabilities && model.reasoning === true && model.reasoningEfforts?.length
+ ? { reasoning: true, reasoningEfforts: [...model.reasoningEfforts] }
+ : {}),
+ } satisfies ProviderRuntimeModelConfig;
+}
+
+function validModels(models: ProviderRuntimeModelConfig[]) {
+ return models
+ .filter((model) => model.id.trim() && model.name.trim())
+ .map((model) => savedModelShape(model, true));
+}
+
+function canonicalHeaders(headers: RuntimeFillHeaderRow[]) {
+ const byName = new Map<string, string>();
+ for (const header of headers) {
+ const name = header.name.trim();
+ if (!name) continue;
+ // Save semantics are object assignment: the last value for a duplicate name wins.
+ if (byName.has(name)) byName.delete(name);
+ byName.set(name, header.value.trim());
+ }
+ return [...byName].map(([name, value]) => ({ name, value }));
+}
+
+/**
+ * Project source models into the exact shape that the target runtime will save.
+ * Pi-only capability metadata belongs to the Pi runtime, so portable fills preserve
+ * it for matching target model ids instead of silently deleting it.
+ */
+function modelsForTarget(
+ sourceModels: ProviderRuntimeModelConfig[],
+ targetModels: ProviderRuntimeModelConfig[],
+ sourceAgent: RuntimeFillAgent,
+ targetAgent: RuntimeFillAgent,
+) {
+ const targetById = new Map(validModels(targetModels).map((model) => [model.id, model]));
+ return validModels(sourceModels).map((sourceModel) => {
+ if (targetAgent !== 'pi') return savedModelShape(sourceModel, false);
+ if (sourceAgent === 'pi') return savedModelShape(sourceModel, true);
+
+ const portable = savedModelShape(sourceModel, false);
+ const existing = targetById.get(portable.id);
+ return {
+ ...portable,
+ ...(existing?.supportsImageInput === true ? { supportsImageInput: true } : {}),
+ ...(existing?.reasoning === true && existing.reasoningEfforts?.length
+ ? { reasoning: true, reasoningEfforts: [...existing.reasoningEfforts] }
+ : {}),
+ };
+ });
+}
+
+function comparableValue(
+ field: RuntimeFillField,
+ draft: RuntimeFillDraft,
+ agent: RuntimeFillAgent,
+): unknown {
+ switch (field) {
+ case 'baseUrl':
+ return draft.baseUrl.trim();
+ case 'requestPath':
+ return draft.requestPath.trim();
+ case 'wireProtocol':
+ return effectiveWire(agent, draft.wireProtocol);
+ case 'apiKey':
+ return draft.apiKey.trim();
+ case 'models':
+ return validModels(draft.models);
+ case 'headers':
+ return canonicalHeaders(draft.headers).sort(
+ (left, right) =>
+ left.name.localeCompare(right.name) || left.value.localeCompare(right.value),
+ );
+ case 'modelsUrl':
+ return draft.modelsUrl.trim();
+ }
+}
+
+function sourceFieldHasValue(
+ field: RuntimeFillField,
+ draft: RuntimeFillDraft,
+ agent: RuntimeFillAgent,
+) {
+ if (field === 'wireProtocol') return draft.baseUrl.trim().length > 0;
+ if (field === 'requestPath') return draft.baseUrl.trim().length > 0;
+ const value = comparableValue(field, draft, agent);
+ return Array.isArray(value) ? value.length > 0 : value !== '';
+}
+
+function targetFieldHasValue(
+ field: RuntimeFillField,
+ draft: RuntimeFillDraft,
+ agent: RuntimeFillAgent,
+) {
+ return field === 'headers'
+ ? sourceFieldHasValue(field, draft, agent) || runtimeHeaderState(draft) != null
+ : sourceFieldHasValue(field, draft, agent);
+}
+
+function runtimeHeaderState(draft: RuntimeFillDraft): 'configured' | 'unknown' | undefined {
+ return draft.headersState;
+}
+
+function endpointUrlChanged(source: RuntimeFillDraft, target: RuntimeFillDraft): boolean {
+ const sourceBaseUrl = source.baseUrl.trim();
+ const sourceModelsUrl = source.modelsUrl.trim();
+ const targetModelsUrl = target.modelsUrl.trim();
+ return (
+ (sourceBaseUrl.length > 0 && sourceBaseUrl !== target.baseUrl.trim()) ||
+ (sourceModelsUrl !== targetModelsUrl &&
+ (sourceModelsUrl.length > 0 || (sourceBaseUrl.length > 0 && targetModelsUrl.length > 0)))
+ );
+}
+
+export function runtimeFillFieldHasValue(
+ field: RuntimeFillField,
+ draft: RuntimeFillDraft,
+ agent: RuntimeFillAgent = 'claude-code',
+): boolean {
+ return sourceFieldHasValue(field, draft, agent);
+}
+
+export function runtimeFillModelCount(draft: RuntimeFillDraft): number {
+ return validModels(draft.models).length;
+}
+
+export function runtimeFillHeaderCount(draft: RuntimeFillDraft): number {
+ return canonicalHeaders(draft.headers).length;
+}
+
+export function runtimeFillEndpointUrlsChanged(
+ previous: RuntimeFillDraft,
+ next: RuntimeFillDraft,
+): boolean {
+ return (
+ previous.baseUrl.trim() !== next.baseUrl.trim() ||
+ previous.modelsUrl.trim() !== next.modelsUrl.trim()
+ );
+}
+
+export function cloneRuntimeFillDraft(draft: RuntimeFillDraft): RuntimeFillDraft {
+ return {
+ ...draft,
+ models: draft.models.map((model) => ({
+ ...model,
+ ...(model.reasoningEfforts ? { reasoningEfforts: [...model.reasoningEfforts] } : {}),
+ })),
+ headers: draft.headers.map((header) => ({ ...header })),
+ };
+}
+
+export function mergeHydratedRuntimeKeys<T extends RuntimeFillDraft>(
+ drafts: Record<RuntimeFillAgent, T>,
+ fetched: Partial<Record<RuntimeFillAgent, string>>,
+ savedTargets: Partial<
+ Record<RuntimeFillAgent, Pick<RuntimeFillDraft, 'baseUrl' | 'modelsUrl'>>
+ >,
+ revisionAtStart: Record<RuntimeFillAgent, number>,
+ currentRevision: Record<RuntimeFillAgent, number>,
+): Record<RuntimeFillAgent, T> {
+ const next = { ...drafts };
+ for (const agent of RUNTIME_FILL_AGENTS) {
+ const apiKey = fetched[agent];
+ const savedTarget = savedTargets[agent];
+ if (
+ apiKey == null ||
+ !savedTarget ||
+ currentRevision[agent] !== revisionAtStart[agent] ||
+ drafts[agent].baseUrl.trim() !== savedTarget.baseUrl.trim() ||
+ drafts[agent].modelsUrl.trim() !== savedTarget.modelsUrl.trim()
+ ) {
+ continue;
+ }
+ next[agent] = { ...drafts[agent], apiKey };
+ }
+ return next;
+}
+
+export function buildRuntimeFillDiffs(
+ source: RuntimeFillDraft,
+ target: RuntimeFillDraft,
+ options: { includeApiKey: boolean; sourceAgent: RuntimeFillAgent; targetAgent: RuntimeFillAgent },
+): RuntimeFillFieldDiff[] {
+ const wire = effectiveWire(options.sourceAgent, source.wireProtocol);
+ const endpointSupported = endpointBundleSupported(
+ source,
+ options.sourceAgent,
+ options.targetAgent,
+ );
+ const sourceHasHiddenHeaders =
+ runtimeHeaderState(source) != null &&
+ !sourceFieldHasValue('headers', source, options.sourceAgent);
+ const targetHeadersUnknown = runtimeHeaderState(target) === 'unknown';
+ const targetHasHeaders = targetFieldHasValue('headers', target, options.targetAgent);
+ const endpointChangesUrl = endpointUrlChanged(source, target);
+ const implicitHeaderClear = endpointChangesUrl && targetHasHeaders;
+ const implicitModelsUrlClear =
+ source.baseUrl.trim().length > 0 &&
+ source.modelsUrl.trim().length === 0 &&
+ target.modelsUrl.trim().length > 0;
+ // A modelsUrl replacement is an endpoint move too. Keep it in the same
+ // inseparable selection as the inference endpoint whenever applying it can
+ // make Main discard endpoint-bound credentials/headers.
+ const modelsUrlEndpointChange =
+ source.modelsUrl.trim() !== target.modelsUrl.trim() && endpointChangesUrl;
+ const implicitApiKeyClear =
+ endpointChangesUrl &&
+ target.apiKey.trim().length > 0 &&
+ true;
+
+ return RUNTIME_FILL_FIELD_ORDER.filter((field) => {
+ if (!options.includeApiKey && field === 'apiKey' && !implicitApiKeyClear) return false;
+ if (field === 'headers') {
+ return sourceFieldHasValue(field, source, options.sourceAgent) ||
+ sourceHasHiddenHeaders ||
+ implicitHeaderClear;
+ }
+ if (field === 'modelsUrl') {
+ return sourceFieldHasValue(field, source, options.sourceAgent) || implicitModelsUrlClear;
+ }
+ if (field === 'apiKey') {
+ return sourceFieldHasValue(field, source, options.sourceAgent) || implicitApiKeyClear;
+ }
+ return sourceFieldHasValue(field, source, options.sourceAgent);
+ }).map((field) => {
+ if (sourceHasHiddenHeaders && HEADER_DEPENDENT_FIELDS.has(field)) {
+ return {
+ field,
+ targetState: 'incompatible',
+ incompatibilityReason: 'headers',
+ };
+ }
+ if (
+ targetHeadersUnknown &&
+ endpointChangesUrl &&
+ (HEADER_DEPENDENT_FIELDS.has(field) || field === 'apiKey')
+ ) {
+ return {
+ field,
+ targetState: 'incompatible',
+ incompatibilityReason: 'headers',
+ };
+ }
+ if (
+ (RUNTIME_FILL_ENDPOINT_FIELDS as readonly RuntimeFillField[]).includes(field) &&
+ !endpointSupported
+ ) {
+ return { field, targetState: 'incompatible', incompatibilityReason: 'endpoint' };
+ }
+ // An API key is endpoint-bound. If the source endpoint cannot be transferred
+ // (for example, because its main-only headers are unavailable to renderer or
+ // because a Pi-incompatible request path makes the bundle unsafe), never let
+ // the key fall through as an independently copyable field to another host.
+ if (field === 'apiKey' && endpointChangesUrl &&
+ (sourceHasHiddenHeaders || !endpointSupported)
+ ) {
+ return {
+ field,
+ targetState: 'incompatible',
+ incompatibilityReason: sourceHasHiddenHeaders ? 'headers' : 'endpoint',
+ };
+ }
+ if (!transferFieldSupported(source, options.sourceAgent, options.targetAgent, field, wire)) {
+ return {
+ field,
+ targetState: 'incompatible',
+ incompatibilityReason:
+ field === 'requestPath' &&
+ (options.sourceAgent === 'pi' || options.targetAgent === 'pi')
+ ? 'endpoint'
+ : 'protocol',
+ };
+ }
+
+ const sourceValue =
+ field === 'models'
+ ? modelsForTarget(source.models, target.models, options.sourceAgent, options.targetAgent)
+ : comparableValue(field, source, options.sourceAgent);
+ const targetValue =
+ field === 'models'
+ ? modelsForTarget(target.models, target.models, options.targetAgent, options.targetAgent)
+ : comparableValue(field, target, options.targetAgent);
+ const same = JSON.stringify(sourceValue) === JSON.stringify(targetValue);
+ const hiddenTargetHeadersOnly =
+ field === 'headers' &&
+ runtimeHeaderState(target) != null &&
+ !sourceFieldHasValue('headers', source, options.sourceAgent);
+ const shouldConfirmImplicitClear =
+ (field === 'headers' && implicitHeaderClear) ||
+ (field === 'modelsUrl' && (implicitModelsUrlClear || modelsUrlEndpointChange)) ||
+ (field === 'apiKey' && implicitApiKeyClear);
+ return {
+ field,
+ targetState: same && !hiddenTargetHeadersOnly
+ ? 'same'
+ : targetFieldHasValue(field, target, options.targetAgent)
+ ? 'conflict'
+ : 'empty',
+ ...(shouldConfirmImplicitClear ? { implicitClear: true } : {}),
+ };
+ });
+}
+
+export function runtimeFillFieldsForToggle(
+ field: RuntimeFillField,
+ diffs: readonly RuntimeFillFieldDiff[],
+): RuntimeFillField[] {
+ const fieldDiff = diffs.find((diff) => diff.field === field);
+ const compatibleEndpointFields = RUNTIME_FILL_ENDPOINT_FIELDS.filter((candidate) =>
+ diffs.some(
+ (diff) => diff.field === candidate && diff.targetState !== 'incompatible',
+ ),
+ );
+ const compatibleImplicitFields = RUNTIME_FILL_FIELD_ORDER.filter((candidate) =>
+ diffs.some(
+ (diff) =>
+ diff.field === candidate &&
+ diff.targetState !== 'incompatible' &&
+ diff.implicitClear === true,
+ ),
+ );
+ const isEndpointField = (RUNTIME_FILL_ENDPOINT_FIELDS as readonly RuntimeFillField[]).includes(
+ field,
+ );
+ if (isEndpointField && fieldDiff?.targetState === 'incompatible') return [];
+ if (fieldDiff?.implicitClear === true && compatibleEndpointFields.length === 0) return [];
+ if (isEndpointField || fieldDiff?.implicitClear === true) {
+ return RUNTIME_FILL_FIELD_ORDER.filter(
+ (candidate) =>
+ compatibleEndpointFields.includes(candidate as (typeof RUNTIME_FILL_ENDPOINT_FIELDS)[number]) ||
+ compatibleImplicitFields.includes(candidate),
+ );
+ }
+ return [field];
+}
+
+export function normalizeRuntimeFillSelection(
+ fields: readonly RuntimeFillField[],
+ diffs: readonly RuntimeFillFieldDiff[],
+): RuntimeFillField[] {
+ const selected = new Set(fields);
+ const selectedImplicitClear = diffs.find(
+ (diff) => diff.implicitClear === true && selected.has(diff.field),
+ );
+ if (
+ selectedImplicitClear ||
+ (RUNTIME_FILL_ENDPOINT_FIELDS as readonly RuntimeFillField[]).some((field) =>
+ selected.has(field),
+ )
+ ) {
+ const bundle = runtimeFillFieldsForToggle(selectedImplicitClear?.field ?? 'baseUrl', diffs);
+ if (selectedImplicitClear && bundle.length === 0) {
+ selected.delete(selectedImplicitClear.field);
+ }
+ for (const field of bundle) {
+ selected.add(field);
+ }
+ }
+ return RUNTIME_FILL_FIELD_ORDER.filter(
+ (field) =>
+ selected.has(field) &&
+ diffs.some(
+ (diff) => diff.field === field && diff.targetState !== 'incompatible',
+ ),
+ );
+}
+
+export function runtimeFillHasUnreviewedConflict(
+ previousDiffs: readonly RuntimeFillFieldDiff[],
+ freshDiffs: readonly RuntimeFillFieldDiff[],
+ selectedFields: readonly RuntimeFillField[],
+): boolean {
+ const selected = new Set(selectedFields);
+ const previousState = new Map(previousDiffs.map((diff) => [diff.field, diff.targetState]));
+ return freshDiffs.some(
+ (diff) =>
+ selected.has(diff.field) &&
+ diff.targetState === 'conflict' &&
+ previousState.get(diff.field) !== 'conflict',
+ );
+}
+
+export function runtimeFillSelectedTargetChanged(
+ previousTarget: RuntimeFillDraft,
+ freshTarget: RuntimeFillDraft,
+ selectedFields: readonly RuntimeFillField[],
+ targetAgent: RuntimeFillAgent,
+): boolean {
+ return selectedFields.some(
+ (field) =>
+ JSON.stringify(comparableValue(field, previousTarget, targetAgent)) !==
+ JSON.stringify(comparableValue(field, freshTarget, targetAgent)),
+ );
+}
+
+export function applyRuntimeFillFields(
+ target: RuntimeFillDraft,
+ source: RuntimeFillDraft,
+ fields: readonly RuntimeFillField[],
+ options: { sourceAgent: RuntimeFillAgent; targetAgent: RuntimeFillAgent },
+): RuntimeFillDraft {
+ const selected = new Set(fields);
+ const sourceWire = effectiveWire(options.sourceAgent, source.wireProtocol);
+ const sourceHasHiddenHeaders =
+ runtimeHeaderState(source) != null &&
+ !sourceFieldHasValue('headers', source, options.sourceAgent);
+ // Keep direct callers safe as well as the overlay: changing modelsUrl moves
+ // the credential endpoint, so it must carry the endpoint bundle and any
+ // target headers that Main would clear with that move.
+ if (
+ selected.has('modelsUrl') &&
+ source.modelsUrl.trim() !== target.modelsUrl.trim() &&
+ endpointUrlChanged(source, target)
+ ) {
+ for (const field of RUNTIME_FILL_ENDPOINT_FIELDS) selected.add(field);
+ if (!sourceHasHiddenHeaders && targetFieldHasValue('headers', target, options.targetAgent)) {
+ selected.add('headers');
+ }
+ }
+ const endpointSelected = (RUNTIME_FILL_ENDPOINT_FIELDS as readonly RuntimeFillField[]).some(
+ (field) => selected.has(field),
+ );
+ const endpointCompatible =
+ protocolSupported(options.targetAgent, sourceWire) &&
+ endpointBundleSupported(source, options.sourceAgent, options.targetAgent) &&
+ !sourceHasHiddenHeaders &&
+ !(runtimeHeaderState(target) === 'unknown' && endpointUrlChanged(source, target));
+ const copyableEndpointFields = RUNTIME_FILL_ENDPOINT_FIELDS.filter(
+ (field) =>
+ transferFieldSupported(
+ source,
+ options.sourceAgent,
+ options.targetAgent,
+ field,
+ sourceWire,
+ ),
+ );
+ const copyEndpoint =
+ endpointSelected &&
+ endpointCompatible &&
+ copyableEndpointFields.some((field) => selected.has(field));
+ const copyBaseUrl = copyEndpoint && copyableEndpointFields.includes('baseUrl');
+ const copyRequestPath = copyEndpoint && copyableEndpointFields.includes('requestPath');
+ const copyWireProtocol = copyEndpoint && copyableEndpointFields.includes('wireProtocol');
+ const copyApiKey = selected.has('apiKey') &&
+ (!endpointUrlChanged(source, target) || endpointCompatible) &&
+ (!endpointSelected || copyEndpoint);
+ const clearTargetApiKeyWithEndpoint =
+ copyEndpoint &&
+ target.apiKey.trim().length > 0 &&
+ !selected.has('apiKey');
+ const models = selected.has('models')
+ ? modelsForTarget(source.models, target.models, options.sourceAgent, options.targetAgent)
+ : target.models;
+ const copyHeaders =
+ selected.has('headers') &&
+ !sourceHasHiddenHeaders &&
+ !(runtimeHeaderState(target) === 'unknown' && endpointUrlChanged(source, target)) &&
+ fieldSupported(options.sourceAgent, 'headers', sourceWire) &&
+ fieldSupported(options.targetAgent, 'headers', sourceWire);
+
+ return {
+ baseUrl: copyBaseUrl ? source.baseUrl : target.baseUrl,
+ requestPath:
+ options.targetAgent === 'pi'
+ ? sourceHasHiddenHeaders
+ ? target.requestPath
+ : ''
+ : copyRequestPath
+ ? source.requestPath
+ : target.requestPath,
+ apiKey: copyApiKey
+ ? source.apiKey
+ : clearTargetApiKeyWithEndpoint
+ ? ''
+ : target.apiKey,
+ wireProtocol: copyWireProtocol ? source.wireProtocol : target.wireProtocol,
+ models,
+ headers: copyHeaders ? canonicalHeaders(source.headers) : target.headers,
+ headersState: copyHeaders ? undefined : target.headersState,
+ modelsUrl:
+ selected.has('modelsUrl') &&
+ !sourceHasHiddenHeaders &&
+ !(runtimeHeaderState(target) === 'unknown' && endpointUrlChanged(source, target)) &&
+ fieldSupported(options.sourceAgent, 'modelsUrl', sourceWire) &&
+ fieldSupported(options.targetAgent, 'modelsUrl', sourceWire)
+ ? source.modelsUrl
+ : target.modelsUrl,
+ };
+}
diff --git a/apps/desktop/src/renderer/lib/customProviders.ts b/apps/desktop/src/renderer/lib/customProviders.ts
index e4245aca64..8a46226886 100644
--- a/apps/desktop/src/renderer/lib/customProviders.ts
+++ b/apps/desktop/src/renderer/lib/customProviders.ts
@@ -63,7 +63,9 @@ export function setCustomProviderModelReasoning(
return models.map((model, index) => {
if (index !== targetIndex) return model;
if (!reasoning) {
- const { reasoning: _reasoning, reasoningEfforts: _reasoningEfforts, ...rest } = model;
+ const rest = { ...model };
+ delete rest.reasoning;
+ delete rest.reasoningEfforts;
return rest;
}
return {
@@ -147,6 +149,7 @@ export function providerViewToCustomProviderConfig(p: ProviderView): CustomProvi
...(routing?.headerOverride && Object.keys(routing.headerOverride).length > 0
? { headers: { ...routing.headerOverride } }
: {}),
+ ...(routing?.headerOverrideState ? { headersState: routing.headerOverrideState } : {}),
...(routing?.modelsUrl ? { modelsUrl: routing.modelsUrl } : {}),
};
}
@@ -189,21 +192,18 @@ export function appendDiscoveredCustomProviderModels(
}
/**
- * 读取该自定义供应商**某 runtime** 本机已存的明文密钥(用户自己的 key);无 / 读失败返回 null。
+ * 读取该自定义供应商**某 runtime** 本机已存的明文密钥(用户自己的 key);无密钥返回 null,
+ * IPC 读取失败则向调用方抛出,避免把“无法读取”误当成“没有密钥”。
* 用于编辑态回填(「能看」)与已保存探测。明文仅在 renderer 本地用于回显 / 核对,不外发。
*/
export async function readCustomProviderKey(
providerId: string,
agent: AgentKind,
): Promise<string | null> {
- try {
- const v = await window.electronAPI.safeStorageRead(
- customProviderSecretStorageKey(providerId, agent),
- );
- return v && v.length > 0 ? v : null;
- } catch {
- return null;
- }
+ const value = await window.electronAPI.safeStorageRead(
+ customProviderSecretStorageKey(providerId, agent),
+ );
+ return value && value.length > 0 ? value : null;
}
// 鉴权请求头是 main-only 密文(isRendererAccessibleSafeStorageKey 明确拒 provider_headers_
diff --git a/apps/desktop/src/renderer/lib/providerModelFetch.ts b/apps/desktop/src/renderer/lib/providerModelFetch.ts
index dcbc5a3006..33a8964345 100644
--- a/apps/desktop/src/renderer/lib/providerModelFetch.ts
+++ b/apps/desktop/src/renderer/lib/providerModelFetch.ts
@@ -109,7 +109,8 @@ function headerRowsEqual(
* 由 main 侧以 renderer 值优先覆盖,这里只决定「是否附带 savedProviderId」。
*/
export function modelFetchCanReuseSavedCredentials(
- form: Pick<ProviderModelFetchSignatureFields, 'baseUrl' | 'modelsUrl'>,
+ form: Pick<ProviderModelFetchSignatureFields, 'baseUrl' | 'modelsUrl'> &
+ Partial<Pick<ProviderModelFetchSignatureFields, 'requestPath'>>,
baseline: Pick<SavedProviderProbeBaseline, 'baseUrl' | 'modelsUrl' | 'authMode'>,
authMode: CustomProviderAuthMode,
): boolean {
@@ -120,6 +121,52 @@ export function modelFetchCanReuseSavedCredentials(
);
}
+/**
+ * Restore an untouched hydrated key after an endpoint edit is reverted to the
+ * saved base/models target. Explicit key edits always win, including clearing
+ * the field, so this helper only fills an actually empty, revision-zero draft.
+ */
+export function restoreHydratedApiKey<
+ T extends Pick<ProviderModelFetchSignatureFields, 'baseUrl' | 'modelsUrl' | 'apiKey'>,
+>(
+ form: T,
+ baseline: Pick<SavedProviderProbeBaseline, 'baseUrl' | 'modelsUrl' | 'authMode' | 'apiKey'>,
+ authMode: CustomProviderAuthMode,
+ keyEditRevision: number,
+): T {
+ if (
+ authMode !== 'apiKey' ||
+ keyEditRevision !== 0 ||
+ form.apiKey.trim() ||
+ !baseline.apiKey.trim() ||
+ !modelFetchCanReuseSavedCredentials(form, baseline, authMode)
+ ) {
+ return form;
+ }
+ return { ...form, apiKey: baseline.apiKey };
+}
+
+/**
+ * Decide whether a hydrated API key may be sent to the saved provider's endpoint.
+ * requestPath is a routing detail within the same base/models URL and does not
+ * change the credential target; baseUrl/modelsUrl changes still require an edit.
+ */
+export function canSendHydratedApiKey(
+ form: Pick<ProviderModelFetchSignatureFields, 'baseUrl' | 'modelsUrl'> &
+ Partial<Pick<ProviderModelFetchSignatureFields, 'requestPath'>>,
+ baseline: Pick<SavedProviderProbeBaseline, 'baseUrl' | 'modelsUrl' | 'authMode'> &
+ Partial<Pick<SavedProviderProbeBaseline, 'requestPath'>>,
+ authMode: CustomProviderAuthMode,
+ keyEditRevision: number,
+): boolean {
+ if (keyEditRevision > 0) return true;
+ return (
+ authMode === baseline.authMode &&
+ form.baseUrl.trim() === baseline.baseUrl.trim() &&
+ form.modelsUrl.trim() === baseline.modelsUrl.trim()
+ );
+}
+
/**
* 测试连接是否走「已存供应商」受控探测(kind:'saved')。saved 探测整体按已存 spec 发起,
* 能带上不回读进表单的 main-only 密文头;但它用的是已存端点/模型/凭证,所以只有当编辑态
diff --git a/apps/desktop/src/shared/providerSecrets.ts b/apps/desktop/src/shared/providerSecrets.ts
index 1a995a889f..3dfb5edfa1 100644
--- a/apps/desktop/src/shared/providerSecrets.ts
+++ b/apps/desktop/src/shared/providerSecrets.ts
@@ -124,6 +124,12 @@ export function customProviderSecretStorageKey(providerId: string, agent: string
return `provider_key_${providerId}_${agent}`;
}
+const CUSTOM_PROVIDER_RUNTIME_KEY_RE = /^provider_key_[a-zA-Z0-9_-]+_(?:claude-code|codex|pi)$/;
+
+export function isCustomProviderRuntimeKeyStorageKey(storageKey: unknown): boolean {
+ return typeof storageKey === 'string' && CUSTOM_PROVIDER_RUNTIME_KEY_RE.test(storageKey);
+}
+
/**
* Main-only encrypted blob containing all custom headers for one provider runtime.
* Header values are never persisted in the custom_providers SQLite row.
diff --git a/packages/model-providers/src/__tests__/user-provider.test.ts b/packages/model-providers/src/__tests__/user-provider.test.ts
index ae421af9c9..86f8972a12 100644
--- a/packages/model-providers/src/__tests__/user-provider.test.ts
+++ b/packages/model-providers/src/__tests__/user-provider.test.ts
@@ -175,6 +175,7 @@ describe('buildUserProvider (per-runtime)', () => {
runtimes: { codex: { ...codexOnly.runtimes.codex!, headers: { 'X-Org': 'acme' } } },
});
expect(p.routing.codex?.headerOverride).toEqual({ 'X-Org': 'acme' });
+ expect(p.routing.codex?.headerOverrideState).toBe('configured');
});
it('carries modelsUrl into routing (edit-form round-trip), absent when unset', () => {
diff --git a/packages/model-providers/src/types.ts b/packages/model-providers/src/types.ts
index b55e164e11..93d910c530 100644
--- a/packages/model-providers/src/types.ts
+++ b/packages/model-providers/src/types.ts
@@ -175,6 +175,7 @@ export interface RoutingDescriptor {
headerDelete?: string[];
/** 额外固定请求头覆盖(少数特例用;多数由 authStrategy 隐含)。 */
headerOverride?: Record<string, string>;
+ headerOverrideState?: 'configured' | 'unknown';
/** 可选 quirk 适配钩子名(对齐 OpenCode custom loader,承接无法纯数据表达的特例)。 */
adapter?: string;
/**
@@ -594,6 +595,8 @@ export interface CustomProviderRuntimeConfig {
* custom_providers SQLite,也不通过非可信 / 远程 provider:list 返回。
*/
headers?: Record<string, string>;
+ /** Transient non-secret state; main normalization strips it before persistence. */
+ headersState?: 'configured' | 'unknown';
/**
* 可选的「列模型」端点(「获取模型列表」按钮用;缺省由 baseUrl 推导 `…/v1/models`)。
* 从预设创建时随 `ProviderPresetRuntime.modelsUrl` 快照进来并持久化,编辑态仍可再拉。
diff --git a/packages/model-providers/src/user-provider.ts b/packages/model-providers/src/user-provider.ts
index 146bdd4b15..8b8c44ca42 100644
--- a/packages/model-providers/src/user-provider.ts
+++ b/packages/model-providers/src/user-provider.ts
@@ -97,6 +97,7 @@ function toRouting(
baseUrl: string,
requestPath: string | undefined,
headers: Record<string, string> | undefined,
+ headersState: 'configured' | 'unknown' | undefined,
strategy: 'api-key-header' | 'oauth-token' | 'none',
modelsUrl?: string,
wireProtocol?: 'anthropic-messages' | 'openai-responses' | 'openai-chat',
@@ -112,7 +113,12 @@ function toRouting(
...(requestPath ? { requestPath } : {}),
...(wireProtocol && wireProtocol !== defaultWireProtocol(agent) ? { wireProtocol } : {}),
};
- if (headers && Object.keys(headers).length > 0) r.headerOverride = { ...headers };
+ if (headers && Object.keys(headers).length > 0) {
+ r.headerOverride = { ...headers };
+ r.headerOverrideState = 'configured';
+ } else if (headersState === 'unknown') {
+ r.headerOverrideState = 'unknown';
+ }
// 列模型端点回带(编辑表单从 routing 重建配置时不丢;路由器不消费本字段)。
if (modelsUrl) r.modelsUrl = modelsUrl;
return r;
@@ -141,6 +147,7 @@ export function buildUserProvider(config: CustomProviderConfig): Provider {
rt.baseUrl,
rt.requestPath,
rt.headers,
+ rt.headersState,
strategy,
rt.modelsUrl,
rt.wireProtocol,